diff --git a/.github/workflows/auto-fix-failed-tests.yml b/.github/workflows/auto-fix-failed-tests.yml index fe438a460..6618594bd 100644 --- a/.github/workflows/auto-fix-failed-tests.yml +++ b/.github/workflows/auto-fix-failed-tests.yml @@ -97,7 +97,7 @@ jobs: - name: Setup Node.js if: steps.workflow-details.outputs.has_failed_tests == 'true' - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: "20" diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index 192ebb612..b80253417 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -24,7 +24,7 @@ jobs: token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 registry-url: "https://registry.npmjs.org" diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 93922dd31..2265efec9 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -25,7 +25,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 cache: "npm" @@ -67,7 +67,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: ${{ matrix.node-version }} diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 7e44fff65..72e555f5f 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -104,7 +104,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" cache: "npm" diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 7efead1fb..34611923f 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -3,7 +3,7 @@ name: Continue General Review on: push: branches: - - nate/fix-wf + - main pull_request: types: [opened, ready_for_review] issue_comment: @@ -25,4 +25,4 @@ jobs: with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" - continue-config: "continuedev/review-bot" + continue-agent: "empty-agent" diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 9c33c822c..54f617534 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -152,7 +152,7 @@ jobs: # # Setup Node.js - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -370,7 +370,7 @@ jobs: # 2. Install npm dependencies - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 041ff53ca..cd4e96d06 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -86,7 +86,7 @@ jobs: with: fetch-depth: 0 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 0155bbfb4..8e1a63386 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -229,7 +229,7 @@ jobs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index fa24eb2bf..6f82464b5 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -70,7 +70,7 @@ jobs: with: fetch-depth: 0 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -165,7 +165,7 @@ jobs: # 4. Create PR with version bump - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index e763aa04c..21986c0f3 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -59,7 +59,7 @@ jobs: uses: ./.github/actions/setup-packages - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/run-continue-agent.yml b/.github/workflows/run-continue-agent.yml index fcc49903b..c98cf963a 100644 --- a/.github/workflows/run-continue-agent.yml +++ b/.github/workflows/run-continue-agent.yml @@ -7,8 +7,8 @@ on: description: "The prompt to send to the Continue agent" required: true type: string - agent: - description: "The agent to use (e.g., continuedev/default-background-agent)" + config: + description: "The config to use (e.g., continuedev/default-background-agent)" required: false type: string default: "continuedev/default-background-agent" @@ -33,7 +33,7 @@ jobs: -H "Authorization: Bearer ${{ secrets.CONTINUE_API_KEY }}" \ -d '{ "prompt": "${{ inputs.prompt }}", - "agent": "${{ inputs.agent }}", + "config": "${{ inputs.config }}", "branchName": "${{ inputs.branch_name }}", "repoUrl": "https://github.com/${{ github.repository }}" }') diff --git a/.github/workflows/snyk-agent.yaml b/.github/workflows/snyk-agent.yaml new file mode 100644 index 000000000..969c43907 --- /dev/null +++ b/.github/workflows/snyk-agent.yaml @@ -0,0 +1,31 @@ +name: Daily Snyk Agent + +on: + schedule: + # Runs at 9:00 AM UTC every day + - cron: "0 9 * * *" + workflow_dispatch: # Allows manual triggering + +jobs: + run-cn-task: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "20" + + - name: Install Continue CLI globally + run: npm install -g @continuedev/cli@latest + + - name: Run Snyk Agent + run: cd extensions/cli && cn -p --agent continuedev/snyk-code-scan-agent "The current directory" + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index c24abf8f8..b21f52eb1 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -40,7 +40,7 @@ jobs: token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 registry-url: "https://registry.npmjs.org" diff --git a/.github/workflows/tidy-up-codebase.yml b/.github/workflows/tidy-up-codebase.yml index a6fa6c688..729998a28 100644 --- a/.github/workflows/tidy-up-codebase.yml +++ b/.github/workflows/tidy-up-codebase.yml @@ -11,7 +11,7 @@ jobs: uses: ./.github/workflows/run-continue-agent.yml with: prompt: "Review every Markdown documentation file and verify that descriptions, examples, or behavior outlines accurately reflect the current code. Only update documentation; do not modify code. Check the corresponding code to confirm behavior before making changes. Correct any inaccuracies or outdated information in descriptions, examples, or behavior outlines. Preserve existing Markdown formatting, style, and structure. Do not add new sections, speculative explanations, or details not present in the code. Only update statements that are clearly incorrect or misleading; do not rewrite text for style or preference. Keep edits minimal and focused, ensuring that the Markdown matches what the code actually does. If verification against the code is ambiguous, leave the documentation unchanged. Use branch name bot/cleanup--" - agent: continuedev/default-background-agent + config: continuedev/default-background-agent branch_name: main secrets: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} diff --git a/.github/workflows/vscode-prerelease.yml b/.github/workflows/vscode-prerelease.yml index a2c4b8208..2d4ed94d6 100644 --- a/.github/workflows/vscode-prerelease.yml +++ b/.github/workflows/vscode-prerelease.yml @@ -29,7 +29,7 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index dbf258f35..ba3ea08c4 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -21,7 +21,7 @@ jobs: gh auth login --with-token <<< "${{ github.token }}" - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index 0e0387c6f..d5e6a7b17 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -9,8 +9,8 @@ inputs: continue-org: description: "Organization for Continue config" required: true - continue-config: - description: 'Config path to use (e.g., "myorg/review-bot")' + continue-agent: + description: 'Agent path to use (e.g., "myorg/review-bot")' required: true runs: @@ -20,44 +20,89 @@ runs: uses: actions/checkout@v4 - name: Check Authorization - shell: bash - env: - # Only move the dangerous check to env to prevent shell injection - HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-review') }} - run: | - # Check if this action should run based on event type and user permissions - SHOULD_RUN="false" + id: auth-check + uses: actions/github-script@v7 + with: + script: | + let shouldRun = false; + let skipReason = ''; - if [ "${{ github.event_name }}" = "pull_request" ]; then - # Check if PR is a draft - if [ "${{ github.event.pull_request.draft }}" = "true" ]; then - echo "::notice::Skipping review - PR is a draft" - else - # Check PR author association - AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" - if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" - fi - fi - elif [ "${{ github.event_name }}" = "issue_comment" ]; then - # Check if it's a PR comment with the trigger phrase - if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then - COMMENTER_ASSOC="${{ github.event.comment.author_association }}" - if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)" - fi - else - echo "::notice::Skipping review - Comment does not contain @continue-review trigger, or is not on a PR" - fi - else - echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}" - fi + if (context.eventName === 'pull_request') { + // Check if PR is a draft + if (context.payload.pull_request.draft) { + skipReason = 'PR is a draft'; + } else { + // Check if user has write permission (includes admin, maintain, write) + const prAuthor = context.payload.pull_request.user.login; + try { + const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: prAuthor + }); + + const allowedPermissions = ['admin', 'maintain', 'write']; + if (allowedPermissions.includes(permission.permission)) { + shouldRun = true; + console.log(`PR author @${prAuthor} has ${permission.permission} permission`); + } else { + skipReason = `PR author @${prAuthor} does not have write permission (has: ${permission.permission})`; + } + } catch (error) { + // If API call fails, fall back to checking author_association + const association = context.payload.pull_request.author_association; + const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR']; + if (allowedAssociations.includes(association)) { + shouldRun = true; + console.log(`PR author @${prAuthor} association: ${association}`); + } else { + skipReason = `PR author @${prAuthor} is not a team member (association: ${association})`; + } + } + } + } else if (context.eventName === 'issue_comment') { + // Check if it's a PR comment with the trigger phrase + const hasTrigger = context.payload.comment.body.includes('@continue-review'); + if (context.payload.issue.pull_request && hasTrigger) { + const commenter = context.payload.comment.user.login; + try { + const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: commenter + }); + + const allowedPermissions = ['admin', 'maintain', 'write']; + if (allowedPermissions.includes(permission.permission)) { + shouldRun = true; + console.log(`Commenter @${commenter} has ${permission.permission} permission`); + } else { + skipReason = `Commenter @${commenter} does not have write permission (has: ${permission.permission})`; + } + } catch (error) { + // If API call fails, fall back to checking author_association + const association = context.payload.comment.author_association; + const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR']; + if (allowedAssociations.includes(association)) { + shouldRun = true; + console.log(`Commenter @${commenter} association: ${association}`); + } else { + skipReason = `Commenter @${commenter} is not a team member (association: ${association})`; + } + } + } else { + skipReason = 'Comment does not contain @continue-review trigger, or is not on a PR'; + } + } else { + skipReason = `Unsupported event type: ${context.eventName}`; + } - echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV + if (skipReason) { + core.notice(`Skipping review - ${skipReason}`); + } + + core.exportVariable('SHOULD_RUN', shouldRun.toString()); + return shouldRun; - name: Setup Node.js if: env.SHOULD_RUN == 'true' @@ -68,7 +113,7 @@ runs: - name: Install Continue CLI if: env.SHOULD_RUN == 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.30 + run: npm install -g @continuedev/cli@latest - name: Post Initial Comment if: env.SHOULD_RUN == 'true' @@ -182,7 +227,7 @@ runs: env: CONTINUE_API_KEY: ${{ inputs.continue-api-key }} CONTINUE_ORG: ${{ inputs.continue-org }} - CONTINUE_CONFIG: ${{ inputs.continue-config }} + CONTINUE_AGENT: ${{ inputs.continue-agent }} GITHUB_TOKEN: ${{ github.token }} run: | echo "Running Continue CLI with prompt:" @@ -208,7 +253,7 @@ runs: exit 1 fi - if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then + if [[ ! "$CONTINUE_AGENT" =~ ^[a-zA-Z0-9_/-]+$ ]]; then echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes." exit 1 fi @@ -228,7 +273,7 @@ runs: # Run the CLI with validated config and error handling if [ "$SKIP_CLI" != "true" ]; then - echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_AGENT" # Write prompt to temp file for headless mode PROMPT_FILE="/tmp/continue-review-$RANDOM.txt" @@ -237,9 +282,9 @@ runs: echo "Prompt length: $(wc -c < "$PROMPT_FILE") characters" # Use timeout to prevent hanging (360 seconds = 6 minutes) - echo "Executing command: cn --config $CONTINUE_ORG/$CONTINUE_CONFIG -p @$PROMPT_FILE --allow Bash" + echo "Executing command: cn --agent $CONTINUE_ORG/$CONTINUE_AGENT -p @$PROMPT_FILE --allow Bash" - if timeout 360 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then + if timeout 360 cn --agent "$CONTINUE_ORG/$CONTINUE_AGENT" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then echo "Continue CLI completed successfully" echo "Raw output length: $(wc -c < code_review_raw.md) characters" diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 28e617f79..f23666165 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -307,7 +307,11 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ { toolCall: ToolCall }, - { contextItems: ContextItem[]; errorMessage?: string }, + { + contextItems: ContextItem[]; + errorMessage?: string; + errorReason?: ContinueErrorReason; + }, ]; "tools/evaluatePolicy": [ { toolName: string; basePolicy: ToolPolicy; args: Record }, diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index faec8a94b..8d695e1e1 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,6 +1,7 @@ import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; +import { ContinueError, ContinueErrorReason } from "../util/errors"; import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; @@ -197,6 +198,7 @@ export async function callTool( ): Promise<{ contextItems: ContextItem[]; errorMessage: string | undefined; + errorReason?: ContinueErrorReason; }> { try { const args = safeParseToolCallArgs(toolCall); @@ -214,12 +216,19 @@ export async function callTool( }; } catch (e) { let errorMessage = `${e}`; - if (e instanceof Error) { + let errorReason: ContinueErrorReason | undefined; + + if (e instanceof ContinueError) { + errorMessage = e.message; + errorReason = e.reason; + } else if (e instanceof Error) { errorMessage = e.message; } + return { contextItems: [], errorMessage, + errorReason, }; } } diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index 0677e7dcd..dca307d99 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -3,6 +3,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; import { getStringArg } from "../parseArgs"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); @@ -15,7 +16,8 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { if (resolvedFileUri) { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileAlreadyExists, `File ${filepath} already exists. Use the edit tool to edit this file`, ); } @@ -37,6 +39,9 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { }, ]; } else { - throw new Error("Failed to resolve path"); + throw new ContinueError( + ContinueErrorReason.PathResolutionFailed, + "Failed to resolve path", + ); } }; diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index 727b5c560..69ccf6aac 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,5 +1,6 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { formatGrepSearchResults } from "../../util/grepSearch"; import { prepareQueryForRipgrep } from "../../util/regexValidator"; import { getStringArg } from "../parseArgs"; @@ -63,7 +64,10 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ]; } - throw error; + throw new ContinueError( + ContinueErrorReason.SearchExecutionFailed, + errorMessage, + ); } const { formatted, numResults, truncated } = formatGrepSearchResults( diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts index a02f28065..c8c753060 100644 --- a/core/tools/implementations/lsTool.ts +++ b/core/tools/implementations/lsTool.ts @@ -3,6 +3,7 @@ import ignore from "ignore"; import { ToolImpl } from "."; import { walkDir } from "../../indexing/walkDir"; import { resolveInputPath } from "../../util/pathResolver"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export function resolveLsToolDirPath(dirPath: string | undefined) { if (!dirPath || dirPath === ".") { @@ -21,7 +22,8 @@ export const lsToolImpl: ToolImpl = async (args, extras) => { const dirPath = resolveLsToolDirPath(args?.dirPath); const resolvedPath = await resolveInputPath(extras.ide, dirPath); if (!resolvedPath) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.DirectoryNotFound, `Directory ${args.dirPath} not found or is not accessible. You can use absolute paths, relative paths, or paths starting with ~`, ); } diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index 67bf168d0..6c55912ee 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -5,6 +5,7 @@ import { ToolImpl } from "."; import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; import { getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const readFileImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); @@ -12,7 +13,8 @@ export const readFileImpl: ToolImpl = async (args, extras) => { // Resolve the path first to get the actual path for security check const resolvedPath = await resolveInputPath(extras.ide, filepath); if (!resolvedPath) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileNotFound, `File "${filepath}" does not exist or is not accessible. You might want to check the path and try again.`, ); } diff --git a/core/tools/implementations/readFileLimit.ts b/core/tools/implementations/readFileLimit.ts index e2af14d56..48f4b9f86 100644 --- a/core/tools/implementations/readFileLimit.ts +++ b/core/tools/implementations/readFileLimit.ts @@ -1,5 +1,6 @@ import { ILLM } from "../.."; import { countTokensAsync } from "../../llm/countTokens"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export async function throwIfFileExceedsHalfOfContext( filepath: string, @@ -10,7 +11,8 @@ export async function throwIfFileExceedsHalfOfContext( const tokens = await countTokensAsync(content, model.title); const tokenLimit = model.contextLength / 2; if (tokens > tokenLimit) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileTooLarge, `File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`, ); } diff --git a/core/tools/implementations/readFileRange.ts b/core/tools/implementations/readFileRange.ts index 4c274e8c7..7b5f47338 100644 --- a/core/tools/implementations/readFileRange.ts +++ b/core/tools/implementations/readFileRange.ts @@ -5,6 +5,7 @@ import { ToolImpl } from "."; import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; import { getNumberArg, getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const readFileRangeImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); @@ -13,17 +14,20 @@ export const readFileRangeImpl: ToolImpl = async (args, extras) => { // Validate that line numbers are positive integers if (startLine < 1) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, "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( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, "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( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, ); } @@ -31,7 +35,8 @@ export const readFileRangeImpl: ToolImpl = async (args, extras) => { // Resolve the path first to get the actual path for security check const resolvedPath = await resolveInputPath(extras.ide, filepath); if (!resolvedPath) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileNotFound, `File "${filepath}" does not exist or is not accessible. You might want to check the path and try again.`, ); } diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index c5c312e70..21ee86af8 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -1,4 +1,5 @@ import { ToolImpl } from "."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { getStringArg } from "../parseArgs"; export const requestRuleImpl: ToolImpl = async (args, extras) => { @@ -8,7 +9,10 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { const rule = extras.config.rules.find((r) => r.name === name); if (!rule || !rule.sourceFile) { - throw new Error(`Rule with name "${name}" not found or has no file path`); + throw new ContinueError( + ContinueErrorReason.RuleNotFound, + `Rule with name "${name}" not found or has no file path`, + ); } return [ diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index cccf3353b..15b1dc1bf 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -2,6 +2,7 @@ import iconv from "iconv-lite"; import childProcess from "node:child_process"; import os from "node:os"; import util from "node:util"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; // Automatically decode the buffer according to the platform to avoid garbled Chinese function getDecodedOutput(data: Buffer): string { if (process.platform === "win32") { @@ -337,7 +338,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (code === 0) { resolve({ stdout, stderr }); } else { - const error = new Error( + const error = new ContinueError( + ContinueErrorReason.CommandExecutionFailed, `Command failed with exit code ${code}`, ); (error as any).stderr = stderr; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index be421f5c6..8a709a8a0 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -2,6 +2,7 @@ import generateRepoMap from "../../util/generateRepoMap"; import { resolveInputPath } from "../../util/pathResolver"; import { ToolImpl } from "."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { getStringArg } from "../parseArgs"; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { @@ -10,7 +11,8 @@ export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { const resolvedPath = await resolveInputPath(extras.ide, directory_path); if (!resolvedPath) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.DirectoryNotFound, `Directory path "${directory_path}" does not exist or is not accessible.`, ); } diff --git a/core/util/errors.ts b/core/util/errors.ts index 4c6cfb16d..69df7c814 100644 --- a/core/util/errors.ts +++ b/core/util/errors.ts @@ -47,6 +47,20 @@ export enum ContinueErrorReason { FileWriteError = "file_write_error", FileIsSecurityConcern = "file_is_security_concern", ParentDirectoryNotFound = "parent_directory_not_found", + FileTooLarge = "file_too_large", + PathResolutionFailed = "path_resolution_failed", + InvalidLineNumber = "invalid_line_number", + DirectoryNotFound = "directory_not_found", + + // Terminal/Command execution + CommandExecutionFailed = "command_execution_failed", + CommandNotAvailableInRemote = "command_not_available_in_remote", + + // Search + SearchExecutionFailed = "search_execution_failed", + + // Rules + RuleNotFound = "rule_not_found", // Other Unspecified = "unspecified", // I.e. a known error but no specific code for it diff --git a/core/util/index.test.ts b/core/util/index.test.ts index fc48a49b2..a77473c25 100644 --- a/core/util/index.test.ts +++ b/core/util/index.test.ts @@ -1,9 +1,9 @@ // File generated by Continue import { + copyOf, dedent, dedentAndGetCommonWhitespace, deduplicateArray, - copyOf, getMarkdownLanguageTagForFile, removeCodeBlocksAndTrim, removeQuotesAndEscapes, @@ -463,4 +463,30 @@ describe("removeCodeBlocksAndTrim", () => { const output = removeCodeBlocksAndTrim(text); expect(output).toBe(""); }); + it("should remove think blocks from text", () => { + const text = + "Okay, the user wants me to help with...Here is my actual response."; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Here is my actual response."); + }); + + it("should remove both code blocks and think blocks", () => { + const text = + "Let me plan this...Here's some code:\n```javascript\nconsole.log('hello');\n```\nThat should work!"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Here's some code:\n\nThat should work!"); + }); + + it("should handle multiple think blocks", () => { + const text = + "First thoughtSome textSecond thoughtMore text"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Some textMore text"); + }); + + it("should handle think blocks with newlines", () => { + const text = "\nMultiline\nthinking\n\nActual response"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Actual response"); + }); }); diff --git a/core/util/index.ts b/core/util/index.ts index 4b3b17535..76b319bdd 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -197,11 +197,13 @@ export function dedent(strings: TemplateStringsArray, ...values: any[]) { */ export function removeCodeBlocksAndTrim(text: string): string { const codeBlockRegex = /```[\s\S]*?```/g; + const thinkBlockRegex = /[\s\S]*?<\/think>/g; - // Remove code blocks from the message text - const textWithoutCodeBlocks = text.replace(codeBlockRegex, ""); + // Remove code blocks and think blocks from the message text + let processedText = text.replace(codeBlockRegex, ""); + processedText = processedText.replace(thinkBlockRegex, ""); - return textWithoutCodeBlocks.trim(); + return processedText.trim(); } export function splitCamelCaseAndNonAlphaNumeric(value: string) { diff --git a/core/util/paths.ts b/core/util/paths.ts index de587cf0d..122ec2f94 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -14,6 +14,16 @@ import Types from "../config/types"; dotenv.config(); +export function setConfigFilePermissions(filePath: string): void { + try { + if (os.platform() !== "win32") { + fs.chmodSync(filePath, 0o600); + } + } catch (error) { + console.warn(`Failed to set permissions on ${filePath}:`, error); + } +} + const CONTINUE_GLOBAL_DIR = (() => { const configPath = process.env.CONTINUE_GLOBAL_DIR; if (configPath) { @@ -117,6 +127,7 @@ export function getConfigYamlPath(ideType?: IdeType): string { } else { fs.writeFileSync(p, YAML.stringify(defaultConfig)); } + setConfigFilePermissions(p); } return p; } @@ -255,12 +266,14 @@ function editConfigJson( } function editConfigYaml(callback: (config: ConfigYaml) => ConfigYaml): void { - const config = fs.readFileSync(getConfigYamlPath(), "utf8"); + const configPath = getConfigYamlPath(); + const config = fs.readFileSync(configPath, "utf8"); let configYaml = YAML.parse(config); // Check if it's an object if (typeof configYaml === "object" && configYaml !== null) { configYaml = callback(configYaml as any) as any; - fs.writeFileSync(getConfigYamlPath(), YAML.stringify(configYaml)); + fs.writeFileSync(configPath, YAML.stringify(configYaml)); + setConfigFilePermissions(configPath); } else { console.warn("config.yaml is not a valid object"); } diff --git a/docs/docs.json b/docs/docs.json index 46920f129..5f7f30add 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -3,7 +3,7 @@ "theme": "mint", "name": "Continue", "banner": { - "content": "Continue CLI v1.4.49 is live 🚀 Learn how you can [leverage the CLI with our MCP Cookbooks](/guides/overview#mcp-integration-cookbooks)", + "content": "Continue CLI v1.5.1 is live 🚀 Learn how you can leverage the CLI with our [MCP Cookbooks](https://docs.continue.dev/guides/overview#mcp-integration-cookbooks)", "dismissable": true }, "colors": { diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 7ab691886..5ee422523 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -10234,9 +10234,9 @@ } }, "node_modules/happy-dom": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.0.0.tgz", - "integrity": "sha512-GkWnwIFxVGCf2raNrxImLo397RdGhLapj5cT3R2PT7FwL62Ze1DROhzmYW7+J3p9105DYMVenEejEbnq5wA37w==", + "version": "20.0.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.0.2.tgz", + "integrity": "sha512-pYOyu624+6HDbY+qkjILpQGnpvZOusItCk+rvF5/V+6NkcgTKnbOldpIy22tBnxoaLtlM9nXgoqAcW29/B7CIw==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts index a8025a4d7..9a9c9f3f5 100644 --- a/extensions/cli/src/commands/remote.test.ts +++ b/extensions/cli/src/commands/remote.test.ts @@ -353,7 +353,32 @@ describe("remote command", () => { expect(mockFetch).toHaveBeenCalledWith( new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ - body: expect.stringContaining(`"agent":"${testConfig}"`), + body: expect.stringContaining(`"config":"${testConfig}"`), + }), + ); + }); + + it("should include agent in request body when agent option is provided", async () => { + const testAgent = "test-agent"; + + await remote("test prompt", { agent: testAgent }); + + 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(`"agent":"${testAgent}"`), + }), + ); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents", mockEnv.env.apiBase), + expect.objectContaining({ + body: expect.stringContaining(`"agent":"${testAgent}"`), }), ); }); @@ -375,11 +400,31 @@ describe("remote command", () => { name: expect.stringMatching(/^devbox-\d+$/), prompt: "test prompt", idempotencyKey: testIdempotencyKey, - agent: testConfig, config: testConfig, }); }); + it("should handle proper request body structure with agent field", async () => { + const testAgent = "my-agent"; + const testIdempotencyKey = "test-with-config"; + + await remote("test prompt", { + agent: testAgent, + 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: testAgent, + }); + }); + it("should not include config in request body when config option is not provided", async () => { await remote("test prompt", {}); diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index 919c720fd..040afa1b1 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -21,6 +21,7 @@ type RemoteCommandOptions = { branch?: string; repo?: string; config?: string; + agent?: string; }; type TunnelResponse = { @@ -169,7 +170,7 @@ function buildAgentRequestBody( repoUrl: options.repo ?? getRepoUrl(), name: `devbox-${Date.now()}`, prompt, - agent: options.config, + agent: options.agent, config: options.config, }; diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts deleted file mode 100644 index 75fc33a85..000000000 --- a/extensions/cli/src/configEnhancer.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "./configEnhancer.js"; - -// Mock processRule to simulate hub loading -vi.mock("./hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // 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 agent file state -vi.mock("./services/ServiceContainer.js", () => ({ - serviceContainer: { - get: vi.fn(() => - Promise.resolve({ - agentFileService: null, - agentFileModelName: null, - agentFile: null, - slug: null, - }), - ), - }, -})); - -vi.mock("./services/types.js", () => ({ - SERVICE_NAMES: { - AGENT_FILE: "agentFile", - }, -})); - -describe("ConfigEnhancer", () => { - let enhancer: ConfigEnhancer; - let mockConfig: any; - - beforeEach(() => { - enhancer = new ConfigEnhancer(); - mockConfig = { - name: "test-config", - version: "1.0.0", - models: [], - mcpServers: [], - } as any; - vi.clearAllMocks(); - }); - - it("should return unchanged config when no enhancements provided", async () => { - const config = await enhancer.enhanceConfig(mockConfig, {}); - - expect(config).toEqual(mockConfig); - }); - - it("should apply rules enhancement", async () => { - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["test-rule"]); - }); - - it("should apply multiple enhancements", async () => { - const options: BaseCommandOptions = { - rule: ["rule1", "rule2"], - mcp: [], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["rule1", "rule2"]); - }); - - it("should preserve existing rules when adding new ones", async () => { - mockConfig.rules = ["existing rule"]; - const options: BaseCommandOptions = { - rule: ["new rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["existing rule", "new rule"]); - }); - - it("should not mutate original config", async () => { - const originalConfig = { ...mockConfig }; - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - await enhancer.enhanceConfig(mockConfig, options); - - expect(mockConfig).toEqual(originalConfig); - }); - - it("should preserve hub slug as rule name", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(1); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - }); - - it("should handle mix of hub slugs and direct content", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish", "Always be helpful", "org/another-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(3); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - expect(config.rules?.[1]).toBe("Always be helpful"); - expect(config.rules?.[2]).toEqual({ - name: "org/another-rule", - rule: "Content for org/another-rule", - }); - }); - - it("should treat file paths as plain strings", async () => { - const options: BaseCommandOptions = { - rule: ["./rules/my-rule.md", "/absolute/path/rule.txt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(2); - // File paths should be stored as plain strings - expect(config.rules?.[0]).toBe("./rules/my-rule.md"); - expect(config.rules?.[1]).toBe("/absolute/path/rule.txt"); - }); - - it("should prepend models from --model flag to make them default", async () => { - // Mock loadPackagesFromHub to return test models - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "GPT-5", provider: "openai", model: "gpt-5" }, - { name: "Claude-3", provider: "anthropic", model: "claude-3" }, - ]); - - // Set up existing models in config - mockConfig.models = [ - { name: "GPT-4", provider: "openai", model: "gpt-4" }, - { name: "Claude-2", provider: "anthropic", model: "claude-2" }, - ]; - - const options: BaseCommandOptions = { - model: ["openai/gpt-5", "anthropic/claude-3"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // Models from --model flag should be prepended (at the start) - expect(config.models).toHaveLength(4); - expect(config.models?.[0]).toEqual({ - name: "GPT-5", - provider: "openai", - model: "gpt-5", - }); - expect(config.models?.[1]).toEqual({ - name: "Claude-3", - provider: "anthropic", - model: "claude-3", - }); - expect(config.models?.[2]).toEqual({ - name: "GPT-4", - provider: "openai", - model: "gpt-4", - }); - expect(config.models?.[3]).toEqual({ - name: "Claude-2", - provider: "anthropic", - model: "claude-2", - }); - }); - - it("should prepend MCPs from --mcp flag", async () => { - // Mock loadPackageFromHub to return test MCP (singular call for each MCP) - const { loadPackageFromHub } = await import("./hubLoader.js"); - (loadPackageFromHub as any).mockResolvedValueOnce({ - name: "New-MCP", - command: "new-mcp", - }); - - // Set up existing MCPs in config - mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; - - const options: BaseCommandOptions = { - mcp: ["test/new-mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // MCPs from --mcp flag should be prepended (at the start) - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "New-MCP", - command: "new-mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Existing-MCP", - command: "existing-mcp", - }); - }); - - it("should handle URLs in --mcp flag as streamable-http servers", async () => { - // Set up existing MCPs in config - mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; - - const options: BaseCommandOptions = { - mcp: ["https://docs.continue.dev/mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // URL should be converted to streamable-http MCP configuration - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "docs.continue.dev", - type: "streamable-http", - url: "https://docs.continue.dev/mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Existing-MCP", - command: "existing-mcp", - }); - }); - - it("should handle mix of URLs and hub slugs in --mcp flag", async () => { - // Mock loadPackageFromHub to return test MCP for hub slug - const { loadPackageFromHub } = await import("./hubLoader.js"); - (loadPackageFromHub as any).mockResolvedValueOnce({ - name: "Hub-MCP", - command: "hub-mcp", - }); - - const options: BaseCommandOptions = { - mcp: ["https://example.com/mcp", "test/hub-mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "example.com", - type: "streamable-http", - url: "https://example.com/mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Hub-MCP", - command: "hub-mcp", - }); - }); - - it("should handle http:// URLs in --mcp flag", async () => { - const options: BaseCommandOptions = { - mcp: ["http://localhost:8080/mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.mcpServers).toHaveLength(1); - expect(config.mcpServers?.[0]).toEqual({ - name: "localhost", - type: "streamable-http", - url: "http://localhost:8080/mcp", - }); - }); - - it("should handle agent file integration gracefully when no agent file", async () => { - // The mocked service container returns null agent file state - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // Should work normally when no agent file is active - expect(config.rules).toEqual(["test-rule"]); - }); - - it("should handle agent file integration when agent file is active", async () => { - // Mock service container to return active agent file - const options: BaseCommandOptions = { - rule: ["user-rule"], - prompt: ["user-prompt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options, { - agentFile: { - name: "Test Agent", - prompt: "You are a test assistant", - rules: "Always be helpful", - model: "gpt-4", - tools: "bash,read", - }, - slug: "owner/test-agent", - agentFileModelName: null, - agentFileService: null, - }); - - // Should have both agent file and user rules - expect(config.rules).toHaveLength(2); - expect(config.rules?.[0]).toBe("Always be helpful"); // Agent file 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 deleted file mode 100644 index 106023b75..000000000 --- a/extensions/cli/src/configEnhancer.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { - AssistantUnrolled, - parseAgentFileTools, - Rule, -} from "@continuedev/config-yaml"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { - loadPackageFromHub, - loadPackagesFromHub, - mcpProcessor, - modelProcessor, - processRule, -} from "./hubLoader.js"; -import { AgentFileServiceState } 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 enhanceConfigFromAgentFile( - config: AssistantUnrolled, - _options: BaseCommandOptions | undefined, - agentFileState?: AgentFileServiceState, - ) { - const enhancedConfig = { ...config }; - const options = { ..._options }; - - if (agentFileState?.agentFile) { - const { rules, model, tools, prompt } = agentFileState?.agentFile; - if (rules) { - options.rule = [ - ...rules - .split(",") - .filter(Boolean) - .map((r) => r.trim()), - ...(options.rule || []), - ]; - } - - if (tools) { - try { - const parsedTools = parseAgentFileTools(tools); - if (parsedTools.mcpServers.length > 0) { - options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; - } - } catch (e) { - logger.error("Failed to parse agent file tools", e); - } - } - - // --model takes precedence over agent file model - if (model) { - try { - const agentFileModel = await loadPackageFromHub( - model, - modelProcessor, - ); - enhancedConfig.models = [ - agentFileModel, - ...(enhancedConfig.models ?? []), - ]; - agentFileState?.agentFileService?.setagentFileModelName( - agentFileModel.name, - ); - } catch (e) { - logger.error("Failed to load agent model", e); - } - } - - // Agent file prompt is included as a slash command, initial kickoff is handled elsewhere - if (prompt) { - enhancedConfig.prompts = [ - { - name: `Agent prompt (${agentFileState.agentFile.name})`, - prompt, - description: agentFileState.agentFile.description, - }, - ...(enhancedConfig.prompts ?? []), - ]; - } - } - return { options, enhancedConfig }; - } - /** - * Apply all enhancements to a configuration - */ - async enhanceConfig( - config: AssistantUnrolled, - _options?: BaseCommandOptions, - agentFileState?: AgentFileServiceState, - ): Promise { - const enhanced = await this.enhanceConfigFromAgentFile( - config, - _options, - agentFileState, - ); - let { enhancedConfig } = enhanced; - const { options } = enhanced; - - // Inject resolved items into config - if (options.rule && options.rule.length > 0) { - enhancedConfig = await this.injectRules(enhancedConfig, options.rule); - } - - if (options.mcp && options.mcp.length > 0) { - enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); - } - - if (options.model && options.model.length > 0) { - enhancedConfig = await this.injectModels(enhancedConfig, options.model); - } - - if (options.prompt && options.prompt.length > 0) { - enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); - } - - return enhancedConfig; - } - - /** - * Inject rules into the system message - */ - private async injectRules( - config: AssistantUnrolled, - rules: string[], - ): Promise { - const processedRules: Rule[] = []; - - for (const ruleSpec of rules) { - try { - const processedContent = await processRule(ruleSpec); - - // Check if this is a hub slug (contains / but doesn't start with . or /) - const isHubSlug = - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/"); - - if (isHubSlug) { - // Store as RuleObject with name (slug) and rule (content) - processedRules.push({ - name: ruleSpec, - rule: processedContent, - }); - } else { - // Store as plain string for file paths or direct content - processedRules.push(processedContent); - } - } catch (error: any) { - logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); - } - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - if (processedRules.length > 0) { - // Combine with existing rules if any - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - } - - return modifiedConfig; - } - - /** - * Inject MCP servers into the configuration - */ - private async injectMcps( - config: AssistantUnrolled, - mcps: string[], - ): Promise { - const processedMcps: any[] = []; - - // Process each MCP spec - check if it's a URL or hub slug - for (const mcpSpec of mcps) { - try { - // Check if it's a URL (starts with http:// or https://) - if (mcpSpec.startsWith("http://") || mcpSpec.startsWith("https://")) { - // Create a streamable-http MCP configuration - processedMcps.push({ - name: new URL(mcpSpec).hostname, - type: "streamable-http", - url: mcpSpec, - }); - } else { - // Otherwise, treat it as a hub slug - const hubMcp = await loadPackageFromHub(mcpSpec, mcpProcessor); - processedMcps.push(hubMcp); - } - } catch (error: any) { - logger.warn(`Failed to load MCP "${mcpSpec}": ${error.message}`); - } - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Prepend processed MCPs to existing mcpServers array for consistency - const existingMcpServers = modifiedConfig.mcpServers || []; - modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers]; - - return modifiedConfig; - } - - /** - * Inject models into the configuration - */ - private async injectModels( - config: AssistantUnrolled, - models: string[], - ): Promise { - const processedModels = await loadPackagesFromHub(models, modelProcessor); - - const modifiedConfig = { ...config }; - - // Prepend processed models to existing models array so they become the default - 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 { - // 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; - } -} - -/** - * Global config enhancer instance - */ -export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index 423875312..c3ccd6296 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -4,9 +4,11 @@ import * as path from "path"; import { AssistantUnrolled, + mergeUnrolledAssistants, PackageIdentifier, RegistryClient, unrollAssistant, + unrollAssistantFromContent, } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; @@ -18,7 +20,6 @@ import { getConfigUri, getOrganizationId, isEnvironmentAuthConfig, - loadAuthConfig, updateConfigUri, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; @@ -34,7 +35,8 @@ export type ConfigSource = | { type: "saved-uri"; uri: string } | { type: "user-assistant"; slug: string } | { type: "default-config-yaml" } - | { type: "default-agent" }; + | { type: "default-agent" } + | { type: "no-config" }; /** * Streamlined configuration loader that implements the specification @@ -44,12 +46,18 @@ export async function loadConfiguration( authConfig: AuthConfig, cliConfigPath: string | undefined, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], + isHeadless: boolean | undefined, ): Promise { const organizationId = getOrganizationId(authConfig); const accessToken = getAccessToken(authConfig); // Step 1: Determine config source using precedence rules - const configSource = determineConfigSource(authConfig, cliConfigPath); + const configSource = determineConfigSource( + authConfig, + cliConfigPath, + isHeadless, + ); // Step 2: Load configuration from the determined source const config = await loadFromSource( @@ -57,6 +65,7 @@ export async function loadConfiguration( accessToken, organizationId ?? null, apiClient, + injectBlocks, ); // Step 3: Save config URI for session continuity (only for file-based auth) @@ -79,12 +88,18 @@ export async function loadConfiguration( function determineConfigSource( authConfig: AuthConfig, cliConfigPath: string | undefined, + isHeadless: boolean | undefined, ): ConfigSource { // Priority 1: CLI --config flag if (cliConfigPath) { return { type: "cli-flag", path: cliConfigPath }; } + // In headless, config fallback behavior isn't supported + if (isHeadless) { + return { type: "no-config" }; + } + // Priority 2: Saved config URI (only for file-based auth) if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { const savedUri = getConfigUri(authConfig); @@ -115,6 +130,7 @@ async function loadFromSource( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { try { switch (source.type) { @@ -124,6 +140,7 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "saved-uri": @@ -132,20 +149,38 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "user-assistant": - return await loadUserAssistantWithFallback(organizationId, apiClient); + return await loadUserAssistantWithFallback( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); case "default-config-yaml": return await loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); case "default-agent": - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); + + case "no-config": + return { + name: "No Config Specified", + version: "1.0.0", + }; default: throw new Error(`Unknown config source type: ${(source as any).type}`); @@ -158,7 +193,12 @@ async function loadFromSource( "Failed to load user assistants, falling back to default agent", ), ); - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } throw error; } @@ -173,6 +213,7 @@ async function loadFromCliFlag( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { if (isFilePath(configPath)) { // Load local YAML file @@ -181,10 +222,17 @@ async function loadFromCliFlag( accessToken, organizationId, apiClient, + injectBlocks, ); } else { // Load assistant slug - return await loadAssistantSlug(configPath, organizationId, apiClient); + return await loadAssistantSlug( + configPath, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } } @@ -196,6 +244,7 @@ async function loadFromSavedUri( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const filePath = uriToPath(uri); if (filePath) { @@ -204,12 +253,19 @@ async function loadFromSavedUri( accessToken, organizationId, apiClient, + injectBlocks, ); } const slug = uriToSlug(uri); if (slug) { - return await loadAssistantSlug(slug, organizationId, apiClient); + return await loadAssistantSlug( + slug, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } throw new Error(`Invalid saved config URI: ${uri}`); @@ -221,6 +277,8 @@ async function loadFromSavedUri( async function loadUserAssistantWithFallback( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const assistants = await apiClient.listAssistants({ alwaysUseProxy: "false", @@ -240,12 +298,29 @@ async function loadUserAssistantWithFallback( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return result.config as AssistantUnrolled; + return apiConfig; } // No user assistants, fall back to default agent - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } /** @@ -255,6 +330,7 @@ async function loadDefaultConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const defaultConfigPath = path.join(env.continueHome, "config.yaml"); return await loadConfigYaml( @@ -262,6 +338,7 @@ async function loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -271,6 +348,8 @@ async function loadDefaultConfigYaml( async function loadDefaultAgent( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const resp = await apiClient.getAssistant({ ownerSlug: "continuedev", @@ -281,18 +360,66 @@ async function loadDefaultAgent( if (!resp.configResult.config) { throw new Error("Failed to load default agent."); } + let apiConfig = resp.configResult.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return resp.configResult.config as AssistantUnrolled; + return apiConfig; +} + +export async function unrollPackageIdentifiersAsConfigYaml( + packageIdentifiers: PackageIdentifier[], + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface, +): Promise<{ block: AssistantUnrolled | undefined } | null> { + const unrollResult = await unrollAssistantFromContent( + { + uriType: "file", + fileUri: "", + }, + "name: FILLER\nschema: v1\nversion: 0.0.1", + new RegistryClient({ + accessToken: accessToken ?? undefined, + apiBase: env.apiBase, + rootPath: undefined, // TODO verify this doesn't cause issues with file blocks + }), + { + currentUserSlug: "", + onPremProxyUrl: null, + orgScopeId: organizationId, + platformClient: new CLIPlatformClient(organizationId, apiClient), + renderSecrets: true, + injectBlocks: packageIdentifiers, + }, + ); + if (!unrollResult?.config) { + const fatalError = unrollResult.errors?.find((e) => e.fatal); + if (fatalError) { + throw new Error(`Error(s) unrolling package: ${fatalError.message}`); + } + } + + return { + block: unrollResult?.config, + }; } -/** - * Common function to unroll an assistant with consistent configuration - */ async function unrollAssistantWithConfig( packageIdentifier: PackageIdentifier, accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const unrollResult = await unrollAssistant( packageIdentifier, @@ -311,7 +438,7 @@ async function unrollAssistantWithConfig( renderSecrets: true, platformClient: new CLIPlatformClient(organizationId, apiClient), onPremProxyUrl: null, - injectBlocks: [], + injectBlocks, }, ); @@ -337,12 +464,14 @@ async function loadConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { return await unrollAssistantWithConfig( { fileUri: filePath, uriType: "file" }, accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -351,8 +480,10 @@ async function loadConfigYaml( */ async function loadAssistantSlug( slug: string, + accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const [ownerSlug, packageSlug] = slug.split("/"); if (!ownerSlug || !packageSlug) { @@ -360,7 +491,6 @@ async function loadAssistantSlug( `Invalid assistant slug format. Expected "owner/package", got: ${slug}`, ); } - // Unroll locally if not logged in if (!(apiClient as any).configuration.accessToken) { return await unrollAssistantWithConfig( @@ -368,9 +498,10 @@ async function loadAssistantSlug( uriType: "slug", fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, }, - getAccessToken(loadAuthConfig()), + accessToken ?? null, organizationId, apiClient, + injectBlocks, ); } @@ -389,8 +520,20 @@ async function loadAssistantSlug( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return result.config as AssistantUnrolled; + return apiConfig; } /** diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts index f7b7eee69..484b9d672 100644 --- a/extensions/cli/src/freeTrialTransition.ts +++ b/extensions/cli/src/freeTrialTransition.ts @@ -3,6 +3,7 @@ import * as fs from "fs"; import * as path from "path"; import chalk from "chalk"; +import { setConfigFilePermissions } from "core/util/paths.js"; import open from "open"; import { env } from "./env.js"; @@ -32,6 +33,7 @@ async function createOrUpdateConfig(apiKey: string): Promise { const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); + setConfigFilePermissions(CONFIG_PATH); } /** diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index 3e7bf384a..412f80208 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,4 +1,8 @@ -import { AgentFile, parseAgentFile } from "@continuedev/config-yaml"; +import { + AgentFile, + ModelConfig, + parseAgentFile, +} from "@continuedev/config-yaml"; import JSZip from "jszip"; import { getAccessToken, loadAuthConfig } from "./auth/workos.js"; @@ -8,7 +12,7 @@ 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._-]+$/; +export const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; /** * Hub package type definitions @@ -66,7 +70,7 @@ export const mcpProcessor: HubPackageProcessor = { /** * Model processor - handles JSON/YAML configuration files */ -export const modelProcessor: HubPackageProcessor = { +export const modelProcessor: HubPackageProcessor = { type: "model", expectedFileExtensions: [".json", ".yaml", ".yml"], parseContent: async (content: string, filename: string) => { @@ -241,9 +245,6 @@ export const loadMcpFromHub = (slug: string) => export const loadModelFromHub = (slug: string) => loadPackageFromHub(slug, modelProcessor); -export const loadPromptFromHub = (slug: string) => - loadPackageFromHub(slug, promptProcessor); - /** * Process a rule specification - supports file paths, hub slugs, or direct content */ @@ -297,6 +298,22 @@ export async function processRule(ruleSpec: string): Promise { return ruleSpec; } +export function isStringRule(rule: string) { + if (rule.includes(" ") || rule.includes("\n")) { + return true; + } + if ( + ["file:/", ".", "/", "~"].some((prefix) => rule.startsWith(prefix)) || + rule.includes("\\") + ) { + return false; + } + if (HUB_SLUG_PATTERN.test(rule)) { + return false; + } + return true; +} + /** * Batch load multiple packages with error handling */ diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index d58d11df3..3a713170d 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -1,125 +1,130 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { describe, expect, it, vi } from "vitest"; +import { decodePackageIdentifier } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { isStringRule } from "src/hubLoader.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "../configEnhancer.js"; +import { ConfigService } from "../services/ConfigService.js"; -// Mock the processRule function to avoid network calls -vi.mock("../hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - return content for hub slugs - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // Return as-is for direct content - return Promise.resolve(rule); - }), - loadPackagesFromHub: vi.fn(() => Promise.resolve([])), - mcpProcessor: {}, - modelProcessor: {}, +// Mock the required functions - need to match the import path used by ConfigService +vi.mock("src/hubLoader.js", () => ({ + isStringRule: vi.fn(), })); -// Mock the service container to provide empty agent file state -vi.mock("../services/ServiceContainer.js", () => ({ - serviceContainer: { - get: vi.fn(() => - Promise.resolve({ - agentFile: null, - slug: null, - }), - ), - }, +vi.mock("@continuedev/config-yaml", async (importOriginal) => ({ + ...(await importOriginal()), + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug" as const, + slug: id, + version: undefined, + })), })); -vi.mock("../services/types.js", () => ({ - SERVICE_NAMES: { - AGENT_FILE: "agentFile", +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +vi.mock("../auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), }, })); describe("Rule duplication integration test", () => { - it("should not duplicate rules when using --rule flag", async () => { - const enhancer = new ConfigEnhancer(); + let configService: ConfigService; - // Initial config without any rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + beforeEach(() => { + vi.clearAllMocks(); + configService = new ConfigService(); + + // Reset mocks to their default behavior + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Reset isStringRule mock + vi.mocked(isStringRule).mockImplementation((rule: string) => { + // Default implementation - string rules contain spaces/newlines or are local paths + return ( + rule.includes(" ") || + rule.includes("\n") || + rule.startsWith(".") || + rule.startsWith("/") || + !rule.includes("/") + ); + }); + }); + + it("should not duplicate rules when using --rule flag", () => { + // Setup mocks + vi.mocked(isStringRule).mockReturnValue(false); // "nate/spanish" is a package identifier // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify the rule was added exactly once as a RuleObject - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules).toEqual([ - { name: "nate/spanish", rule: "Content for nate/spanish" }, - ]); + // The rule should be processed as a package identifier + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules go into injected }); - it("should merge command-line rules with existing config rules", async () => { - const enhancer = new ConfigEnhancer(); - - // Initial config with existing rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: ["existing-rule"], - } as any; + it("should merge command-line rules with existing config rules", () => { + // Setup mocks for different rule types + vi.mocked(isStringRule) + .mockReturnValueOnce(false) // "nate/spanish" is a package identifier + .mockReturnValueOnce(true); // "direct-rule" is a string rule // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish", "direct-rule"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify all rules are present without duplication - expect(enhancedConfig.rules).toHaveLength(3); - expect(enhancedConfig.rules).toEqual([ - "existing-rule", - { name: "nate/spanish", rule: "Content for nate/spanish" }, - "direct-rule", - ]); + // "nate/spanish" should be a package identifier, "direct-rule" should be a string rule + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); // nate/spanish + expect(additional.rules).toEqual(["direct-rule"]); // direct-rule as string }); - it("should handle rule content with frontmatter", async () => { - const enhancer = new ConfigEnhancer(); - - // Mock processRule to return content with frontmatter - const { processRule } = await import("../hubLoader.js"); - (processRule as any).mockImplementation((rule: string) => { - if (rule === "nate/spanish") { - return Promise.resolve(`--- -alwaysApply: true ---- - -Always respond in Spanish.`); - } - return Promise.resolve(rule); - }); - - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + it("should process package identifiers for hub rules", () => { + // Setup mock - all rules are package identifiers + vi.mocked(isStringRule).mockReturnValue(false); const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Hub rules should be stored as RuleObject with name and content - expect(enhancedConfig.rules).toHaveLength(1); - const ruleObj = enhancedConfig.rules?.[0] as any; - expect(ruleObj.name).toBe("nate/spanish"); - expect(ruleObj.rule).toContain("Always respond in Spanish."); - expect(ruleObj.rule).toContain("alwaysApply: true"); + // Hub rules should be processed as package identifiers, not string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules don't go into additional.rules }); }); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index a8f780591..2a8162284 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -2,6 +2,7 @@ import * as fs from "fs"; import * as path from "path"; import chalk from "chalk"; +import { setConfigFilePermissions } from "core/util/paths.js"; import { AuthConfig, login } from "./auth/workos.js"; import { getApiClient } from "./config.js"; @@ -44,6 +45,7 @@ export async function createOrUpdateConfig(apiKey: string): Promise { const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); + setConfigFilePermissions(CONFIG_PATH); } export async function runOnboardingFlow( @@ -146,6 +148,8 @@ export async function initializeWithOnboarding( authConfig, configPath, getApiClient(authConfig?.accessToken), + [], + false, ); } catch (errorMessage) { throw new Error( diff --git a/extensions/cli/src/services/AgentFileService.test.ts b/extensions/cli/src/services/AgentFileService.test.ts index 13e1eb9bd..1100095c1 100644 --- a/extensions/cli/src/services/AgentFileService.test.ts +++ b/extensions/cli/src/services/AgentFileService.test.ts @@ -1,13 +1,19 @@ -import { Mock, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import { agentFileProcessor } from "../hubLoader.js"; - -import { AgentFileService } from "./AgentFileService.js"; +import { + AgentFileService, + EMPTY_AGENT_FILE_STATE, +} from "./AgentFileService.js"; // Mock the hubLoader module vi.mock("../hubLoader.js", () => ({ loadPackageFromHub: vi.fn(), - HubPackageProcessor: vi.fn(), + loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), + isStringRule: vi.fn(), agentFileProcessor: { type: "agentFile", expectedFileExtensions: [".md"], @@ -25,268 +31,401 @@ vi.mock("../util/logger.js", () => ({ }, })); +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + }; +}); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, +})); + describe("AgentFileService", () => { - let service: AgentFileService; + let agentFileService: AgentFileService; let mockLoadPackageFromHub: any; + let mockLoadModelFromHub: any; + + const mockAgentFile = { + name: "Test Agent File", + description: "A test agent for integration testing", + model: "gpt-4-agent", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are an assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; beforeEach(async () => { vi.clearAllMocks(); - service = new AgentFileService(); - // Get the mock function + // Get mock functions const hubLoaderModule = await import("../hubLoader.js"); mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + + // Create service instance + agentFileService = new AgentFileService(); + + // Setup default mocks + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", + provider: "openai", + }); }); describe("initialization", () => { - it("should initialize with inactive state when no agent file provided", async () => { - const state = await service.initialize(); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - }); - - it("should initialize with inactive state when agent slug is empty string", async () => { - const state = await service.initialize(""); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - }); - - it("should reject invalid agent slug format", async () => { - const state = await service.initialize("invalid-slug"); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - - // Should not call loadPackageFromHub with invalid slug - expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); - }); - - it("should reject agent slug with too many parts", async () => { - const state = await service.initialize("owner/package/extra"); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - - expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); - }); - - it("should load valid agent file successfully", async () => { - const mockAgentFile = { - name: "Test Agent", - description: "A test agent", - model: "gpt-4", - tools: "bash,read,write", - rules: "Be helpful", - prompt: "You are a helpful assistant.", + it("should initialize with empty state when no agent slug provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + const result = await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); - const state = await service.initialize("owner/package"); + expect(result).toEqual(EMPTY_AGENT_FILE_STATE); + expect(agentFileService.getState()).toEqual(EMPTY_AGENT_FILE_STATE); + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); - expect(state).toEqual({ - agentFile: mockAgentFile, - slug: "owner/package", - agentFileModelName: null, - agentFileService: service, - }); + it("should load and parse agent file when slug is provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "owner/package", - agentFileProcessor, + "owner/agent", + expect.objectContaining({ + type: "agentFile", + expectedFileExtensions: [".md"], + }), ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); }); - it("should handle loading errors gracefully", async () => { + it("should load agent file model when model is specified", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).toHaveBeenCalledWith("gpt-4-agent"); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", + }); + }); + }); + + describe("rules parsing", () => { + it("should parse rules when agent file has rules", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeDefined(); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + }); + + it("should not parse rules when agent file has no rules", async () => { + const agentFileWithoutRules = { ...mockAgentFile, rules: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutRules); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeNull(); + }); + }); + + describe("tools parsing", () => { + it("should parse tools when agent file has tools", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeDefined(); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + }); + + it("should not parse tools when agent file has no tools", async () => { + const agentFileWithoutTools = { ...mockAgentFile, tools: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutTools); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeNull(); + }); + }); + + describe("model loading", () => { + it("should not load model when agent file has no model", async () => { + const agentFileWithoutModel = { ...mockAgentFile, model: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutModel); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).not.toHaveBeenCalled(); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toBeNull(); + }); + + it("should throw error when API client is not available for model loading", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: null }; + + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + "Cannot load agent model, failed to load api client service", + ); + }); + }); + + describe("error handling", () => { + it("should throw error when agent loading fails", async () => { mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); - const state = await service.initialize("owner/package"); + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "owner/package", - agentFileProcessor, + const state = agentFileService.getState(); + expect(state.agentFile).toBeNull(); + }); + + it("should throw error for invalid agent slug format", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await expect( + agentFileService.initialize( + "invalid-slug", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + 'Invalid agent slug format. Expected "owner/package", got: invalid-slug', ); }); - it("should handle minimal agent file", async () => { - const mockAgentFile = { - name: "Minimal Agent File", - prompt: "", + it("should throw error when model loading fails", async () => { + mockLoadModelFromHub.mockRejectedValue(new Error("Model load error")); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Model load error"); + }); + }); - const state = await service.initialize("owner/minimal"); + describe("state management", () => { + it("should return correct state after initialization", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - expect(state).toEqual({ - agentFile: mockAgentFile, - slug: "owner/minimal", - agentFileModelName: null, - agentFileService: service, + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", }); }); + + it("should have correct dependencies", () => { + const dependencies = agentFileService.getDependencies(); + expect(dependencies).toEqual(["auth", "apiClient"]); + }); }); - describe("state getters", () => { - beforeEach(async () => { - const mockAgentFile = { - name: "Test Agent", - description: "A test Agent", - model: "gpt-4", - tools: "bash,read,write", - rules: "Be helpful", - prompt: "You are a helpful assistant.", + describe("partial data handling", () => { + it("should handle agent file with missing optional properties", async () => { + const partialAgentFile = { + name: "Partial Agent File", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/package"); - }); + mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); - it("should return agent file state", () => { - const state = service.getState(); - expect(state.agentFile?.name).toBe("Test Agent"); - expect(state.slug).toBe("owner/package"); - expect(state.agentFile?.model).toBe("gpt-4"); - expect(state.agentFile?.tools).toBe("bash,read,write"); - expect(state.agentFile?.rules).toBe("Be helpful"); - expect(state.agentFile?.prompt).toBe("You are a helpful assistant."); - }); - }); - - describe("inactive agent file state", () => { - beforeEach(() => { - service.initialize(); - }); - - it("should return inactive state when no agent file", () => { - const state = service.getState(); - expect(state.agentFile).toBeNull(); - expect(state.slug).toBeNull(); - }); - }); - - describe("partial agent file data", () => { - it("should handle agent file with only name and prompt", async () => { - const mockAgentFile = { - name: "Simple Agent", - prompt: "Simple prompt", + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/simple"); + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); - const state = service.getState(); - expect(state.agentFile?.model).toBeUndefined(); + const state = agentFileService.getState(); + expect(state.agentFile?.name).toBe("Partial Agent File"); + expect(state.agentFile?.model).toBe("gpt-3.5-turbo"); + expect(state.agentFile?.prompt).toBe("Partial prompt"); expect(state.agentFile?.tools).toBeUndefined(); expect(state.agentFile?.rules).toBeUndefined(); - expect(state.agentFile?.prompt).toBe("Simple prompt"); - }); - - it("should handle agent file with empty prompt", async () => { - const mockAgentFile = { - name: "Empty Prompt Agent", - model: "gpt-3.5-turbo", - prompt: "", - }; - - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/empty"); - - const state = service.getState(); - expect(state.agentFile?.model).toBe("gpt-3.5-turbo"); - expect(state.agentFile?.prompt).toBe(""); + expect(state.parsedRules).toBeNull(); + expect(state.parsedTools).toBeNull(); }); }); }); - -describe("agentFileProcessor", () => { - it("should have correct type and extensions", () => { - expect(agentFileProcessor.type).toBe("agentFile"); - expect(agentFileProcessor.expectedFileExtensions).toEqual([".md"]); - }); - - it("should parse agent file content correctly", () => { - const content = `--- -name: Test Agent -model: gpt-4 -tools: bash,read ---- -You are a helpful assistant.`; - - // Set up the mock to return expected result - const expectedResult = { - name: "Test Agent", - model: "gpt-4", - tools: "bash,read", - prompt: "You are a helpful assistant.", - }; - (agentFileProcessor.parseContent as Mock).mockReturnValue(expectedResult); - - const result = agentFileProcessor.parseContent(content, "test.md"); - expect(result).toEqual({ - name: "Test Agent", - model: "gpt-4", - tools: "bash,read", - prompt: "You are a helpful assistant.", - }); - }); - - it("should validate agent file content", () => { - const validAgentFile = { - name: "Valid Agent", - prompt: "Test prompt", - }; - - const invalidAgentFile = { - prompt: "Test prompt", - // Missing name - }; - - // Set up mock validation responses - (agentFileProcessor.validateContent as Mock) - .mockReturnValueOnce(true) // For valid agent file - .mockReturnValueOnce(false); // For invalid agent file - - expect(agentFileProcessor.validateContent?.(validAgentFile)).toBe(true); - expect(agentFileProcessor.validateContent?.(invalidAgentFile as any)).toBe( - false, - ); - }); - - it("should validate agent file with empty name as invalid", () => { - const invalidAgentFile = { - name: "", - prompt: "Test prompt", - }; - - // Mock validation to return false for empty name - (agentFileProcessor.validateContent as Mock).mockReturnValue(false); - - expect(agentFileProcessor.validateContent?.(invalidAgentFile)).toBe(false); - }); -}); diff --git a/extensions/cli/src/services/AgentFileService.ts b/extensions/cli/src/services/AgentFileService.ts index 8220e34f5..81dd0e4df 100644 --- a/extensions/cli/src/services/AgentFileService.ts +++ b/extensions/cli/src/services/AgentFileService.ts @@ -1,43 +1,60 @@ -import { agentFileProcessor, loadPackageFromHub } from "../hubLoader.js"; +import { + parseAgentFileRules, + parseAgentFileTools, +} from "@continuedev/config-yaml"; + +import { + agentFileProcessor, + loadModelFromHub, + loadPackageFromHub, +} from "../hubLoader.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { AgentFileServiceState } from "./types.js"; +import { + AgentFileServiceState, + ApiClientServiceState, + AuthServiceState, + SERVICE_NAMES, +} from "./types.js"; +export const EMPTY_AGENT_FILE_STATE: AgentFileServiceState = { + agentFile: null, + slug: null, + parsedRules: null, + parsedTools: null, + agentFileModel: null, +}; /** * Service for managing agent file state * Loads agent files from the hub and extracts model, tools, and prompt information */ -export class AgentFileService extends BaseService { - /** - * Set the resolved agent file model name after it's been processed - * Called by ConfigEnhancer after resolving the model slug - */ - setagentFileModelName(modelName: string): void { - this.setState({ - agentFileModelName: modelName, - }); - } +export class AgentFileService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("AgentFileService", { - agentFileService: null, - agentFile: null, - slug: null, - agentFileModelName: null, + ...EMPTY_AGENT_FILE_STATE, }); } + getDependencies(): string[] { + return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + } + /** * Initialize the agent file service with a hub slug */ - async doInitialize(agentFileSlug?: string): Promise { + async doInitialize( + agentFileSlug: string | undefined, + authServiceState: AuthServiceState, + apiClientState: ApiClientServiceState, + ): Promise { if (!agentFileSlug) { return { - agentFileService: this, - agentFile: null, - slug: null, - agentFileModelName: null, + ...EMPTY_AGENT_FILE_STATE, }; } @@ -54,20 +71,40 @@ export class AgentFileService extends BaseService { agentFileProcessor, ); - return { - agentFileService: this, + // Set the basic agent file state + this.setState({ agentFile, slug: agentFileSlug, - agentFileModelName: null, // Will be set by ConfigEnhancer after model resolution - }; + }); + + if (agentFile.model) { + if (!apiClientState.apiClient) { + throw new Error( + "Cannot load agent model, failed to load api client service", + ); + } + const model = await loadModelFromHub(agentFile.model); + this.setState({ + agentFileModel: model, + }); + } + + if (agentFile.rules) { + this.setState({ + parsedRules: parseAgentFileRules(agentFile.rules), + }); + } + + if (agentFile.tools) { + this.setState({ + parsedTools: parseAgentFileTools(agentFile.tools), + }); + } + + return this.getState(); } catch (error: any) { logger.error("Failed to initialize AgentFileService:", error); - return { - agentFileService: this, - agentFile: null, - slug: null, - agentFileModelName: null, - }; + throw error; } } diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts deleted file mode 100644 index c79d563d2..000000000 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ /dev/null @@ -1,206 +0,0 @@ -// 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"; - -// /** -// * 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(); - -// const state: AuthServiceState = { -// authConfig, -// isAuthenticated: authenticated, -// organizationId: authConfig?.organizationId || undefined, -// }; - -// logger.debug("AuthService initialized", { -// authenticated, -// hasConfig: !!authConfig, -// orgId: state.organizationId, -// }); - -// return state; -// } - -// /** -// * Perform login flow -// */ -// async login(): Promise { -// logger.debug("Starting login flow"); - -// try { -// const newAuthConfig = await doLogin(); - -// this.setState({ -// authConfig: newAuthConfig, -// isAuthenticated: true, -// organizationId: newAuthConfig?.organizationId || undefined, -// }); - -// 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; -// } -// } - -// /** -// * Perform logout -// */ -// async logout(): Promise { -// logger.debug("Logging out"); - -// doLogout(); - -// this.setState({ -// authConfig: null, -// isAuthenticated: false, -// organizationId: undefined, -// }); - -// 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"); -// } - -// logger.debug("Ensuring organization is selected", { -// currentOrgId: this.currentState.organizationId, -// isHeadless, -// }); - -// const updatedConfig = await ensureOrganization( -// this.currentState.authConfig, -// isHeadless, -// ); - -// this.setState({ -// authConfig: updatedConfig, -// isAuthenticated: true, -// organizationId: updatedConfig?.organizationId || undefined, -// }); - -// logger.debug("Organization ensured", { -// orgId: this.currentState.organizationId, -// }); - -// 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", -// ); -// } - -// logger.debug("Switching organization", { -// from: this.currentState.organizationId, -// to: organizationId, -// }); - -// const authenticatedConfig = this.currentState -// .authConfig as AuthenticatedConfig; - -// const updatedConfig: AuthenticatedConfig = { -// ...authenticatedConfig, -// organizationId, -// }; - -// saveAuthConfig(updatedConfig); - -// this.setState({ -// authConfig: updatedConfig, -// isAuthenticated: true, -// organizationId: organizationId || undefined, -// }); - -// logger.debug("Organization switched", { -// newOrgId: this.currentState.organizationId, -// }); - -// return this.getState(); -// } - -// /** -// * 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; -// } -// } - -// /** -// * 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(); -// } -// } -export {}; diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 2ca7b9146..6a4820553 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -1,37 +1,79 @@ +import { + decodePackageIdentifier, + mergeUnrolledAssistants, + ModelRole, +} from "@continuedev/config-yaml"; import { beforeEach, describe, expect, test, vi } from "vitest"; -// Mock modules -vi.mock("../auth/workos.js"); -vi.mock("../configLoader.js"); -vi.mock("../configEnhancer.js"); -vi.mock("./ServiceContainer.js"); - import * as workos from "../auth/workos.js"; -import { configEnhancer } from "../configEnhancer.js"; import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { AgentFileServiceState, SERVICE_NAMES } from "./types.js"; +vi.mock("../auth/workos.js"); +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), + unrollPackageIdentifiersAsConfigYaml: vi.fn(), +})); +vi.mock("../util/logger.js"); +vi.mock("./ServiceContainer.js"); +vi.mock("@continuedev/config-yaml"); + +const defaultModel = { + provider: "anthropic", + name: "claude-sonnet-4.5", + model: "claude-3-5-sonnet-20241022", + roles: ["chat"] as ModelRole[], +}; describe("ConfigService", () => { let service: ConfigService; const mockConfig = { name: "test-assistant", version: "1.0.0", - models: [], + models: [ + { + name: "existing-model", + model: "gpt-4", + roles: ["chat"], + }, + ], systemMessage: "Test system message", } as any; const mockApiClient = { get: vi.fn(), post: vi.fn() }; const mockAgentFileState: AgentFileServiceState = { slug: null, agentFile: null, - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; beforeEach(() => { vi.clearAllMocks(); service = new ConfigService(); + + // Setup mocks + vi.mocked(mergeUnrolledAssistants).mockReturnValue(mockConfig as any); + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Mock the default model loading function + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default-chat-model", + version: "1.0.0", + models: [defaultModel], + }, + }); }); describe("State Management", () => { @@ -41,10 +83,9 @@ describe("ConfigService", () => { source: { type: "cli-flag", path: "/path/to/config.yaml" } as any, }); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/path/to/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -53,6 +94,16 @@ describe("ConfigService", () => { config: mockConfig as any, configPath: "/path/to/config.yaml", }); + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }), + ); }); test("should initialize with undefined config path", async () => { @@ -61,10 +112,9 @@ describe("ConfigService", () => { source: { type: "default-agent" } as any, }); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: undefined, - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -75,7 +125,7 @@ describe("ConfigService", () => { }); }); - test("should inject rules into config", async () => { + test("should inject rules into config using mergeUnrolledAssistants", async () => { vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, @@ -83,26 +133,29 @@ describe("ConfigService", () => { const expectedConfig = { ...mockConfig, - systemMessage: - "Test system message\n\nProcessed: rule1\n\nProcessed: rule2", + rules: ["rule1", "rule2"], }; - vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(expectedConfig); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, injectedConfigOptions: { rule: ["rule1", "rule2"] }, }); - // Verify configEnhancer was called with the right parameters - expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( + // Verify mergeUnrolledAssistants was called with the right parameters + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( mockConfig, - { rule: ["rule1", "rule2"] }, - mockAgentFileState, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: ["rule1", "rule2"], + mcpServers: [], + prompts: [], + }), ); expect(state.config).toEqual(expectedConfig); @@ -116,10 +169,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -130,13 +182,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - const state = await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: newConfig, @@ -146,10 +199,9 @@ describe("ConfigService", () => { }); test("should handle switch config errors", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -159,12 +211,12 @@ describe("ConfigService", () => { ); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("Config not found"); }); }); @@ -176,10 +228,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -190,12 +241,13 @@ describe("ConfigService", () => { config: updatedConfig, source: { type: "cli-flag", path: "/config.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(updatedConfig); - const state = await service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: updatedConfig, @@ -209,20 +261,19 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "default-agent" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: undefined, - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); await expect( - service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("No configuration path available for reload"); }); }); @@ -234,10 +285,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -247,9 +297,10 @@ describe("ConfigService", () => { accessToken: "token", organizationId: "org-123", } as any); - vi.mocked(serviceContainer.get).mockResolvedValue({ - apiClient: mockApiClient, - }); + vi.mocked(serviceContainer.get) + .mockResolvedValueOnce({ apiClient: mockApiClient }) + .mockResolvedValueOnce(mockAgentFileState) + .mockResolvedValueOnce({ isHeadless: false }); // Mock new config load const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -257,6 +308,7 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); await service.updateConfigPath("/new.yaml"); @@ -277,10 +329,9 @@ describe("ConfigService", () => { }); test("should handle missing API client", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -299,12 +350,89 @@ describe("ConfigService", () => { }); }); + describe("getAdditionalBlocksFromOptions()", () => { + test("should process command line options correctly", () => { + const options = { + rule: ["rule1", "owner/package-rule"], + prompt: ["prompt1"], + model: ["gpt-4"], + mcp: ["owner/mcp-server", "https://example.com/mcp"], + }; + const agentFileState = { + agentFile: { + name: "test-agent", + model: "agent-model", + prompt: "Agent prompt", + }, + parsedRules: ["agent/rule"], + parsedTools: { + mcpServers: ["agent/mcp"], + }, + } as any; + + const result = service.getAdditionalBlocksFromOptions( + options, + agentFileState, + ); + + // Should have package identifiers from models, MCPs, and non-string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith("gpt-4"); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent-model", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/package-rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/mcp-server", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/mcp", + ); + + // Should have additional blocks with string rules and URL MCPs + expect(result.additional.rules).toContain("rule1"); + expect(result.additional.rules).toContain("prompt1"); + expect(result.additional.mcpServers).toEqual([ + expect.objectContaining({ + name: "example.com", + url: "https://example.com/mcp", + }), + ]); + expect(result.additional.prompts).toEqual([ + expect.objectContaining({ + name: "Agent prompt (test-agent)", + prompt: "Agent prompt", + }), + ]); + }); + + test("should handle empty options", () => { + const result = service.getAdditionalBlocksFromOptions( + undefined, + undefined, + ); + + expect(result.injected).toEqual([]); + expect(result.additional).toEqual({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }); + }); + }); + describe("getDependencies()", () => { - test("should declare auth and apiClient dependencies", () => { + test("should declare auth, apiClient, and agentFile dependencies", () => { expect(service.getDependencies()).toEqual([ - "auth", - "apiClient", - "agentFile", + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.AGENT_FILE, ]); }); }); @@ -315,10 +443,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -331,13 +458,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(listener).toHaveBeenCalledWith( expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }), @@ -349,10 +477,9 @@ describe("ConfigService", () => { }); test("should emit error on switch failure", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -364,17 +491,260 @@ describe("ConfigService", () => { vi.mocked(configLoader.loadConfiguration).mockRejectedValue(error); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow(); expect(errorListener).toHaveBeenCalledWith(error); }); }); + describe("addDefaultChatModelIfNone()", () => { + test("should add default model when no chat models exist", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "non-chat-model", + model: "test-model", + roles: ["embed", "rerank"], // No "chat" role + }, + ], + } as any; + + // Mock the default model loading + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + [ + { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, + }, + ], + "token", + null, + mockApiClient, + ); + + expect(result.models).toHaveLength(2); + expect(result.models![1]).toEqual(defaultModel); + }); + + test("should not add default model when chat model already exists", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "existing-chat-model", + model: "gpt-4", + roles: ["chat"], + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + // Should not call the unroll function since chat model exists + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); // Should return unchanged config + }); + + test("should not add default model when model with no roles exists (defaults to chat)", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "model-with-no-roles", + model: "gpt-4", + // No roles specified, defaults to including chat + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); + }); + + test("should handle empty models array by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should handle undefined models by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + // models is undefined + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should throw error when default model fails to load", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + const error = new Error("Failed to load default model"); + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockRejectedValue(error); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ), + ).rejects.toThrow("No model specified and failed to load default model"); + }); + + test("should throw error when loaded default model is empty", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + // Mock empty model config + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [], // Empty models array + }, + }); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ), + ).rejects.toThrow("No model specified and failed to load default model"); + }); + + test("should work with null access token", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + undefined, // No auth config + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + expect.any(Array), + null, // Should pass null for access token + null, // Should pass null for organization ID + mockApiClient, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + }); + describe("Legacy Compatibility", () => { test("updateConfigPath method exists and has correct signature", () => { // Test that the updateConfigPath method exists and is a function diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 391215399..864c84cc9 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -1,12 +1,25 @@ +import { + AssistantUnrolled, + decodePackageIdentifier, + mergeUnrolledAssistants, + PackageIdentifier, +} from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { isStringRule } from "src/hubLoader.js"; +import { getErrorString } from "src/util/error.js"; + import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { configEnhancer } from "../configEnhancer.js"; +import { + loadConfiguration, + unrollPackageIdentifiersAsConfigYaml, +} from "../configLoader.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionServiceState } from "./ToolPermissionService.js"; import { AgentFileServiceState, ApiClientServiceState, @@ -14,13 +27,22 @@ import { SERVICE_NAMES, } from "./types.js"; +const DEFAULT_MODEL_IDENTIFIER: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, +}; + interface ConfigServiceInit { authConfig: AuthConfig; configPath: string | undefined; - _organizationId: string | null; apiClient: DefaultApiInterface; agentFileState: AgentFileServiceState; injectedConfigOptions?: BaseCommandOptions; + isHeadless?: boolean; } /** * Service for managing configuration state and operations @@ -48,97 +70,248 @@ export class ConfigService ]; } + getAdditionalBlocksFromOptions( + injectedConfigOptions: BaseCommandOptions | undefined, + agentFileState: AgentFileServiceState | undefined, + ): { + injected: PackageIdentifier[]; + additional: AssistantUnrolled; + } { + const packageIdentifiers: PackageIdentifier[] = []; + const additional: AssistantUnrolled = { + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }; + + const options = injectedConfigOptions || {}; + + this.processModels(options.model || [], agentFileState, packageIdentifiers); + this.processMcpServers( + options.mcp || [], + agentFileState, + packageIdentifiers, + additional, + ); + this.processAgentFileRules(agentFileState, packageIdentifiers); + this.processRulesAndPrompts( + options.rule || [], + options.prompt || [], + packageIdentifiers, + additional, + ); + this.processAgentFilePrompt(agentFileState, additional); + + return { + injected: packageIdentifiers, + additional, + }; + } + + private processModels( + models: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + const allModels = [...models]; + if (agentFileState?.agentFile?.model) { + allModels.push(agentFileState.agentFile.model); + } + + for (const model of allModels) { + try { + packageIdentifiers.push(decodePackageIdentifier(model)); + } catch (e) { + logger.warn(`Failed to add model "${model}": ${getErrorString(e)}`); + } + } + } + + private processMcpServers( + mcps: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allMcps = [ + ...mcps, + ...(agentFileState?.parsedTools?.mcpServers || []), + ]; + + for (const mcp of allMcps) { + try { + if (this.isUrl(mcp)) { + additional.mcpServers!.push({ + name: new URL(mcp).hostname, + url: mcp, + }); + } else { + packageIdentifiers.push(decodePackageIdentifier(mcp)); + } + } catch (e) { + logger.warn(`Failed to add MCP server "${mcp}": ${getErrorString(e)}`); + } + } + } + + private processAgentFileRules( + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + for (const rule of agentFileState?.parsedRules || []) { + try { + packageIdentifiers.push(decodePackageIdentifier(rule)); + } catch (e) { + logger.warn( + `Failed to get rule "${rule} (from agent file)": ${getErrorString(e)}`, + ); + } + } + } + + private processRulesAndPrompts( + rules: string[], + prompts: string[], + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allRulesAndPrompts = [...rules, ...prompts]; + + for (const item of allRulesAndPrompts) { + try { + if (isStringRule(item)) { + additional.rules!.push(item); + } else { + packageIdentifiers.push(decodePackageIdentifier(item)); + } + } catch (e) { + logger.warn( + `Failed to load rule or prompt "${item}": ${getErrorString(e)}`, + ); + } + } + } + + private processAgentFilePrompt( + agentFileState: AgentFileServiceState | undefined, + additional: AssistantUnrolled, + ): void { + if (agentFileState?.agentFile?.prompt) { + additional.prompts!.push({ + name: `Agent prompt (${agentFileState.agentFile.name})`, + prompt: agentFileState.agentFile.prompt, + description: agentFileState.agentFile.description, + }); + } + } + + private isUrl(value: string): boolean { + return value.startsWith("http://") || value.startsWith("https://"); + } + + async addDefaultChatModelIfNone( + config: AssistantUnrolled, + apiClient: DefaultApiInterface, + authConfig: AuthConfig | undefined, + ): Promise { + const hasChatModel = !!config.models?.find( + (m) => !!m && (!m.roles || m.roles.includes("chat")), + ); + if (!hasChatModel) { + try { + const modelConfig = await unrollPackageIdentifiersAsConfigYaml( + [DEFAULT_MODEL_IDENTIFIER], + authConfig?.accessToken ?? null, + authConfig?.organizationId ?? null, + apiClient, + ); + const defaultModel = modelConfig?.block?.models?.[0]; + if (!defaultModel) { + throw new Error("Loaded default model contained no model block"); + } + config.models = [...(config.models || []), defaultModel]; + } catch (e) { + logger.error("Failed to load default model with no model specified", e); + throw new Error("No model specified and failed to load default model"); + } + } + return config; + } + + private async loadConfig( + init: ConfigServiceInit, + ): Promise { + const { + authConfig, + configPath, + apiClient, + injectedConfigOptions, + agentFileState, + } = init; + const { injected, additional } = this.getAdditionalBlocksFromOptions( + injectedConfigOptions, + agentFileState, + ); + + const result = await loadConfiguration( + authConfig, + configPath, + apiClient, + injected, + init.isHeadless, + ); + + const loadedConfig = result.config; + const merged = mergeUnrolledAssistants(loadedConfig, additional); + + const withModel = await this.addDefaultChatModelIfNone( + merged, + apiClient, + authConfig, + ); + + // Config URI persistence is now handled by the streamlined loader + logger.debug("ConfigService initialized successfully"); + + const state = { + config: withModel, + configPath, + }; + this.setState(state); + + return state; + } + /** * Initialize the config service */ - async doInitialize({ - apiClient, - authConfig, - configPath, - agentFileState, - injectedConfigOptions, - }: ConfigServiceInit): Promise { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration(authConfig, configPath, apiClient); - - let config = result.config; - - // Apply injected config if provided - if ( - agentFileState?.agentFile || - (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - agentFileState, - ); - - logger.debug("Applied injected configuration"); - } + async doInitialize(init: ConfigServiceInit): Promise { + const result = await this.loadConfig(init); // Config URI persistence is now handled by the streamlined loader - logger.debug("ConfigService initialized successfully"); - return { - config, - configPath, - }; + return result; } /** * Switch to a new configuration */ - async switchConfig( - newConfigPath: string, - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { + async switchConfig(init: ConfigServiceInit): Promise { logger.debug("Switching configuration", { from: this.currentState.configPath, - to: newConfigPath, + to: init.configPath, }); try { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClient, - ); - - let config = result.config; - - // Apply injected config if provided - if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - ); - - logger.debug("Applied injected configuration"); - } - - this.setState({ - config, - configPath: newConfigPath, - }); - - // Config URI persistence is now handled by the streamlined loader - + const state = await this.loadConfig(init); logger.debug("Configuration switched successfully", { - newConfigPath, + newConfigPath: init.configPath, }); - return this.getState(); + return state; } catch (error: any) { logger.error("Failed to switch configuration:", error); this.emit("error", error); @@ -150,10 +323,7 @@ export class ConfigService * Reload the current configuration */ async reload( - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, + init: Omit, ): Promise { if (!this.currentState.configPath) { throw new Error("No configuration path available for reload"); @@ -161,25 +331,10 @@ export class ConfigService logger.debug("Reloading current configuration"); - return this.switchConfig( - this.currentState.configPath, - authConfig, - _organizationId, - apiClient, - injectedConfigOptions, - ); - } - - /** - * Check if injected config options contain any config to inject - */ - private hasInjectedConfig(options: BaseCommandOptions): boolean { - return !!( - (options.rule && options.rule.length > 0) || - (options.mcp && options.mcp.length > 0) || - (options.model && options.model.length > 0) || - (options.prompt && options.prompt.length > 0) - ); + return this.switchConfig({ + ...init, + configPath: this.currentState.configPath, + }); } /** @@ -195,40 +350,39 @@ export class ConfigService try { // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); - const apiClientState = await serviceContainer.get( + const { apiClient } = await serviceContainer.get( SERVICE_NAMES.API_CLIENT, ); - if (!apiClientState.apiClient) { + if (!apiClient) { throw new Error("API client not available"); } - // Load the new configuration using streamlined loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClientState.apiClient, + const agentFileState = await serviceContainer.get( + SERVICE_NAMES.AGENT_FILE, ); - // Update internal state - this.setState({ - config: result.config, + const toolPermissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const result = await this.loadConfig({ + agentFileState, + apiClient, + authConfig, configPath: newConfigPath, + injectedConfigOptions: {}, + isHeadless: toolPermissionsState.isHeadless, }); - // Config URI persistence is now handled by the streamlined loader - - // Update the CONFIG service in the container - serviceContainer.set(SERVICE_NAMES.CONFIG, this.getState()); - // Manually reload dependent services (MODEL, MCP) to pick up the new config await serviceContainer.reload(SERVICE_NAMES.MODEL); await serviceContainer.reload(SERVICE_NAMES.MCP); logger.debug("Configuration path updated successfully", { newConfigPath, - configName: result.config.name, + configName: result.config?.name, }); } catch (error: any) { logger.error("Failed to update configuration path:", error); @@ -236,4 +390,9 @@ export class ConfigService throw error; } } + + setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState); + } } diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index bcc797780..1ce83b540 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -100,45 +100,6 @@ describe("ModelService", () => { }); }); - describe("update()", () => { - test("should update model with new assistant config", async () => { - // Initialize first - vi.mocked(config.getLlmApi).mockReturnValue([ - mockLlmApi as any, - mockAssistant.models![0] as ModelConfig, - ]); - await service.initialize(mockAssistant, mockAuthConfig); - - // Update with new assistant - const newAssistant = { - ...mockAssistant, - models: [ - { - provider: "openai", - model: "gpt-4-turbo", - name: "GPT-4 Turbo", - apiKey: "new-key", - roles: ["chat"], - } as ModelConfig, - ], - }; - const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; - vi.mocked(config.getLlmApi).mockReturnValue([ - newLlmApi as any, - newAssistant.models![0] as ModelConfig, - ]); - - const state = await service.update(newAssistant, mockAuthConfig); - - expect(state).toEqual({ - llmApi: newLlmApi, - model: newAssistant.models![0], - assistant: newAssistant, - authConfig: mockAuthConfig, - }); - }); - }); - describe("switchModel()", () => { test("should switch to a different model by index", async () => { vi.mocked(config.getLlmApi).mockReturnValue([ diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index f4e0a18b8..0c36e1971 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -41,7 +41,7 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, - agentFileServiceState?: AgentFileServiceState, + agentFileServiceState: AgentFileServiceState | undefined, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -60,8 +60,8 @@ export class ModelService let modelSource = "default"; // Priority = agentFile -> last selected model - if (agentFileServiceState?.agentFileModelName) { - preferredModelName = agentFileServiceState.agentFileModelName; + if (agentFileServiceState?.agentFileModel?.name) { + preferredModelName = agentFileServiceState.agentFileModel?.name; modelSource = "agentFile"; } else { preferredModelName = getModelName(authConfig); @@ -122,48 +122,6 @@ export class ModelService } } - /** - * Update the model based on new config or auth changes - */ - async update( - assistant: AssistantUnrolled, - authConfig: AuthConfig, - ): Promise { - logger.debug("Updating ModelService"); - - try { - // Update instance properties for backward compatibility - this.assistant = assistant; - this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - const [llmApi, model] = getLlmApi(assistant, authConfig); - - // Ensure state has all necessary data - this.setState({ - llmApi, - model, - assistant, - authConfig, - }); - - logger.debug("ModelService updated successfully", { - modelProvider: model.provider, - modelName: (model as any).name || "unnamed", - availableModels: this.availableModels.length, - }); - - return this.getState(); - } catch (error: any) { - logger.error("Failed to update ModelService:", error); - this.emit("error", error); - throw error; - } - } - /** * Override isReady to check for required state */ diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts index e683a86d2..8706a1150 100644 --- a/extensions/cli/src/services/ModelService.workflow-priority.test.ts +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -60,8 +60,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "gpt-4", - agentFileService: null, + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, }; // Mock createLlmApi to return different models based on the selected model @@ -102,8 +107,9 @@ describe("ModelService agent file model prioritization", () => { // No model specified }, slug: "test/agent", - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; // Mock getModelName to return a persisted model @@ -146,8 +152,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "non-existent-model", - agentFileService: null, + agentFileModel: { + name: "non-existent-model", + model: "non-existent", + provider: "nonexistent", + }, + parsedRules: null, + parsedTools: null, }; const getLlmApiMock = vi.mocked(config.getLlmApi); @@ -177,8 +188,9 @@ describe("ModelService agent file model prioritization", () => { const agentFileServiceState: AgentFileServiceState = { agentFile: null, slug: null, - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; // Make sure getModelName returns null (no persisted model) @@ -215,8 +227,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "gpt-4", - agentFileService: null, + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, }; // Mock getModelName to return a different persisted model diff --git a/extensions/cli/src/services/agent-file-integration.test.ts b/extensions/cli/src/services/agent-file-integration.test.ts index 905f7a683..080f9e40d 100644 --- a/extensions/cli/src/services/agent-file-integration.test.ts +++ b/extensions/cli/src/services/agent-file-integration.test.ts @@ -1,17 +1,18 @@ -import { vi } from "vitest"; - -import { ConfigEnhancer } from "../configEnhancer.js"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { AgentFileService } from "./AgentFileService.js"; +import { ConfigService } from "./ConfigService.js"; import { ModelService } from "./ModelService.js"; // Mock the hubLoader module vi.mock("../hubLoader.js", () => ({ loadPackageFromHub: vi.fn(), loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), mcpProcessor: {}, modelProcessor: {}, processRule: vi.fn(), + isStringRule: vi.fn(), agentFileProcessor: { type: "agentFile", expectedFileExtensions: [".md"], @@ -38,18 +39,50 @@ vi.mock("../config.js", () => ({ // Mock auth module vi.mock("../auth/workos.js", () => ({ getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug", + slug: id, + version: undefined, + })), + }; +}); + +// Mock configLoader +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, })); describe("Agent file Integration Tests", () => { let agentFileService: AgentFileService; let modelService: ModelService; - let configEnhancer: ConfigEnhancer; + let configService: ConfigService; let mockLoadPackageFromHub: any; let mockLoadPackagesFromHub: any; let mockProcessRule: any; let mockCreateLlmApi: any; let mockGetLlmApi: any; let mockModelProcessor: any; + let mockDecodePackageIdentifier: any; + let mockLoadModelFromHub: any; + let mockIsStringRule: any; const mockAgentFile = { name: "Test Agent File", @@ -90,21 +123,32 @@ describe("Agent file Integration Tests", () => { mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; mockProcessRule = hubLoaderModule.processRule as any; mockModelProcessor = hubLoaderModule.modelProcessor; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + mockIsStringRule = hubLoaderModule.isStringRule as any; mockCreateLlmApi = configModule.createLlmApi as any; mockGetLlmApi = configModule.getLlmApi as any; + // Get mock functions from config-yaml + const configYaml = await import("@continuedev/config-yaml"); + mockDecodePackageIdentifier = configYaml.decodePackageIdentifier as any; + // Create service instances agentFileService = new AgentFileService(); modelService = new ModelService(); - configEnhancer = new ConfigEnhancer(); + configService = new ConfigService(); // Setup default mocks mockProcessRule.mockResolvedValue("Processed rule content"); mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); - mockLoadPackageFromHub.mockResolvedValue({ - name: "test-model", + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", provider: "openai", }); + mockIsStringRule.mockImplementation((rule: string) => { + // String rules are those that don't look like package identifiers + return rule.includes(" ") || rule.includes("\n") || !rule.includes("/"); + }); mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); mockGetLlmApi.mockReturnValue([ { mock: "llmApi" }, @@ -112,158 +156,157 @@ describe("Agent file Integration Tests", () => { ]); }); - describe("Agent file models are injected via ConfigEnhancer", () => { - it("should add agent file model to options when agent file active", async () => { + describe("Agent file models are injected via ConfigService", () => { + it("should add agent file model when agent file is active", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); - // Mock loadPackageFromHub to return a model for the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - - // Test that ConfigEnhancer adds the agent file model to options - const baseConfig = { models: [] }; + // Test that ConfigService processes the agent file model const baseOptions = {}; // No --model flag - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Should have loaded the agent file model directly via loadPackageFromHub - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "gpt-4-agent", - mockModelProcessor, - ); - - // The agent file model should be prepended to the models array - expect(enhancedConfig.models).toHaveLength(1); - expect(enhancedConfig.models?.[0]).toEqual({ - name: "gpt-4-agent", - provider: "openai", - }); + // Should have processed the agent file model as a package identifier + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(2); // Agent file model + parsed rules become package identifiers }); it("should not add agent file model when no agent file active", async () => { // Initialize agent file service without agent - await agentFileService.initialize(); + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile).toBeNull(); - // Test that ConfigEnhancer doesn't add any agent file models - const baseConfig = { models: [] }; + // Test that ConfigService doesn't add any agent file models const baseOptions = {}; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Should not have enhanced with any models - expect(enhancedConfig.models).toEqual([]); + // Should not have processed any models + expect(injected).toHaveLength(0); + expect(additional.models || []).toHaveLength(0); }); - it("should respect --model flag priority over agent file model", async () => { + it("should process both --model flag and agent file model", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - // Mock loadPackageFromHub for agent file model and loadPackagesFromHub for user models - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - mockLoadPackagesFromHub.mockResolvedValueOnce([ - { - name: "user-specified-model", - provider: "anthropic", - }, - ]); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - // Test that --model flag takes precedence - const baseConfig = { models: [] }; + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + // Test that --model flag and agent file model are both processed const baseOptions = { model: ["user-specified-model"] }; // User specified --model - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileService.getState(), + ); - // Should process the user model via loadPackagesFromHub - expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( - ["user-specified-model"], - mockModelProcessor, + // Should process both the user model and agent file model as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith( + "user-specified-model", ); - - // Should also load the agent file model - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "gpt-4-agent", - mockModelProcessor, - ); - - // Both models should be in the config, with user model first (takes precedence) - expect(enhancedConfig.models).toHaveLength(2); - expect(enhancedConfig.models?.[0]).toEqual({ - name: "user-specified-model", - provider: "anthropic", - }); - expect(enhancedConfig.models?.[1]).toEqual({ - name: "gpt-4-agent", - provider: "openai", - }); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(3); // User model + agent file model + parsed rules as package identifiers }); }); - describe("AgentFileService affects ConfigEnhancer", () => { + describe("AgentFileService affects ConfigService", () => { it("should inject agent file rules when agent file active", async () => { - // Setup agent file service with active agent file - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + // Mock the agent file with parsed rules + const agentFileStateWithRules = { + agentFile: mockAgentFile, + parsedRules: ["agent/rule1"], // Parsed rules from agent file + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - // Rules should be processed normally since agent file rules are now added to options.rule - expect(mockProcessRule).toHaveBeenCalledWith(mockAgentFile.rules); - expect(enhancedConfig.rules).toHaveLength(2); - // The agent file rule is processed first, then existing rules - expect(mockProcessRule).toHaveBeenNthCalledWith(1, mockAgentFile.rules); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithRules, + ); + + // Agent file rules should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("agent/rule1"); + expect(injected).toHaveLength(2); // Model + rule }); it("should not inject agent file rules when agent file inactive", async () => { // Initialize agent file service without agent file - await agentFileService.initialize(); - - const baseConfig = { - rules: ["existing rule"], + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, ); - expect(mockProcessRule).not.toHaveBeenCalled(); - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig?.rules?.[0]).toBe("existing rule"); + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Should not process any rules since no agent file is active + expect(injected).toHaveLength(0); + expect(additional.rules).toHaveLength(0); }); it("should not inject agent file rules when agent file has no rules", async () => { @@ -272,29 +315,46 @@ describe("Agent file Integration Tests", () => { rules: undefined, }; - mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutRules); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + // Mock agent file state with no parsed rules + const agentFileStateWithoutRules = { + agentFile: agentFileWithoutRules, + parsedRules: [], // No parsed rules + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - expect(mockProcessRule).not.toHaveBeenCalled(); - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutRules, + ); + + // Should only have the model, no rules + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only the model + expect(injected).toHaveLength(1); // Only the model + expect(additional.rules).toHaveLength(0); }); }); describe("Agent file model constraints", () => { it("should filter available models to only agent file model when specified", async () => { mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); await modelService.initialize( mockAssistant as any, @@ -312,7 +372,18 @@ describe("Agent file Integration Tests", () => { }); it("should allow all models when no agent file active", async () => { - await agentFileService.initialize(); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); await modelService.initialize( mockAssistant as any, @@ -332,7 +403,21 @@ describe("Agent file Integration Tests", () => { it("should handle agent loading errors gracefully", async () => { mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); - await agentFileService.initialize("owner/agent"); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + // The service should throw the error, not handle it gracefully + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile).toBeNull(); @@ -345,25 +430,34 @@ describe("Agent file Integration Tests", () => { expect(mockGetLlmApi).toHaveBeenCalled(); }); - it("should handle agent rule processing errors gracefully", async () => { - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - mockProcessRule.mockRejectedValue(new Error("Rule processing failed")); + it("should handle package identifier decoding errors gracefully", async () => { + // Mock decoding to throw an error + mockDecodePackageIdentifier.mockImplementation((id: string) => { + if (id === "invalid-rule") { + throw new Error("Invalid package identifier"); + } + return { type: "slug", slug: id, version: undefined }; + }); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + const agentFileStateWithInvalidRules = { + agentFile: mockAgentFile, + parsedRules: ["invalid-rule"], // This will throw an error when decoded + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - // Should not inject agent file rule but should preserve existing rules - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithInvalidRules, + ); + + // Should handle the error gracefully and only include valid package identifiers + expect(injected).toHaveLength(1); // Only the model should be included + expect(additional.rules).toHaveLength(0); }); // Removed test for missing service container since agent file service @@ -372,142 +466,209 @@ describe("Agent file Integration Tests", () => { it("should inject agent file prompt when agent file active", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseConfig = { - rules: ["existing rule"], - prompts: [], + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Agent file prompt should be added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be added to additional.prompts + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]).toMatchObject({ prompt: "You are an assistant.", name: expect.stringContaining("Test Agent"), }); - expect(enhancedConfig.rules).toHaveLength(2); }); - it("should add agent file prompt to config alongside other prompts", async () => { + it("should prepare agent file prompt for merging with other prompts", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseConfig = { - prompts: [{ name: "Existing", prompt: "existing-prompt" }], + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; - const baseOptions = {}; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Agent file prompt should be prepended to existing prompts - expect(enhancedConfig.prompts).toHaveLength(2); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be in additional block ready for merging + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ name: expect.stringContaining("Test Agent"), prompt: "You are an assistant.", }); - expect(enhancedConfig.prompts?.[1]).toMatchObject({ - name: "Existing", - prompt: "existing-prompt", - }); + + // mergeUnrolledAssistants would combine this with base config prompts + const { mergeUnrolledAssistants } = await import( + "@continuedev/config-yaml" + ); + const baseConfig = { + name: "original", + version: "1.0.0", + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + + const merged = mergeUnrolledAssistants(baseConfig, additional); + expect(merged.prompts).toHaveLength(2); }); it("should not add agent file prompt when agent file has no prompt", async () => { const agentFileWithoutPrompt = { ...mockAgentFile, - prompt: undefined, + prompt: "", }; - mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutPrompt); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - prompts: [{ name: "Existing", prompt: "existing-prompt" }], + const agentFileStateWithoutPrompt = { + agentFile: agentFileWithoutPrompt, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, }; + const baseOptions = {}; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutPrompt, + ); - // Should only have the existing prompt, no agent file prompt added - expect(enhancedConfig.prompts).toHaveLength(1); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ - name: "Existing", - prompt: "existing-prompt", - }); + // Should not have any prompts in additional block + expect(additional.prompts).toHaveLength(0); }); }); - describe("ConfigEnhancer prompt integration", () => { - it("should add agent file prompt to config.prompts when agent file active", async () => { + describe("ConfigService prompt integration", () => { + it("should process agent file prompt and user prompts together", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseOptions = { prompt: ["user-prompt"] }; - const baseConfig = { prompts: [] }; + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - // Enhance config with agent file state - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Verify that the agent file prompt was added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts).toHaveLength(1); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = { prompt: ["user-prompt"] }; + const agentFileState = agentFileService.getState(); + + // Process options with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Verify that the agent file prompt was added to additional block + expect(additional.prompts).toBeDefined(); + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ name: expect.stringContaining("Test Agent"), prompt: "You are an assistant.", description: "A test agent for integration testing", }); + + // User prompts should be in additional.rules as string rules + expect(additional.rules).toContain("user-prompt"); }); - it("should work end-to-end with agent file prompt in config", async () => { + it("should work end-to-end with agent file prompt processing", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.prompt).toBe("You are an assistant."); - const baseConfig = { prompts: [] }; const baseOptions = { prompt: ["Tell me about TypeScript"] }; - // Enhance config with agent file - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + // Process with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Verify agent file prompt is added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); - expect(enhancedConfig.prompts?.[0]?.prompt).toBe("You are an assistant."); - expect(enhancedConfig.prompts?.[0]?.name).toContain("Test Agent"); + // Verify agent file prompt is prepared for merging + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]?.prompt).toBe("You are an assistant."); + expect(additional.prompts?.[0]?.name).toContain("Test Agent"); + + // User prompt should be a string rule + expect(additional.rules).toContain("Tell me about TypeScript"); }); }); describe("Agent file data extraction", () => { it("should correctly extract all agent file properties", async () => { mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); @@ -528,7 +689,19 @@ describe("Agent file Integration Tests", () => { }; mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); - await agentFileService.initialize("owner/partial"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-3.5-turbo"); @@ -540,102 +713,88 @@ describe("Agent file Integration Tests", () => { describe("Agent file tools integration", () => { it("should inject MCP servers from agent file tools", async () => { - const agentFileWithTools = { - ...mockAgentFile, - tools: "owner/mcp1, another/mcp2:specific_tool", + const agentFileStateWithTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, another/mcp2:specific_tool", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1", "another/mcp2"], // Parsed MCP servers + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, }; - // Clear the default mock and setup specific mocks - mockLoadPackageFromHub.mockReset(); - // First call loads the agent file - mockLoadPackageFromHub.mockResolvedValueOnce(agentFileWithTools); - // Second call loads the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - // Third call loads mcp1 - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); - // Fourth call loads mcp2 - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp2" }); + const baseOptions = {}; - await agentFileService.initialize("owner/agent"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithTools, + ); - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], - }; - - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - expect(enhancedConfig.mcpServers).toHaveLength(3); - // MCPs are prepended in the order they are loaded - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); - expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" }); - expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" }); + // MCP servers should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("another/mcp2"); + expect(injected).toHaveLength(3); // model + 2 MCP servers }); it("should not inject MCP servers when agent file has no tools", async () => { - const agentWithoutTools = { - ...mockAgentFile, - tools: undefined, + const agentFileStateWithoutTools = { + agentFile: { + ...mockAgentFile, + tools: undefined, + }, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, }; - mockLoadPackageFromHub.mockReset(); - mockLoadPackageFromHub.mockResolvedValueOnce(agentWithoutTools); - await agentFileService.initialize("owner/agent"); + const baseOptions = {}; - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], - }; + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutTools, + ); - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - expect(enhancedConfig.mcpServers).toHaveLength(1); - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "existing-mcp" }); + // Should only have the model, no MCP servers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only model + expect(injected).toHaveLength(1); // Only model + expect(additional.mcpServers).toHaveLength(0); }); - it("should deduplicate MCP servers", async () => { - const agentFileWithDuplicateTools = { - ...mockAgentFile, - tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + it("should handle deduplicated MCP servers from parsing", async () => { + const agentFileStateWithDuplicateTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1"], // parseAgentFileTools already deduplicated + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, }; - // Clear the default mock and setup specific mocks - mockLoadPackageFromHub.mockReset(); - // First call loads the agent file - mockLoadPackageFromHub.mockResolvedValueOnce(agentFileWithDuplicateTools); - // Second call loads the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - // Third call: The parseAgentFileTools will extract only unique MCP servers, so only one loadPackageFromHub call - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); + const baseOptions = {}; - await agentFileService.initialize("owner/agent"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithDuplicateTools, + ); - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], // Changed to avoid confusion - }; - - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - // parseAgentFileTools deduplicates, so we only get mcp1 once - expect(enhancedConfig.mcpServers).toHaveLength(2); - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); - expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "existing-mcp" }); + // Should only process the deduplicated MCP server once + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(injected).toHaveLength(2); // model + deduplicated MCP server }); }); }); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 07145f705..7450476a6 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,7 +1,6 @@ +import { Configuration, DefaultApi } from "@continuedev/sdk/dist/api"; import { vi } from "vitest"; -import { AgentFileService } from "./AgentFileService.js"; - import { initializeServices, services } from "./index.js"; // Mock the onboarding module @@ -13,6 +12,15 @@ vi.mock("../onboarding.js", () => ({ // Mock auth module vi.mock("../auth/workos.js", () => ({ loadAuthConfig: vi.fn().mockReturnValue({}), + getConfigUri: vi.fn().mockReturnValue(null), +})); + +// Mock the config loader +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn().mockResolvedValue({ + config: { name: "test", version: "1.0.0" }, + source: { type: "test" }, + }), })); describe("initializeServices", () => { @@ -21,6 +29,37 @@ describe("initializeServices", () => { beforeEach(() => { // Reset all mocks vi.clearAllMocks(); + + // Mock service methods to avoid actual initialization + vi.spyOn(services.auth, "initialize").mockResolvedValue({ + authConfig: { + accessToken: "", + expiresAt: 123, + organizationId: "", + refreshToken: "", + userEmail: "", + }, + isAuthenticated: false, + }); + vi.spyOn(services.apiClient, "initialize").mockResolvedValue({ + apiClient: new DefaultApi( + new Configuration({ + basePath: "", + accessToken: "", + }), + ), + }); + vi.spyOn(services.agentFile, "initialize").mockResolvedValue({ + slug: null, + agentFile: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, + }); + vi.spyOn(services.config, "initialize").mockResolvedValue({ + config: { name: "test", version: "1.0.0" }, + configPath: undefined, + }); }); afterEach(() => { @@ -51,8 +90,9 @@ describe("initializeServices", () => { { slug: null, agentFile: null, - agentFileModelName: null, - agentFileService: expect.any(AgentFileService), + agentFileModel: null, + parsedRules: null, + parsedTools: null, }, ); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 79b0b4269..bb3a50df6 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -51,7 +51,6 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); const commandOptions = initOptions.options || {}; - // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); @@ -75,10 +74,40 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { commandOptions.config = CONFIG_PATH; } + serviceContainer.register( + SERVICE_NAMES.AUTH, + async () => { + return await authService.initialize(); + }, + [], // No dependencies + ); + + serviceContainer.register( + SERVICE_NAMES.API_CLIENT, + async () => { + const authState = await serviceContainer.get( + SERVICE_NAMES.AUTH, + ); + return apiClientService.initialize(authState.authConfig); + }, + [SERVICE_NAMES.AUTH], // Depends on auth + ); + serviceContainer.register( SERVICE_NAMES.AGENT_FILE, - () => agentFileService.initialize(commandOptions.agent), - [], + async () => { + const [authState, apiClientState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.API_CLIENT), + ]); + + return await agentFileService.initialize( + commandOptions.agent, + authState, + apiClientState, + ); + }, + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], ); serviceContainer.register( @@ -131,29 +160,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { [SERVICE_NAMES.TOOL_PERMISSIONS], ); - serviceContainer.register( - SERVICE_NAMES.AUTH, - () => authService.initialize(), - [], // No dependencies - ); - serviceContainer.register( SERVICE_NAMES.UPDATE, () => updateService.initialize(), [], // No dependencies ); - serviceContainer.register( - SERVICE_NAMES.API_CLIENT, - async () => { - const authState = await serviceContainer.get( - SERVICE_NAMES.AUTH, - ); - return apiClientService.initialize(authState.authConfig); - }, - [SERVICE_NAMES.AUTH], // Depends on auth - ); - serviceContainer.register( SERVICE_NAMES.CONFIG, async () => { @@ -200,13 +212,14 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { } } - return configService.initialize({ + return await configService.initialize({ authConfig: finalAuthState.authConfig, configPath, // organizationId: finalAuthState.organizationId || null, apiClient: apiClientState.apiClient, agentFileState, injectedConfigOptions: commandOptions, + isHeadless: initOptions.headless, }); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.AGENT_FILE], // Dependencies diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index cbe4121d4..8de9f26d9 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -2,6 +2,8 @@ import { AgentFile, AssistantUnrolled, ModelConfig, + parseAgentFileRules, + parseAgentFileTools, } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { AssistantConfig } from "@continuedev/sdk"; @@ -12,7 +14,6 @@ import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; import { PermissionMode } from "../permissions/types.js"; -import { AgentFileService } from "./AgentFileService.js"; import { type MCPService } from "./MCPService.js"; /** @@ -119,8 +120,9 @@ export interface StorageSyncServiceState { export interface AgentFileServiceState { agentFile: AgentFile | null; slug: string | null; - agentFileModelName: string | null; - agentFileService: AgentFileService | null; + agentFileModel: ModelConfig | null; + parsedTools: ReturnType | null; + parsedRules: ReturnType | null; } export type { ChatHistoryState } from "./ChatHistoryService.js"; diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 4564d20a9..24b83ee04 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -80,7 +80,7 @@ describe("getAllTools - Tool Filtering", () => { expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should include all tools in auto mode", async () => { @@ -107,7 +107,7 @@ describe("getAllTools - Tool Filtering", () => { expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should respect explicit exclude in normal mode", async () => { diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index b3af7eb65..6f97f9872 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -35,7 +35,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Should include write tools in normal mode expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); // Switch to plan mode (simulating Shift+Tab during streaming) toolPermissionService.switchMode("plan"); @@ -50,7 +50,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Should exclude write tools in plan mode expect(toolNames).not.toContain("Write"); - expect(toolNames).not.toContain("Edit"); + expect(toolNames).not.toContain("MultiEdit"); // Should still include read-only tools expect(toolNames).toContain("Read"); @@ -83,7 +83,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // getAllTools should immediately reflect auto mode (all tools allowed) tools = await getAllTools(); expect(tools.map((t) => t.function.name)).toContain("Write"); - expect(tools.map((t) => t.function.name)).toContain("Edit"); + expect(tools.map((t) => t.function.name)).toContain("MultiEdit"); expect(tools.map((t) => t.function.name)).toContain("Read"); }); diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts index f81211298..910c82f59 100644 --- a/extensions/cli/src/telemetry/telemetryService.ts +++ b/extensions/cli/src/telemetry/telemetryService.ts @@ -17,6 +17,7 @@ import { } from "@opentelemetry/semantic-conventions"; import { v4 as uuidv4 } from "uuid"; +import { ContinueErrorReason } from "../../../../core/util/errors.js"; import { isHeadlessMode } from "../util/cli.js"; import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js"; import { logger } from "../util/logger.js"; @@ -498,7 +499,7 @@ class TelemetryService { success: boolean; durationMs: number; error?: string; - errorReason?: string; + errorReason?: ContinueErrorReason; decision?: "accept" | "reject"; source?: string; toolParameters?: string; diff --git a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts b/extensions/cli/src/ui/hooks/useConfigSelector.test.ts deleted file mode 100644 index 9272cdbc0..000000000 --- a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, test } from "vitest"; - -describe("useConfigSelector", () => { - test("hook updated to use reactive service pattern", () => { - // This test documents that useConfigSelector has been updated - - // Changes made: - // 1. Removed manual onAssistantChange callback - // 2. Now calls services.config.updateConfigPath() - // 3. Lets ServiceContainer handle dependency management - // 4. Allows automatic UI updates via reactive system - - // The hook now properly: - // - Handles local config selection - // - Handles assistant config selection - // - Handles create config option - // - Provides error handling - // - Triggers reactive updates - - expect("hook").toBe("hook"); - }); - - test("integrates with reactive service system", () => { - // The hook integration follows the correct pattern: - // - User interaction → service method call - // - Service handles state update and notification - // - ServiceContainer manages dependency cascade - // - UI components re-render automatically - - expect("integration").toBe("integration"); - }); -}); diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 1862c9b23..2f234d784 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,5 +1,5 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginVersion=1.0.47 +pluginVersion=1.0.48 platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 41a94453e..b52a0fa31 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.3.18", + "version": "1.3.19", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index c5c87d219..c9374ea9a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -8,16 +8,20 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { walkDirAsync } from "core/indexing/walkDir"; import { isModelInstaller } from "core/llm"; +import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { startLocalLemonade } from "core/util/lemonadeHelper"; import { startLocalOllama } from "core/util/ollamaHelper"; -import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths"; +import { + getConfigJsonPath, + getConfigYamlPath, + setConfigFilePermissions, +} from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import * as YAML from "yaml"; import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; -import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -716,6 +720,7 @@ const getCommandsMap: ( const configYamlPath = getConfigYamlPath(); fs.writeFileSync(configYamlPath, YAML.stringify(configYaml)); + setConfigFilePermissions(configYamlPath); // Open config.yaml await openEditorAndRevealRange( diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index 9c9689b87..d0da3465f 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -94,7 +94,7 @@ export const callToolById = createAsyncThunk< output = result.content.contextItems; error = result.content.errorMessage ? new ContinueError( - ContinueErrorReason.Unspecified, + result.content.errorReason || ContinueErrorReason.Unspecified, result.content.errorMessage, ) : undefined; diff --git a/packages/config-yaml/src/load/injectBlocks.test.ts b/packages/config-yaml/src/load/injectBlocks.test.ts new file mode 100644 index 000000000..14feb97dc --- /dev/null +++ b/packages/config-yaml/src/load/injectBlocks.test.ts @@ -0,0 +1,538 @@ +import { Registry } from "../interfaces/index.js"; +import { PackageIdentifier } from "../interfaces/slugs.js"; +import { ConfigYaml } from "../schemas/index.js"; +import { unrollBlocks } from "./unroll.js"; + +// Mock Registry for testing +class MockRegistry implements Registry { + private content: Record = {}; + + setContent(id: string, content: string) { + this.content[id] = content; + } + + async getContent(id: PackageIdentifier): Promise { + const key = + id.uriType === "file" + ? id.fileUri + : `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + if (this.content[key]) { + return this.content[key]; + } + throw new Error(`Content not found for ${key}`); + } +} + +describe("injectBlocks with input-to-secret conversion", () => { + let mockRegistry: MockRegistry; + + beforeEach(() => { + mockRegistry = new MockRegistry(); + }); + + it("converts inputs to secrets in injected model blocks", async () => { + // Set up a basic assistant config + const assistant: ConfigYaml = { + name: "Test Assistant", + version: "1.0.0", + }; + + // Set up an injected block with input template variables in model + // Note: Block schema requires exactly 1 element in arrays + const injectedBlockContent = ` +name: OpenAI Block +version: 1.0.0 +schema: v1 +models: + - name: gpt-4 + provider: openai + model: gpt-4 + apiKey: \${{ inputs.openaiKey }} + apiBase: \${{ inputs.customEndpoint }} +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/openai-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/openai-block.yaml", + injectedBlockContent, + ); + + // Unroll with injected blocks + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], // inject the block + undefined, // no allowlist + undefined, // no blocklist + undefined, // no request options + ); + + expect(result.config).toBeDefined(); + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + + // Check that inputs were converted to secrets in the model + const model = result.config!.models![0]!; + expect(model.apiKey).toBe("${{ secrets.openaiKey }}"); + expect(model.apiBase).toBe("${{ secrets.customEndpoint }}"); + expect(model.name).toBe("gpt-4"); + expect(model.provider).toBe("openai"); + expect(model.model).toBe("gpt-4"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.openaiKey"); + expect(configStr).not.toContain("inputs.customEndpoint"); + }); + + it("converts inputs to secrets in injected rule blocks", async () => { + const assistant: ConfigYaml = { + name: "Rule Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Style Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Use \${{ inputs.codeStyle }} formatting consistently" +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/rules-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + // Check that input was converted to secret in the rule + // Note: string rules get wrapped in objects with sourceFile when injected + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Use ${{ secrets.codeStyle }} formatting consistently"); + } else { + expect(rule.rule).toBe( + "Use ${{ secrets.codeStyle }} formatting consistently", + ); + } + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.codeStyle"); + }); + + it("converts inputs to secrets in injected docs blocks", async () => { + const assistant: ConfigYaml = { + name: "Docs Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Docs Block +version: 1.0.0 +schema: v1 +docs: + - name: project-docs + startUrl: \${{ inputs.docsBaseUrl }}/api + rootUrl: \${{ inputs.docsBaseUrl }} + faviconUrl: \${{ inputs.docsBaseUrl }}/favicon.ico +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/docs-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/docs-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.docs).toBeDefined(); + expect(result.config!.docs!.length).toBe(1); + + // Check that inputs were converted to secrets in the doc config + const doc = result.config!.docs![0]!; + expect(doc.startUrl).toBe("${{ secrets.docsBaseUrl }}/api"); + expect(doc.rootUrl).toBe("${{ secrets.docsBaseUrl }}"); + expect(doc.faviconUrl).toBe("${{ secrets.docsBaseUrl }}/favicon.ico"); + expect(doc.name).toBe("project-docs"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.docsBaseUrl"); + }); + + it("converts inputs to secrets in injected prompt blocks", async () => { + const assistant: ConfigYaml = { + name: "Prompt Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Prompt Block +version: 1.0.0 +schema: v1 +prompts: + - name: custom-prompt + description: "A customizable prompt" + prompt: "You are a \${{ inputs.roleType }} assistant. Use \${{ inputs.responseStyle }} responses." +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/prompt-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/prompt-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.prompts).toBeDefined(); + expect(result.config!.prompts!.length).toBe(1); + + // Check that inputs were converted to secrets in the prompt + const prompt = result.config!.prompts![0]!; + expect(prompt.prompt).toBe( + "You are a ${{ secrets.roleType }} assistant. Use ${{ secrets.responseStyle }} responses.", + ); + expect(prompt.name).toBe("custom-prompt"); + expect(prompt.description).toBe("A customizable prompt"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.roleType"); + expect(configStr).not.toContain("inputs.responseStyle"); + }); + + it("handles multiple injected blocks of different types", async () => { + const assistant: ConfigYaml = { + name: "Multi-Block Assistant", + version: "1.0.0", + }; + + // Model block with inputs + const modelBlockContent = ` +name: API Model Block +version: 1.0.0 +schema: v1 +models: + - name: custom-api + provider: openai + model: \${{ inputs.modelName }} + apiKey: \${{ inputs.apiKey }} +`; + + // Rules block with inputs + const rulesBlockContent = ` +name: Dynamic Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Follow \${{ inputs.codingStandard }} conventions" +`; + + const modelBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/model-block.yaml", + }; + + const rulesBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent("file:///test/model-block.yaml", modelBlockContent); + mockRegistry.setContent("file:///test/rules-block.yaml", rulesBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [modelBlockId, rulesBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check model block conversion + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.model).toBe("${{ secrets.modelName }}"); + expect(model.apiKey).toBe("${{ secrets.apiKey }}"); + + // Check rules block conversion + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Follow ${{ secrets.codingStandard }} conventions"); + } else { + expect(rule.rule).toBe( + "Follow ${{ secrets.codingStandard }} conventions", + ); + } + + // Verify no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.modelName"); + expect(configStr).not.toContain("inputs.apiKey"); + expect(configStr).not.toContain("inputs.codingStandard"); + }); + + it("handles blocks with no template variables", async () => { + const assistant: ConfigYaml = { + name: "Static Assistant", + version: "1.0.0", + }; + + const staticBlockContent = ` +name: Static Block +version: 1.0.0 +schema: v1 +models: + - name: static-model + provider: ollama + model: llama3.1 + defaultCompletionOptions: + temperature: 0.5 + stream: false +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/static-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/static-block.yaml", + staticBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that static content is preserved as-is + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.name).toBe("static-model"); + expect(model.provider).toBe("ollama"); + expect(model.model).toBe("llama3.1"); + expect(model.defaultCompletionOptions?.temperature).toBe(0.5); + expect(model.defaultCompletionOptions?.stream).toBe(false); + }); + + it("preserves non-input template variables", async () => { + const assistant: ConfigYaml = { + name: "Mixed Variables Assistant", + version: "1.0.0", + }; + + const mixedBlockContent = ` +name: Mixed Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Input: \${{ inputs.userSetting }} | Secret: \${{ secrets.apiKey }} | Continue: \${{ continue.workspaceRoot }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/mixed-block.yaml", + }; + + mockRegistry.setContent("file:///test/mixed-block.yaml", mixedBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // Input should be converted to secret, others should remain unchanged + expect(ruleText).toBe( + "Input: ${{ secrets.userSetting }} | Secret: ${{ secrets.apiKey }} | Continue: ${{ continue.workspaceRoot }}", + ); + + // Verify only inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.userSetting"); + expect(configStr).toContain("secrets.apiKey"); + expect(configStr).toContain("continue.workspaceRoot"); + }); + + it("adds source file information to injected blocks", async () => { + const assistant: ConfigYaml = { + name: "Source Test Assistant", + version: "1.0.0", + }; + + const blockContent = ` +name: Source Block +version: 1.0.0 +schema: v1 +rules: + - name: custom-rule + rule: "Always add type hints with \${{ inputs.typeStyle }}" + description: "Enforce type hints for better code clarity" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/source-block.yaml", + }; + + mockRegistry.setContent("file:///test/source-block.yaml", blockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that rules have source file information + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]; + expect(rule).toMatchObject({ + name: "custom-rule", + rule: "Always add type hints with ${{ secrets.typeStyle }}", + description: "Enforce type hints for better code clarity", + sourceFile: "file:///test/source-block.yaml", + }); + + // Verify input was converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.typeStyle"); + }); + + it("handles complex nested input variables", async () => { + const assistant: ConfigYaml = { + name: "Nested Variables Assistant", + version: "1.0.0", + }; + + const nestedBlockContent = ` +name: Nested Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Database config: host=\${{ inputs.db.host }};port=\${{ inputs.db.port }};user=\${{ inputs.db.user }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/nested-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/nested-block.yaml", + nestedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // All nested inputs should be converted to secrets + expect(ruleText).toBe( + "Database config: host=${{ secrets.db.host }};port=${{ secrets.db.port }};user=${{ secrets.db.user }}", + ); + + // Verify all nested inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.db.host"); + expect(configStr).not.toContain("inputs.db.port"); + expect(configStr).not.toContain("inputs.db.user"); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.test.ts b/packages/config-yaml/src/load/unroll.test.ts index fb94017b1..9a308dd9b 100644 --- a/packages/config-yaml/src/load/unroll.test.ts +++ b/packages/config-yaml/src/load/unroll.test.ts @@ -1,5 +1,8 @@ import { PackageIdentifier } from "../interfaces/slugs.js"; -import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js"; +import { + parseMarkdownRuleOrAssistantUnrolled, + replaceInputsWithSecrets, +} from "./unroll.js"; describe("parseMarkdownRuleOrAssistantUnrolled tests", () => { it("parses valid YAML content as AssistantUnrolled", () => { @@ -88,3 +91,186 @@ model: # should be models expect(rule).toHaveProperty("rule", dubiousContent); }); }); + +describe("replaceInputsWithSecrets tests", () => { + it("replaces single input with secret", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value: \${{ inputs.apiKey }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("replaces multiple inputs with secrets", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + dbPassword: \${{ inputs.dbPassword }} + endpoint: \${{ inputs.endpoint }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).toContain("\${{ secrets.endpoint }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.endpoint }}"); + }); + + it("leaves secrets template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ secrets.existingSecret }} + dbPassword: \${{ inputs.dbPassword }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.existingSecret }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + }); + + it("leaves other template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + environment: \${{ continue.environment }} + customVar: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ continue.environment }}"); + expect(result).toContain("\${{ other.variable }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("handles yaml with no input template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + staticValue: "hello world" + secretValue: \${{ secrets.mySecret }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(yamlContent); // Should remain unchanged + expect(result).toContain("\${{ secrets.mySecret }}"); + }); + + it("handles empty string", () => { + const yamlContent = ""; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(""); + }); + + it("handles inputs with whitespace in template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.apiKey }} + value2: \${{\tinputs.tabbed\t}} + value3: \${{\n inputs.multiline \n}} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.tabbed }}"); + expect(result).toContain("\${{ secrets.multiline }}"); + expect(result).not.toContain("inputs.apiKey"); + expect(result).not.toContain("inputs.tabbed"); + expect(result).not.toContain("inputs.multiline"); + }); + + it("handles nested input keys", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + config: \${{ inputs.database.host }} + port: \${{ inputs.database.port }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.database.host }}"); + expect(result).toContain("\${{ secrets.database.port }}"); + expect(result).not.toContain("inputs.database.host"); + expect(result).not.toContain("inputs.database.port"); + }); + + it("handles multiple inputs on same line", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + connectionString: "host=\${{ inputs.host }};port=\${{ inputs.port }};user=\${{ inputs.user }}" +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.host }}"); + expect(result).toContain("\${{ secrets.port }}"); + expect(result).toContain("\${{ secrets.user }}"); + expect(result).not.toContain("inputs.host"); + expect(result).not.toContain("inputs.port"); + expect(result).not.toContain("inputs.user"); + }); + + it("preserves malformed template variables that don't start with inputs", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.valid }} + value2: \${{ malformed.inputs.something }} + value3: \${{ input.typo }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.valid }}"); + expect(result).toContain("\${{ malformed.inputs.something }}"); // Should remain unchanged + expect(result).toContain("\${{ input.typo }}"); // Should remain unchanged (typo in 'input') + expect(result).not.toContain("inputs.valid"); + }); + + it("handles YAML with complex structure", () => { + const yamlContent = ` +name: Complex Test +version: 1.0.0 +models: + - name: gpt-4 + apiKey: \${{ inputs.openaiKey }} +prompts: + - name: system + content: "You are a helpful assistant. API key: \${{ inputs.openaiKey }}" +rules: + - "Use \${{ inputs.style }} formatting" +data: + config: + database: + host: \${{ inputs.dbHost }} + password: \${{ inputs.dbPassword }} + external: + secret: \${{ secrets.external }} + other: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + // Check all inputs were replaced with secrets + expect(result).toContain("\${{ secrets.openaiKey }}"); + expect(result).toContain("\${{ secrets.style }}"); + expect(result).toContain("\${{ secrets.dbHost }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + // Check that non-input variables remain unchanged + expect(result).toContain("\${{ secrets.external }}"); + expect(result).toContain("\${{ other.variable }}"); + // Check that no input variables remain + expect(result).not.toContain("inputs.openaiKey"); + expect(result).not.toContain("inputs.style"); + expect(result).not.toContain("inputs.dbHost"); + expect(result).not.toContain("inputs.dbPassword"); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index bc8aa3785..cc05ccaf0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -239,6 +239,18 @@ export async function unrollAssistant( return result; } +export function replaceInputsWithSecrets(yamlContent: string): string { + const inputsToSecretsMap: Record = {}; + + getTemplateVariables(yamlContent) + .filter((v) => v.startsWith("inputs.")) + .forEach((v) => { + inputsToSecretsMap[v] = `\${{ ${v.replace("inputs.", "secrets.")} }}`; + }); + + return fillTemplateVariables(yamlContent, inputsToSecretsMap); +} + function renderTemplateData( rawYaml: string, templateData: Partial, @@ -284,7 +296,7 @@ export async function unrollAssistantFromContent( // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN - const templatedYaml = renderTemplateData(rawUnrolledYaml, { + let templatedYaml = renderTemplateData(rawUnrolledYaml, { secrets: extractFQSNMap(rawUnrolledYaml, [id]), }); @@ -529,16 +541,13 @@ export async function unrollBlocks( const injectedBlockPromises = injectBlocks.map(async (injectBlock) => { try { const blockConfigYaml = await registry.getContent(injectBlock); - const parsedBlock = parseMarkdownRuleOrConfigYaml( - blockConfigYaml, + const blockConfigYamlWithSecrets = + replaceInputsWithSecrets(blockConfigYaml); + const resolvedBlock = parseMarkdownRuleOrConfigYaml( + blockConfigYamlWithSecrets, injectBlock, ); - const blockType = getBlockType(parsedBlock); - const resolvedBlock = await resolveBlock( - injectBlock, - undefined, - registry, - ); + const blockType = getBlockType(resolvedBlock); return { blockType, diff --git a/packages/config-yaml/src/markdown/agentFiles.ts b/packages/config-yaml/src/markdown/agentFiles.ts index 5f072c4ac..4450cda0c 100644 --- a/packages/config-yaml/src/markdown/agentFiles.ts +++ b/packages/config-yaml/src/markdown/agentFiles.ts @@ -153,3 +153,10 @@ export function parseAgentFileTools(toolsString?: string): ParsedAgentTools { allBuiltIn, }; } + +export function parseAgentFileRules(rules: string) { + return rules + .split(",") + .map((r) => r.trim()) + .filter(Boolean); +}