├── .eslintrc.json ├── .gitignore ├── .vscode-test.mjs ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── .vscodeignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── build ├── azure-pipelines.pr.yml ├── azure-pipelines.pre-release.yml └── azure-pipelines.stable.yml ├── images ├── custom-label-demo.gif ├── discover-keybinding.gif ├── font-size-demo.gif ├── light-theme-demo.gif ├── new-window-with-profile-demo.gif └── vscode-commander.png ├── package-lock.json ├── package.json ├── scenarios.md ├── scripts └── prepare-prerelease-build.js ├── src ├── chatParticipant.tsx ├── configurationSearch.ts ├── extension.ts ├── jsonSchema.ts ├── test │ ├── extension.test.ts │ └── mocks.ts └── tools │ ├── runCommands.tsx │ ├── searchConfigurations.tsx │ ├── updateSettings.tsx │ └── utils.ts ├── tsconfig.json └── webpack.config.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "ecmaVersion": 6, 6 | "sourceType": "module" 7 | }, 8 | "plugins": [ 9 | "@typescript-eslint" 10 | ], 11 | "rules": { 12 | "@typescript-eslint/naming-convention": [ 13 | "warn", 14 | { 15 | "selector": "import", 16 | "format": [ "camelCase", "PascalCase" ] 17 | } 18 | ], 19 | "@typescript-eslint/semi": "warn", 20 | "curly": "warn", 21 | "eqeqeq": "warn", 22 | "no-throw-literal": "warn", 23 | "semi": "off" 24 | }, 25 | "ignorePatterns": [ 26 | "out", 27 | "dist", 28 | "**/*.d.ts" 29 | ] 30 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | .vscode-test/ 5 | *.vsix 6 | -------------------------------------------------------------------------------- /.vscode-test.mjs: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import { defineConfig } from '@vscode/test-cli'; 7 | 8 | export default defineConfig({ 9 | files: 'out/test/**/*.test.js', 10 | }); 11 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "dbaeumer.vscode-eslint", 6 | "amodio.tsl-problem-matcher", 7 | "ms-vscode.extension-test-runner" 8 | ] 9 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "args": [ 13 | "--extensionDevelopmentPath=${workspaceFolder}", 14 | "--profile-temp" 15 | ], 16 | "outFiles": [ 17 | "${workspaceFolder}/dist/**/*.js" 18 | ], 19 | "preLaunchTask": "${defaultBuildTask}" 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false, // set this to true to hide the "out" folder with the compiled JS files 5 | "dist": false // set this to true to hide the "dist" folder with the compiled JS files 6 | }, 7 | "search.exclude": { 8 | "out": true, // set this to false to include "out" folder in search results 9 | "dist": true // set this to false to include "dist" folder in search results 10 | }, 11 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 12 | "typescript.tsc.autoDetect": "off", 13 | 14 | "git.branchProtection": [ 15 | "main", 16 | "release/*" 17 | ], 18 | "git.branchProtectionPrompt": "alwaysCommitToNewBranch", 19 | "git.branchRandomName.enable": true, 20 | "git.pullBeforeCheckout": true, 21 | 22 | "githubPullRequests.defaultMergeMethod": "squash", 23 | } 24 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "watch", 9 | "problemMatcher": "$ts-webpack-watch", 10 | "isBackground": true, 11 | "presentation": { 12 | "reveal": "never", 13 | "group": "watchers" 14 | }, 15 | "group": { 16 | "kind": "build", 17 | "isDefault": true 18 | } 19 | }, 20 | { 21 | "type": "npm", 22 | "script": "watch-tests", 23 | "problemMatcher": "$tsc-watch", 24 | "isBackground": true, 25 | "presentation": { 26 | "reveal": "never", 27 | "group": "watchers" 28 | }, 29 | "group": "build" 30 | }, 31 | { 32 | "label": "tasks: watch-tests", 33 | "dependsOn": [ 34 | "npm: watch", 35 | "npm: watch-tests" 36 | ], 37 | "problemMatcher": [] 38 | } 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | build 4 | scripts 5 | out/** 6 | node_modules/** 7 | src/** 8 | .gitignore 9 | .yarnrc 10 | webpack.config.js 11 | vsc-extension-quickstart.md 12 | **/tsconfig.json 13 | **/.eslintrc.json 14 | **/*.map 15 | **/*.ts 16 | **/.vscode-test.* 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to the "vscode-commander" extension will be documented in this file. 4 | 5 | ## [Unreleased] 6 | 7 | - Initial release -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to 4 | agree to a Contributor License Agreement (CLA) declaring that you have the right to, 5 | and actually do, grant us the rights to use your contribution. For details, visit 6 | https://cla.microsoft.com. 7 | 8 | When you submit a pull request, a CLA-bot will automatically determine whether you need 9 | to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the 10 | instructions provided by the bot. You will only need to do this once across all repositories using our CLA. 11 | 12 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 13 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 14 | or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VS Code Commander 2 | 3 | The **VS Code Commander** extension acts as your personal assistant within Visual Studio Code. This powerful tool allows you to configure your VS Code environment using conversational, free-form text. With the VS Code Commander, you can: 4 | 5 | - Discover and explore various settings and commands. 6 | - Tailor your development environment to your needs. 7 | 8 | All of these actions can be performed through a simple and intuitive chat interface, making it easier than ever to manage your VS Code configuration. 9 | 10 | ## Update Settings 11 | With VS Code Commander, you can easily change your settings. If needed, you can also undo these changes effortlessly. 12 | 13 | ![Using VS Code Commander to switch to light theme](images/light-theme-demo.gif) 14 | 15 | You can quickly open the settings editor after changing a setting to review or further modify your configurations. 16 | 17 | ![Using VS Code Commander to create a custom editor label](images/custom-label-demo.gif) 18 | 19 | ## Run Commads 20 | Use VS Code Commander to execute various commands seamlessly through chat. 21 | 22 | ![Using VS Code Commander to open a new window with the python profile](images/new-window-with-profile-demo.gif) 23 | 24 | You can easily discover keybindings and quickly change them. 25 | 26 | ![Using VS Code Commander to find the keybinding for the toggle sidebar command](images/discover-keybinding.gif) 27 | 28 | 29 | # Trademarks 30 | 31 | This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies. -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /build/azure-pipelines.pr.yml: -------------------------------------------------------------------------------- 1 | # Notes: Only trigger a PR build for main and release, and skip build/rebuild 2 | # on changes in the news and .vscode folders. 3 | pr: 4 | autoCancel: true 5 | branches: 6 | include: ['main', 'release/*'] 7 | paths: 8 | exclude: ['/.vscode'] 9 | 10 | # Not the CI build for merges to main and release. 11 | trigger: none 12 | 13 | resources: 14 | repositories: 15 | - repository: templates 16 | type: github 17 | name: microsoft/vscode-engineering 18 | ref: main 19 | endpoint: Monaco 20 | 21 | extends: 22 | template: azure-pipelines/extension/stable.yml@templates 23 | parameters: 24 | # l10nSourcePaths: ./src 25 | buildSteps: 26 | - script: npm ci 27 | displayName: Install Dependencies 28 | 29 | - script: npm run lint 30 | displayName: Linting 31 | 32 | - script: npm run compile 33 | displayName: Compile 34 | 35 | # - script: npm run test 36 | # displayName: Run Tests 37 | -------------------------------------------------------------------------------- /build/azure-pipelines.pre-release.yml: -------------------------------------------------------------------------------- 1 | trigger: none 2 | pr: none 3 | 4 | resources: 5 | repositories: 6 | - repository: templates 7 | type: github 8 | name: microsoft/vscode-engineering 9 | ref: main 10 | endpoint: Monaco 11 | 12 | parameters: 13 | - name: publishExtension 14 | displayName: 🚀 Publish Extension 15 | type: boolean 16 | default: false 17 | 18 | extends: 19 | template: azure-pipelines/extension/pre-release.yml@templates 20 | parameters: 21 | ghCreateRelease: false 22 | publishExtension: ${{ parameters.publishExtension }} 23 | vscePackageArgs: "--allow-missing-repository" 24 | 25 | buildSteps: 26 | - script: npm ci 27 | displayName: Install dependencies 28 | 29 | - script: npm run lint 30 | displayName: Linting 31 | 32 | # - script: npm run test 33 | # displayName: Run Tests 34 | 35 | - script: npm run package 36 | displayName: Package 37 | 38 | - script: > 39 | node ./scripts/prepare-prerelease-build.js 40 | displayName: Generate package.json 41 | 42 | - script: | 43 | mv ./package.json ./package.json.bak 44 | mv ./package.prerelease.json ./package.json 45 | displayName: Override package.json 46 | 47 | tsa: 48 | config: 49 | areaPath: 'Visual Studio Code Web Extensions' 50 | serviceTreeID: '1788a767-5861-45fb-973b-c686b67c5541' 51 | enabled: true 52 | 53 | -------------------------------------------------------------------------------- /build/azure-pipelines.stable.yml: -------------------------------------------------------------------------------- 1 | trigger: none 2 | pr: none 3 | 4 | resources: 5 | repositories: 6 | - repository: templates 7 | type: github 8 | name: microsoft/vscode-engineering 9 | ref: main 10 | endpoint: Monaco 11 | 12 | parameters: 13 | - name: publishExtension 14 | displayName: 🚀 Publish Extension 15 | type: boolean 16 | default: false 17 | 18 | extends: 19 | template: azure-pipelines/extension/stable.yml@templates 20 | parameters: 21 | ghCreateRelease: false 22 | publishExtension: ${{ parameters.publishExtension }} 23 | 24 | buildSteps: 25 | - script: npm ci 26 | displayName: Install dependencies 27 | 28 | - script: npm run lint 29 | displayName: Linting 30 | 31 | # - script: npm run test 32 | # displayName: Run Tests 33 | 34 | - script: npm run package 35 | displayName: Package 36 | 37 | tsa: 38 | config: 39 | areaPath: 'Visual Studio Code Web Extensions' 40 | serviceTreeID: '1788a767-5861-45fb-973b-c686b67c5541' 41 | enabled: true 42 | -------------------------------------------------------------------------------- /images/custom-label-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/custom-label-demo.gif -------------------------------------------------------------------------------- /images/discover-keybinding.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/discover-keybinding.gif -------------------------------------------------------------------------------- /images/font-size-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/font-size-demo.gif -------------------------------------------------------------------------------- /images/light-theme-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/light-theme-demo.gif -------------------------------------------------------------------------------- /images/new-window-with-profile-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/new-window-with-profile-demo.gif -------------------------------------------------------------------------------- /images/vscode-commander.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/vscode-commander/935935c27e2b31719a35e5ab706885bedbd25571/images/vscode-commander.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vscode-commander", 3 | "publisher": "ms-vscode", 4 | "displayName": "VS Code Commander", 5 | "description": "Enables users to configure VS Code using chat. The extension allows to search for settings and commands and reason about them. The settings values can easily be updated and commands can be run.", 6 | "version": "0.2.0", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/microsoft/vscode-commander" 10 | }, 11 | "engines": { 12 | "vscode": "^1.95.0" 13 | }, 14 | "categories": [ 15 | "AI", 16 | "Chat" 17 | ], 18 | "main": "./dist/extension.js", 19 | "icon": "images/vscode-commander.png", 20 | "contributes": { 21 | "commands": [ 22 | { 23 | "command": "vscode-commander.undo-settings-updates", 24 | "title": "Undo settings updates" 25 | } 26 | ], 27 | "chatParticipants": [ 28 | { 29 | "id": "vscode-commander", 30 | "fullName": "VS Code Commander", 31 | "name": "commander", 32 | "description": "Assistant for configuring VS Code.", 33 | "isSticky": true 34 | } 35 | ], 36 | "languageModelTools": [ 37 | { 38 | "name": "searchConfigurations", 39 | "displayName": "Search Configurations", 40 | "modelDescription": "Use this tool to search for settings and commands. This will return all those settings and commands that contain the provided keywords. Each result will have a type to know if it is a setting or a command. A setting includes the description, default value, current value and other possible values and a command includes the description and possible arguments to be used to invoke the command.", 41 | "inputSchema": { 42 | "type": "object", 43 | "properties": { 44 | "keywords": { 45 | "type": "string", 46 | "description": "List of keywords to search for the settings and commands" 47 | } 48 | } 49 | }, 50 | "tags": [ 51 | "commander" 52 | ] 53 | }, 54 | { 55 | "name": "updateSettings", 56 | "displayName": "Update settings", 57 | "modelDescription": "Use this tool to update settings. This tool support bulk updates, so you can update multiple settings at once. Provide the settings to update as a key value pair of setting id and new value. The value of the setting must follow the setting schema.", 58 | "tags": [ 59 | "commander" 60 | ], 61 | "inputSchema": { 62 | "type": "object", 63 | "description": "Dictionary of settings to update. The key is the setting id and the value is the new value of the setting.", 64 | "properties": {} 65 | } 66 | }, 67 | { 68 | "name": "runCommand", 69 | "displayName": "Run command", 70 | "modelDescription": "Use this tool to run a command. This tool will run the command with the provided arguments if the command supports them. The arguments must follow the command arguments schema provided by the searchConfigurations.", 71 | "tags": [ 72 | "commander" 73 | ], 74 | "inputSchema": { 75 | "type": "object", 76 | "properties": { 77 | "key": { 78 | "type": "string", 79 | "description": "Id of the command" 80 | }, 81 | "argumentsArray": { 82 | "type": "string", 83 | "description": "Arguments to pass to the command as JSON stringified array" 84 | } 85 | } 86 | } 87 | } 88 | ] 89 | }, 90 | "extensionDependencies": [ 91 | "GitHub.copilot-chat" 92 | ], 93 | "scripts": { 94 | "vscode:prepublish": "npm run package", 95 | "compile": "webpack", 96 | "watch": "webpack --watch", 97 | "package": "webpack --mode production --devtool hidden-source-map", 98 | "compile-tests": "tsc -p . --outDir out", 99 | "watch-tests": "tsc -p . -w --outDir out", 100 | "pretest": "npm run compile-tests && npm run compile && npm run lint", 101 | "lint": "eslint src --ext ts", 102 | "test": "vscode-test" 103 | }, 104 | "devDependencies": { 105 | "@types/mocha": "^10.0.6", 106 | "@types/node": "20.x", 107 | "@types/vscode": "^1.95.0", 108 | "@typescript-eslint/eslint-plugin": "^7.11.0", 109 | "@typescript-eslint/parser": "^7.11.0", 110 | "@vscode/test-cli": "^0.0.10", 111 | "@vscode/test-electron": "^2.4.0", 112 | "eslint": "^8.57.0", 113 | "ts-loader": "^9.5.1", 114 | "typescript": "^5.4.5", 115 | "webpack": "^5.92.0", 116 | "webpack-cli": "^5.1.4" 117 | }, 118 | "dependencies": { 119 | "@vscode/prompt-tsx": "^0.3.0-alpha.12", 120 | "jsonc-parser": "^3.3.1", 121 | "minisearch": "^7.1.0" 122 | } 123 | } -------------------------------------------------------------------------------- /scenarios.md: -------------------------------------------------------------------------------- 1 | Here is the list of scenarios that this tool should be able to handle: 2 | 3 | 1. Save my files automatically 4 | 1. Increase the size of the text it is small 5 | 1. Change the font to Fira Code 6 | 1. Change typescript file label to have an apple emoji prefixed 7 | 1. Change to Monokai theme 8 | 1. Open {Profile Name} window 9 | 1. What are featured extensions today? 10 | 1. Go to my previous cursor position 11 | 1. Set a 2x3 editor grid -------------------------------------------------------------------------------- /scripts/prepare-prerelease-build.js: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | const fs = require('fs'); 7 | 8 | const json = JSON.parse(fs.readFileSync('./package.json').toString()); 9 | const stableVersion = json.version.match(/(\d+)\.(\d+)\.(\d+)/); 10 | const major = stableVersion[1]; 11 | const minor = stableVersion[2]; 12 | 13 | function prependZero(number) { 14 | if (number > 99) { 15 | throw new Error('Unexpected value to prepend with zero'); 16 | } 17 | return `${number < 10 ? '0' : ''}${number}`; 18 | } 19 | 20 | // update name, publisher and description 21 | // calculate version 22 | // If the format of the patch version is ever changed, the isPreRelease utility function should be updated. 23 | const date = new Date(); 24 | const month = date.getMonth() + 1; 25 | const day = date.getDate(); 26 | const hours = date.getHours(); 27 | const patch = `${date.getFullYear()}${prependZero(month)}${prependZero(day)}${prependZero(hours)}`; 28 | 29 | // The stable version should always be ..patch 30 | // For the nightly build, we keep the major, make the minor an odd number with +1, and add the timestamp as a patch. 31 | const preReleasePackageJson = Object.assign(json, { 32 | version: `${major}.${Number(minor)+1}.${patch}` 33 | }); 34 | 35 | fs.writeFileSync('./package.prerelease.json', JSON.stringify(preReleasePackageJson)); -------------------------------------------------------------------------------- /src/chatParticipant.tsx: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { SearchConfigurations } from './tools/searchConfigurations'; 8 | import { UpdateSettings } from './tools/updateSettings'; 9 | import { RunCommand } from './tools/runCommands'; 10 | import { ChatResponsePart } from '@vscode/prompt-tsx/dist/base/vscodeTypes'; 11 | import { 12 | AssistantMessage, 13 | BasePromptElementProps, PrioritizedList, 14 | PromptElement, 15 | PromptPiece, 16 | PromptSizing, 17 | UserMessage, 18 | PromptMetadata, 19 | ToolCall, 20 | Chunk, 21 | ToolMessage, 22 | renderPrompt 23 | } from '@vscode/prompt-tsx'; 24 | import { Configurations } from './configurationSearch'; 25 | import { getTsxDataFromToolsResult } from './tools/utils'; 26 | 27 | export interface TsxToolUserMetadata { 28 | readonly toolCallsMetadata: ToolCallsMetadata; 29 | } 30 | 31 | export interface ToolCallsMetadata { 32 | readonly toolCallRounds: ToolCallRound[]; 33 | readonly toolCallResults: Record; 34 | } 35 | 36 | export function isTsxToolUserMetadata(obj: unknown): obj is TsxToolUserMetadata { 37 | // If you change the metadata format, you would have to make this stricter or handle old objects in old ChatRequest metadata 38 | return !!obj && 39 | !!(obj as TsxToolUserMetadata).toolCallsMetadata && 40 | Array.isArray((obj as TsxToolUserMetadata).toolCallsMetadata.toolCallRounds); 41 | } 42 | 43 | interface HistoryProps extends BasePromptElementProps { 44 | readonly priority: number; 45 | readonly context: vscode.ChatContext; 46 | } 47 | 48 | class History extends PromptElement { 49 | 50 | render() { 51 | return ( 52 | 53 | {this.props.context.history.map((turn) => { 54 | if (turn instanceof vscode.ChatRequestTurn) { 55 | return {turn.prompt}; 56 | } else if (turn instanceof vscode.ChatResponseTurn) { 57 | return { 58 | turn.response.map(response => { 59 | if (response instanceof vscode.ChatResponseMarkdownPart) { 60 | return response.value.value; 61 | } 62 | }).join('') 63 | }; 64 | } 65 | })} 66 | 67 | ); 68 | } 69 | } 70 | 71 | interface ToolCallElementProps extends BasePromptElementProps { 72 | readonly toolCall: vscode.LanguageModelToolCallPart; 73 | readonly toolInvocationToken: vscode.ChatParticipantToolToken | undefined; 74 | readonly toolCallResult: vscode.LanguageModelToolResult | undefined; 75 | } 76 | 77 | class ToolCallElement extends PromptElement { 78 | async render(state: void, sizing: PromptSizing): Promise { 79 | const tool = vscode.lm.tools.find(t => t.name === this.props.toolCall.name); 80 | if (!tool) { 81 | console.error(`Tool not found: ${this.props.toolCall.name}`); 82 | return Tool not found; 83 | } 84 | 85 | const tokenizationOptions: vscode.LanguageModelToolInvocationOptions['tokenizationOptions'] = { 86 | tokenBudget: sizing.tokenBudget, 87 | countTokens: async (content: string) => sizing.countTokens(content), 88 | }; 89 | 90 | const toolResult = this.props.toolCallResult ?? 91 | await vscode.lm.invokeTool(this.props.toolCall.name, { input: this.props.toolCall.input, toolInvocationToken: this.props.toolInvocationToken, tokenizationOptions }, new vscode.CancellationTokenSource().token); 92 | 93 | const data = getTsxDataFromToolsResult(toolResult); 94 | if (!data) { 95 | console.error(`Tool result does not contain a TSX part: ${this.props.toolCall.name}`); 96 | return Tool result does not contain a TSX part; 97 | } 98 | 99 | return 100 | 101 | 102 | ; 103 | } 104 | } 105 | 106 | interface ToolCallsProps extends BasePromptElementProps { 107 | readonly toolCallRounds: ToolCallRound[]; 108 | readonly toolCallResults: Record; 109 | readonly toolInvocationToken: vscode.ChatParticipantToolToken | undefined; 110 | } 111 | 112 | class ToolCalls extends PromptElement { 113 | async render(state: void, sizing: PromptSizing) { 114 | if (!this.props.toolCallRounds.length) { 115 | return undefined; 116 | } 117 | 118 | return <> 119 | {this.props.toolCallRounds.map(round => this.renderOneToolCallRound(round))} 120 | Above is the result of calling one or more tools. The user cannot see the results, so you should explain them to the user if referencing them in your answer. 121 | ; 122 | } 123 | 124 | private renderOneToolCallRound(round: ToolCallRound) { 125 | const assistantToolCalls: ToolCall[] = round.toolCalls.map(tc => ({ type: 'function', function: { name: tc.name, arguments: JSON.stringify(tc.input) }, id: tc.callId })); 126 | return 127 | {round.response} 128 | {round.toolCalls.map(toolCall => 129 | 130 | )} 131 | ; 132 | } 133 | } 134 | 135 | interface ToolCallRound { 136 | readonly response: string; 137 | readonly toolCalls: vscode.LanguageModelToolCallPart[]; 138 | } 139 | 140 | interface CommanderPromptProps extends BasePromptElementProps { 141 | readonly request: vscode.ChatRequest; 142 | readonly context: vscode.ChatContext; 143 | readonly toolCallRounds: ToolCallRound[]; 144 | readonly toolCallResults: Record; 145 | } 146 | 147 | class CommanderPrompt extends PromptElement { 148 | 149 | render(state: void, sizing: PromptSizing, progress?: vscode.Progress, token?: vscode.CancellationToken) { 150 | return <> 151 | 152 | 153 | You are an assistant tasked with performing actions in VS Code. You will be given:
154 | 1. A user's request in natural language
155 | 2. Set of tools that can be used to perform the appropriate action
156 | Your task is to:
157 | 1. IMPORTANT: Never guess or rely from history or memory.
158 | 2. Analyze the user's request and come up with keywords, phrases and synonyms that are relevant to VS Code actions, commands, and settings, which describe the action they want to perform.
159 | 3. Use the {SearchConfigurations.ID} tool to find configurations that match with the keywords you found in previous step. Only use the {SearchConfigurations.ID} tool once.
160 | 4. Look for the most appropriate setting or command that matches the user's intent. Prefer a setting over a command if the user's request can be achieved by a setting change. Do not do the both to acheive the same result.
161 | 5. If you choose to update the setting:
162 |   a. Use the {UpdateSettings.ID} tool to update the setting to the value the user requested. If there are multiple settings to update, update them in bulk.
163 |   b. Always inform the user of each updated setting, including the setting ID and the new value.
164 | 6. If you choose to run a command:
165 |   a. If the command has arguments then use step by step reasoning to generate arguments that match the schema exactly in terms of names, types, and values.
166 |   b. Ensure the arguments are logically valid based on the user's request and the schema.
167 |   c. Use the {RunCommand.ID} tool to run a command found using the {SearchConfigurations.ID} tool.
168 |   d. Always inform the user what the keybinding is for the command, if applicable.
169 | 7. Never ask the user whether they think you should perform the action or suggest actions, If the user's request is clear, execute the action confidently. 170 |
171 | User Request: "{this.props.request.prompt}" 172 | 176 | 177 | ; 178 | } 179 | } 180 | 181 | export class ToolResultMetadata extends PromptMetadata { 182 | constructor( 183 | public toolCallId: string, 184 | public result: vscode.LanguageModelToolResult, 185 | ) { 186 | super(); 187 | } 188 | } 189 | 190 | export default function ( 191 | updatedSettings: { key: string, oldValue: any, newValue: any }[], 192 | ranCommands: { key: string, arguments: any }[], 193 | chatContext: { prompt: string }, 194 | configurations: Configurations, 195 | logger: vscode.LogOutputChannel 196 | ) { 197 | return async (request: vscode.ChatRequest, context: vscode.ChatContext, response: vscode.ChatResponseStream, token: vscode.CancellationToken) => { 198 | updatedSettings.splice(0, updatedSettings.length); 199 | ranCommands.splice(0, ranCommands.length); 200 | chatContext.prompt = request.prompt; 201 | 202 | const [model] = await vscode.lm.selectChatModels({ family: 'gpt-4o' }); 203 | 204 | const tools = vscode.lm.tools 205 | .filter(t => t.tags.includes('commander')) 206 | .map(t => ({ 207 | name: t.name, 208 | description: t.description, 209 | parametersSchema: t.inputSchema, 210 | })); 211 | 212 | 213 | const toolCallRounds: ToolCallRound[] = []; 214 | const toolCallResults: Record = {}; 215 | 216 | while (true) { 217 | const { messages, metadatas } = await renderPrompt(CommanderPrompt, { request, context, toolCallRounds, toolCallResults }, { modelMaxPromptTokens: model.maxInputTokens }, model, undefined, token); 218 | const toolResultMetadata = metadatas.getAll(ToolResultMetadata); 219 | 220 | if (toolResultMetadata?.length) { 221 | toolResultMetadata.forEach(meta => toolCallResults[meta.toolCallId] = meta.result); 222 | } 223 | 224 | logger.trace('sending request to the model'); 225 | const modelResponse = await model.sendRequest(messages, { tools }, token); 226 | logger.info('model responded.'); 227 | 228 | const { textResponse, toolCalls } = await processResponseStream(modelResponse, response, configurations); 229 | 230 | if (toolCalls.length === 0) { 231 | break; 232 | } 233 | 234 | toolCallRounds.push({ response: textResponse, toolCalls }); 235 | } 236 | 237 | if (updatedSettings.length && !ranCommands.length) { 238 | response.button({ 239 | command: 'vscode-commander.undo-settings-updates', 240 | title: 'Undo', 241 | }); 242 | } 243 | 244 | return { 245 | metadata: { 246 | toolCallsMetadata: { 247 | toolCallResults, 248 | toolCallRounds 249 | } 250 | } 251 | }; 252 | }; 253 | } 254 | 255 | const backtickPattern = /`([^\s`]+)`/g; 256 | async function processResponseStream(modelResponse: vscode.LanguageModelChatResponse, response: vscode.ChatResponseStream, configurations: Configurations): Promise<{ textResponse: string, toolCalls: vscode.LanguageModelToolCallPart[] }> { 257 | const toolCalls: vscode.LanguageModelToolCallPart[] = []; 258 | let textResponse = ''; 259 | let buffer = ""; 260 | 261 | for await (const part of modelResponse.stream) { 262 | // Process the text parts. Search for setting and command ids surrounded by backticks 263 | // and replace them with links to the settings or keybindings 264 | if (part instanceof vscode.LanguageModelTextPart) { 265 | buffer += part.value; 266 | 267 | const markdownString = new vscode.MarkdownString(undefined, true); 268 | markdownString.isTrusted = { enabledCommands: ['workbench.action.openSettings', 'workbench.action.openGlobalKeybindings'] }; 269 | 270 | let lastBacktickIndex = buffer.lastIndexOf('`'); 271 | const match = backtickPattern.exec(buffer); 272 | 273 | // Output the rendering of the configuration id if pattern matches 274 | if (match !== null) { 275 | const configurationIdWithBackticks = match[0]; 276 | const configurationId = match[1]; 277 | textResponse += buffer; // Do not annotate the ids in the response string 278 | 279 | const renderedConfigurationId = renderConfigurationId(configurationId, configurations); 280 | buffer = buffer.replace(configurationIdWithBackticks, renderedConfigurationId); 281 | markdownString.appendMarkdown(buffer); 282 | 283 | buffer = ""; 284 | backtickPattern.lastIndex = 0; 285 | } 286 | // Output everything if no backtick found 287 | else if (lastBacktickIndex === -1 || buffer.length > 80 /*If buffer is too large, flush it. Commands/Settings are shorter*/) { 288 | textResponse += buffer; 289 | markdownString.appendMarkdown(buffer); 290 | buffer = ""; 291 | } 292 | // Output everything before the last '`' which might be part of an incomplete match 293 | else { 294 | const textBeforeTick = buffer.substring(0, lastBacktickIndex); 295 | textResponse += textBeforeTick; 296 | markdownString.appendMarkdown(textBeforeTick); 297 | buffer = buffer.substring(lastBacktickIndex); // Keep the potential match in the buffer 298 | } 299 | 300 | response.markdown(markdownString); 301 | 302 | } else if (part instanceof vscode.LanguageModelToolCallPart) { 303 | const tool = vscode.lm.tools.find(t => t.name === part.name); 304 | 305 | if (!tool) { 306 | continue; 307 | } 308 | 309 | toolCalls.push(part); 310 | } 311 | } 312 | 313 | return { textResponse, toolCalls }; 314 | } 315 | 316 | function renderConfigurationId(potentialConfigurationId: string, configurations: Configurations): string { 317 | const setting = configurations.getSetting(potentialConfigurationId); 318 | if (setting) { 319 | return `[\`${setting.key}\`](command:workbench.action.openSettings?%5B%22${setting.key}%22%5D "Open Setting")`; 320 | } 321 | 322 | const command = configurations.getCommand(potentialConfigurationId); 323 | if (command) { 324 | return `[\`${command.key}\`](command:workbench.action.openGlobalKeybindings?%5B%22${command.key}%22%5D "Open Keyboard Shortcuts")`; 325 | } 326 | 327 | return `\`${potentialConfigurationId}\``; 328 | } -------------------------------------------------------------------------------- /src/configurationSearch.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import * as jsonc from 'jsonc-parser'; 8 | import MiniSearch from 'minisearch'; 9 | import { followReference, IJSONSchema, resolveReferences } from './jsonSchema'; 10 | 11 | type Configuration = { type: string, key: string, description: string }; 12 | type Searchables = { key: string, description: string, id: string, object: T & Configuration }; 13 | export type Setting = Configuration & { type: 'setting', defaultValue: any; valueType: string, restricted: boolean }; 14 | export type Command = Configuration & { type: 'command', keybinding?: string, argsSchema?: IJSONSchema | string, hasArguments?: false }; 15 | 16 | const settingsSchemaResource = vscode.Uri.parse('vscode://schemas/settings/default'); 17 | const keybindingsSchemaResource = vscode.Uri.parse('vscode://schemas/keybindings'); 18 | const defaultKeybindingsResource = vscode.Uri.parse('vscode://defaultsettings/keybindings.json'); 19 | 20 | interface IUserFriendlyKeybinding { 21 | key: string; 22 | command: string; 23 | args?: any; 24 | when?: string; 25 | } 26 | 27 | export class Configurations implements vscode.Disposable { 28 | 29 | private readonly miniSearch: MiniSearch>; 30 | 31 | private readonly settings = new Map(); 32 | private readonly commands = new Map(); 33 | 34 | private initPromise: Promise | undefined; 35 | private disposables: vscode.Disposable[] = []; 36 | 37 | constructor( 38 | private readonly logger: vscode.LogOutputChannel, 39 | ) { 40 | this.miniSearch = new MiniSearch>({ 41 | fields: ['key', 'description'], 42 | storeFields: ['key', 'object'], 43 | }); 44 | this.init(); 45 | this.disposables.push(vscode.workspace.onDidChangeTextDocument(e => { 46 | if (e.document.uri.toString() === settingsSchemaResource.toString() 47 | || e.document.uri.toString() === defaultKeybindingsResource.toString() 48 | || e.document.uri.toString() === keybindingsSchemaResource.toString()) { 49 | this.initPromise = undefined; 50 | } 51 | })); 52 | } 53 | 54 | private init(): Promise { 55 | if (!this.initPromise) { 56 | this.initPromise = (async () => { 57 | this.miniSearch.removeAll(); 58 | const [searchableSettings, searchableCommands] = await Promise.all([ 59 | this.getSearchableSettings(), 60 | this.getSearchableCommands() 61 | ]); 62 | this.logger.info(`Found ${searchableSettings.length} searchable settings`); 63 | this.logger.info(`Found ${searchableCommands.length} searchable commands`); 64 | this.miniSearch.addAll([...searchableSettings, ...searchableCommands]); 65 | })(); 66 | } 67 | return this.initPromise; 68 | } 69 | 70 | private async getSearchableSettings(): Promise[]> { 71 | const defaultSettingsSchemaDocument = await vscode.workspace.openTextDocument(settingsSchemaResource); 72 | 73 | const settings: IJSONSchema = JSON.parse(defaultSettingsSchemaDocument.getText()); 74 | if (!settings.properties) { 75 | return []; 76 | } 77 | 78 | const searchableSettings: Searchables[] = []; 79 | for (const key in settings.properties) { 80 | if (key.startsWith('[')) { 81 | continue; 82 | } 83 | 84 | let property: IJSONSchema | undefined = settings.properties[key]; 85 | 86 | // If property has a definition reference, retrieve it 87 | if (property.$ref !== undefined) { 88 | property = { ...property, ...followReference(property.$ref, settings) }; 89 | delete property.$ref; 90 | } 91 | 92 | if (!property) { 93 | continue; 94 | } 95 | 96 | // Add enum descriptions if applicable 97 | let description = property.markdownDescription ?? property.description ?? ''; 98 | if (property.type === 'string' && property.enum) { 99 | description += '\n' + enumsDescription(property.enum, property.enumDescriptions ?? property.markdownEnumDescriptions ?? []); 100 | } 101 | 102 | searchableSettings.push({ 103 | id: `settings:${key}`, 104 | key, 105 | description, 106 | object: { 107 | key, 108 | description, 109 | defaultValue: property.default, 110 | valueType: (Array.isArray(property.type) ? property.type[0] : property.type) ?? 'string', 111 | type: 'setting', 112 | restricted: !!(property as any).restricted, 113 | } 114 | }); 115 | } 116 | 117 | searchableSettings.forEach(setting => this.settings.set(setting.key, setting.object)); 118 | 119 | return searchableSettings; 120 | } 121 | 122 | private async getSearchableCommands(): Promise[]> { 123 | const [defaultKeybindingsDocument, keybindingsSchemaResourceDocument] = await Promise.all([ 124 | vscode.workspace.openTextDocument(defaultKeybindingsResource), 125 | vscode.workspace.openTextDocument(keybindingsSchemaResource), 126 | ]); 127 | const keybindingsSchema: IJSONSchema = JSON.parse(keybindingsSchemaResourceDocument.getText()); 128 | const defaultKeybindings: IUserFriendlyKeybinding[] = jsonc.parse(defaultKeybindingsDocument.getText()); 129 | 130 | // Find all commands with arguments 131 | const commandsWithArgs = new Map(); 132 | for (const p of keybindingsSchema.definitions?.['commandsSchemas']?.allOf ?? []) { 133 | 134 | // Resolve all $ref in the command schema 135 | resolveReferences(p, keybindingsSchema); 136 | 137 | const commandId: string | undefined = p.if?.properties?.command?.const; 138 | if (commandId === undefined) { 139 | continue; 140 | } 141 | 142 | const commandSchema = p.then; 143 | if (commandSchema === undefined) { 144 | continue; 145 | } 146 | 147 | const argumentsSchema = commandSchema.properties?.args; 148 | if (!argumentsSchema) { 149 | this.logger.info(`Skipping command ${commandId}: Does not have a args schema: ${JSON.stringify(commandSchema)}`); 150 | continue; 151 | } 152 | 153 | this.logger.trace(`Found command with args: ${commandId}, ${argumentsSchema}`); 154 | commandsWithArgs.set(commandId, argumentsSchema); 155 | } 156 | 157 | const searchableCommands: Searchables[] = []; 158 | 159 | const commandNames = keybindingsSchema.definitions?.['commandNames']; 160 | if (!commandNames?.enumDescriptions) { 161 | return searchableCommands; 162 | } 163 | 164 | for (let index = 0; index < commandNames.enumDescriptions.length; index++) { 165 | const commandDescription = commandNames.enumDescriptions[index]; 166 | const commandId: string | undefined = commandNames.enum?.[index]; 167 | if (!commandId) { 168 | continue; 169 | } 170 | 171 | if (commandId.toLowerCase().includes('focus')) { 172 | continue; // Focus commands do nothing if the view is not open/visible so don't show them 173 | } 174 | 175 | if (!commandDescription) { 176 | this.logger.trace(`Skipping command ${commandId}: Does not have a description`); 177 | continue; 178 | } 179 | 180 | const argsSchema = commandsWithArgs.get(commandId); 181 | searchableCommands.push({ 182 | id: `command:${commandId}`, 183 | key: commandId, 184 | description: commandDescription, 185 | object: { 186 | key: commandId, 187 | description: commandDescription, 188 | type: 'command', 189 | keybinding: defaultKeybindings.find(keybinding => keybinding.command === commandId)?.key, 190 | argsSchema: commandId === 'vscode.setEditorLayout' ? commandDescription : argsSchema, 191 | hasArguments: argsSchema === undefined ? false : undefined, 192 | } 193 | }); 194 | } 195 | 196 | searchableCommands.forEach(command => this.commands.set(command.key, command.object)); 197 | 198 | return searchableCommands; 199 | } 200 | 201 | async search(keywords: string, limit: number): Promise<(Setting | Command)[]> { 202 | await this.init(); 203 | 204 | // search for exact match on key 205 | if (this.settings.has(keywords)) { 206 | return [this.settings.get(keywords)!]; 207 | } 208 | 209 | if (this.commands.has(keywords)) { 210 | return [this.commands.get(keywords)!]; 211 | } 212 | 213 | const results = this.miniSearch.search(keywords, { fields: ['key', 'description'] }); 214 | return results.slice(0, limit).map(result => result.object); 215 | } 216 | 217 | getSetting(key: string): Setting | undefined { 218 | return this.settings.get(key); 219 | } 220 | 221 | getCommand(key: string): Command | undefined { 222 | return this.commands.get(key); 223 | } 224 | 225 | dispose() { 226 | this.disposables.forEach(disposable => disposable.dispose()); 227 | } 228 | } 229 | 230 | function enumsDescription(enumKeys: string[], enumDescriptions: string[]): string { 231 | if (enumKeys.length === 0) { 232 | return ''; 233 | } 234 | 235 | const prefix = 'Allowed Enums:\n'; 236 | const enumsDescriptions = enumKeys.map((enumKey, index) => { 237 | const enumDescription = enumDescriptions[index]; 238 | return enumKey + (enumDescription ? `: ${enumDescription}` : ''); 239 | }).join('\n'); 240 | 241 | return prefix + enumsDescriptions; 242 | } 243 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { Configurations } from './configurationSearch'; 8 | import { SearchConfigurations } from './tools/searchConfigurations'; 9 | import { UpdateSettings } from './tools/updateSettings'; 10 | import { RunCommand } from './tools/runCommands'; 11 | import createChatParticipant from './chatParticipant'; 12 | 13 | const UNDO_SETTINGS_UPDATES_COMMAND_ID = 'vscode-commander.undo-settings-updates'; 14 | 15 | export function activate(context: vscode.ExtensionContext) { 16 | const updatedSettings: { key: string, oldValue: any, newValue: any }[] = []; 17 | const ranCommands: { key: string, arguments: any }[] = []; 18 | const chatContext: { prompt: string } = { prompt: '' }; 19 | 20 | const logger = vscode.window.createOutputChannel('VS Code Commander', { log: true }); 21 | const configurations = new Configurations(logger); 22 | 23 | context.subscriptions.push(configurations); 24 | 25 | context.subscriptions.push(vscode.commands.registerCommand(UNDO_SETTINGS_UPDATES_COMMAND_ID, async () => { 26 | for (const { key, oldValue } of updatedSettings) { 27 | await vscode.workspace.getConfiguration().update(key, oldValue, vscode.ConfigurationTarget.Global); 28 | } 29 | })); 30 | 31 | context.subscriptions.push(vscode.chat.createChatParticipant('vscode-commander', createChatParticipant(updatedSettings, ranCommands, chatContext, configurations, logger))); 32 | context.subscriptions.push(vscode.lm.registerTool(SearchConfigurations.ID, new SearchConfigurations(configurations, logger))); 33 | context.subscriptions.push(vscode.lm.registerTool(UpdateSettings.ID, new UpdateSettings(updatedSettings, configurations, logger))); 34 | context.subscriptions.push(vscode.lm.registerTool(RunCommand.ID, new RunCommand(chatContext, ranCommands, configurations, logger))); 35 | } 36 | 37 | export function deactivate() { } 38 | -------------------------------------------------------------------------------- /src/jsonSchema.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | export type JSONSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'array' | 'object'; 7 | 8 | export interface IJSONSchema { 9 | id?: string; 10 | $id?: string; 11 | $schema?: string; 12 | type?: JSONSchemaType | JSONSchemaType[]; 13 | title?: string; 14 | default?: any; 15 | definitions?: IJSONSchemaMap; 16 | description?: string; 17 | properties?: IJSONSchemaMap; 18 | patternProperties?: IJSONSchemaMap; 19 | additionalProperties?: boolean | IJSONSchema; 20 | minProperties?: number; 21 | maxProperties?: number; 22 | dependencies?: IJSONSchemaMap | { [prop: string]: string[] }; 23 | items?: IJSONSchema | IJSONSchema[]; 24 | minItems?: number; 25 | maxItems?: number; 26 | uniqueItems?: boolean; 27 | additionalItems?: boolean | IJSONSchema; 28 | pattern?: string; 29 | minLength?: number; 30 | maxLength?: number; 31 | minimum?: number; 32 | maximum?: number; 33 | exclusiveMinimum?: boolean | number; 34 | exclusiveMaximum?: boolean | number; 35 | multipleOf?: number; 36 | required?: string[]; 37 | $ref?: string; 38 | anyOf?: IJSONSchema[]; 39 | allOf?: IJSONSchema[]; 40 | oneOf?: IJSONSchema[]; 41 | not?: IJSONSchema; 42 | enum?: any[]; 43 | format?: string; 44 | 45 | // schema draft 06 46 | const?: any; 47 | contains?: IJSONSchema; 48 | propertyNames?: IJSONSchema; 49 | examples?: any[]; 50 | 51 | // schema draft 07 52 | $comment?: string; 53 | if?: IJSONSchema; 54 | then?: IJSONSchema; 55 | else?: IJSONSchema; 56 | 57 | // schema 2019-09 58 | unevaluatedProperties?: boolean | IJSONSchema; 59 | unevaluatedItems?: boolean | IJSONSchema; 60 | minContains?: number; 61 | maxContains?: number; 62 | deprecated?: boolean; 63 | dependentRequired?: { [prop: string]: string[] }; 64 | dependentSchemas?: IJSONSchemaMap; 65 | $defs?: { [name: string]: IJSONSchema }; 66 | $anchor?: string; 67 | $recursiveRef?: string; 68 | $recursiveAnchor?: string; 69 | $vocabulary?: any; 70 | 71 | // schema 2020-12 72 | prefixItems?: IJSONSchema[]; 73 | $dynamicRef?: string; 74 | $dynamicAnchor?: string; 75 | 76 | // VSCode extensions 77 | 78 | defaultSnippets?: IJSONSchemaSnippet[]; 79 | errorMessage?: string; 80 | patternErrorMessage?: string; 81 | deprecationMessage?: string; 82 | markdownDeprecationMessage?: string; 83 | enumDescriptions?: string[]; 84 | markdownEnumDescriptions?: string[]; 85 | markdownDescription?: string; 86 | doNotSuggest?: boolean; 87 | suggestSortText?: string; 88 | allowComments?: boolean; 89 | allowTrailingCommas?: boolean; 90 | } 91 | 92 | export interface IJSONSchemaMap { 93 | [name: string]: IJSONSchema; 94 | } 95 | 96 | export interface IJSONSchemaSnippet { 97 | label?: string; 98 | description?: string; 99 | body?: any; // a object that will be JSON stringified 100 | bodyText?: string; // an already stringified JSON object that can contain new lines (\n) and tabs (\t) 101 | } 102 | 103 | function parseReference($ref: string): string[] | undefined { 104 | if (!$ref.startsWith('#/')) { 105 | return undefined; 106 | } 107 | return $ref.split('/').slice(1); 108 | } 109 | 110 | export function followReference($ref: string, document: IJSONSchema): IJSONSchema | undefined { 111 | const parsedRef = parseReference($ref); 112 | if (!parsedRef) { 113 | return undefined; 114 | } 115 | 116 | let current: any = document; 117 | for (const part of parsedRef) { 118 | if (current.hasOwnProperty(part)) { 119 | current = current[part]; 120 | } else { 121 | return undefined; 122 | } 123 | } 124 | return current; 125 | } 126 | export function resolveReferences(partialSchema: any, documentSchema: IJSONSchema): void { 127 | // Check for nested $ref properties and replace them with their definitions 128 | // Recursive references are included only once to avoid infinite recursion 129 | 130 | const checkAndReplaceRef = (schema: any, followedReferences: string[]) => { 131 | if (typeof schema !== 'object' || schema === null) { 132 | return; 133 | } 134 | 135 | for (const key in schema) { 136 | if (key === '$ref' && typeof schema['$ref'] === 'string') { 137 | // Only resolve a reference once to avoid infinite recursion and very large schemas 138 | if (followedReferences.includes(schema['$ref'])) { 139 | continue; 140 | } 141 | 142 | // Make a copy so a different path can also resolve this reference once 143 | const newFollowedReferences = [...followedReferences, schema['$ref']]; 144 | 145 | // retrieve the referenced definition 146 | const def = followReference(schema['$ref'], documentSchema); 147 | delete schema['$ref']; 148 | if (!def) { 149 | continue; 150 | } 151 | 152 | for (const defKey in def) { 153 | schema[defKey] = (def as any)[defKey]; 154 | } 155 | // rerun for the same schema again including the resolved reference 156 | checkAndReplaceRef(schema, newFollowedReferences); 157 | break; 158 | } else { 159 | checkAndReplaceRef(schema[key], followedReferences); 160 | } 161 | } 162 | }; 163 | 164 | checkAndReplaceRef(partialSchema, []); 165 | } 166 | -------------------------------------------------------------------------------- /src/test/extension.test.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import assert from 'assert'; 7 | import { MockConfigurations } from './mocks'; 8 | 9 | suite('Configuration Search', () => { 10 | 11 | const configurationSearch = new MockConfigurations(); 12 | 13 | test('Exact command id match', async () => { 14 | const configurations = await configurationSearch.search('vscode.setEditorLayout', 50); 15 | assert.strictEqual(configurations.length, 1); 16 | assert.strictEqual(configurations[0].type, 'command'); 17 | assert.strictEqual(configurations[0].key, 'vscode.setEditorLayout'); 18 | }); 19 | 20 | test('Exact setting id match', async () => { 21 | const configurations = await configurationSearch.search('workbench.editor.customLabels.patterns', 50); 22 | assert.strictEqual(configurations.length, 1); 23 | assert.strictEqual(configurations[0].type, 'setting'); 24 | assert.strictEqual(configurations[0].key, 'workbench.editor.customLabels.patterns'); 25 | }); 26 | 27 | test('Keywords: workbench editor custom labels pattern', async () => { 28 | const configurations = await configurationSearch.search('workbench editor custom labels pattern', 20); 29 | assert.strictEqual(configurations.some(c => c.key === 'workbench.editor.customLabels.patterns'), true); 30 | }); 31 | 32 | test('Keywords: editor label', async () => { 33 | const configurations = await configurationSearch.search('editor label', 20); 34 | assert.strictEqual(configurations.some(c => c.key === 'workbench.editor.customLabels.patterns'), true); 35 | }); 36 | 37 | test('Keywords: label pattern', async () => { 38 | const configurations = await configurationSearch.search('label pattern', 20); 39 | assert.strictEqual(configurations.some(c => c.key === 'workbench.editor.customLabels.patterns'), true); 40 | }); 41 | 42 | teardown(() => { 43 | configurationSearch.dispose(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/test/mocks.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { Configurations } from "../configurationSearch"; 8 | 9 | export class MockConfigurations extends Configurations { 10 | constructor() { 11 | super(new MockLogOutputChannel()); 12 | } 13 | } 14 | 15 | export class MockLogOutputChannel implements vscode.LogOutputChannel { 16 | logLevel: vscode.LogLevel = vscode.LogLevel.Info; 17 | readonly name: string = 'MockLogOutputChannel'; 18 | private logLevelEmitter = new vscode.EventEmitter(); 19 | readonly onDidChangeLogLevel: vscode.Event = this.logLevelEmitter.event; 20 | 21 | trace(): void { } 22 | debug(): void { } 23 | info(): void { } 24 | warn(): void { } 25 | error(): void { } 26 | append(): void { } 27 | appendLine(): void { } 28 | replace(): void { } 29 | clear(): void { } 30 | show(): void { } 31 | hide(): void { } 32 | dispose(): void { } 33 | } -------------------------------------------------------------------------------- /src/tools/runCommands.tsx: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { BasePromptElementProps, PromptElement, renderElementJSON } from '@vscode/prompt-tsx'; 8 | import { Configurations, Command } from '../configurationSearch'; 9 | import { createLanguageModelToolResult } from './utils'; 10 | 11 | const commandsRequiringConfirmation: { [key: string]: vscode.LanguageModelToolConfirmationMessages } = { 12 | 'workbench.action.resetViewLocations': { 13 | title: 'Reset View Locations', 14 | message: 'This will reset all views to their default locations. Are you sure you want to do this?', 15 | }, 16 | }; 17 | 18 | const commandsWithComplexArguments = new Set(['vscode.setEditorLayout']); 19 | 20 | const complexArgumentSetterTool: vscode.LanguageModelChatTool = { 21 | name: 'SetArgument', 22 | description: 'Use this tool to set the argument for the command', 23 | inputSchema: { 24 | type: "object", 25 | properties: { 26 | argument: { 27 | type: "string", 28 | description: "Argument to pass to the command", 29 | } 30 | } 31 | } 32 | }; 33 | 34 | interface RunCommandResultSuccessProps extends BasePromptElementProps { 35 | readonly commandId: string; 36 | readonly result: unknown; 37 | } 38 | 39 | interface RunCommandResultErrorProps extends BasePromptElementProps { 40 | readonly error: string; 41 | } 42 | 43 | type RunCommandResultProps = RunCommandResultSuccessProps | RunCommandResultErrorProps; 44 | 45 | function isSuccess(props: RunCommandResultProps): props is RunCommandResultSuccessProps { 46 | return !!(props as RunCommandResultSuccessProps).commandId; 47 | } 48 | 49 | class RunCommandResult extends PromptElement { 50 | 51 | render() { 52 | if (!isSuccess(this.props)) { 53 | return <>{this.props.error}; 54 | } else if (this.props.result) { 55 | return <>The result of executing the command {this.props.commandId} is {JSON.stringify(this.props.result)}; 56 | } else { 57 | return <>Command {this.props.commandId} has been executed; 58 | } 59 | } 60 | } 61 | 62 | export class RunCommand implements vscode.LanguageModelTool<{ key?: string, argumentsArray?: string }> { 63 | 64 | static readonly ID = 'runCommand'; 65 | 66 | constructor( 67 | private readonly chatContext: { prompt: string }, 68 | private readonly ranCommands: { key: string, arguments: any }[], 69 | private readonly configurations: Configurations, 70 | private readonly logger: vscode.LogOutputChannel, 71 | ) { 72 | } 73 | 74 | prepareInvocation(options: vscode.LanguageModelToolInvocationPrepareOptions<{ key?: string, argumentsArray?: string }>, token: vscode.CancellationToken): vscode.ProviderResult { 75 | // validate parameters 76 | const commandId = options.input.key; 77 | if (typeof commandId !== 'string' || !commandId.length) { 78 | return undefined; 79 | } 80 | 81 | return { 82 | invocationMessage: `Running \`${commandId}\``, 83 | confirmationMessages: commandsRequiringConfirmation[commandId] 84 | }; 85 | } 86 | 87 | async invoke(options: vscode.LanguageModelToolInvocationOptions<{ key?: string, argumentsArray?: string }>, token: vscode.CancellationToken): Promise { 88 | // validate parameters 89 | const commandId = options.input.key; 90 | if (typeof commandId !== 'string' || !commandId.length) { 91 | return await this.createToolErrorResult('Not able to change because the parameter is missing or invalid', options, token); 92 | } 93 | 94 | // Make sure the command exists 95 | const command = await this.configurations.getCommand(commandId); 96 | if (!command) { 97 | return await this.createToolErrorResult(`Command ${commandId} not found`, options, token); 98 | } 99 | 100 | // Parse arguments 101 | const parsedArgs = await this.parseArguments(options.input.argumentsArray, command, token); 102 | if (parsedArgs.errorMessage) { 103 | return await this.createToolErrorResult(parsedArgs.errorMessage, options, token); 104 | } 105 | const args = parsedArgs.args ?? []; 106 | 107 | this.logger.info(`Running ${command.key}` + (args.length ? ` with args ${JSON.stringify(args)}` : '')); 108 | 109 | // Run the command 110 | let result: unknown = undefined; 111 | try { 112 | // Some commands require the editor to be focused to work correctly 113 | if (this.requiresEditorFocus(command.key)) { 114 | await vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup'); 115 | } 116 | 117 | result = await vscode.commands.executeCommand(command.key, ...args); 118 | this.ranCommands.push({ key: command.key, arguments: args }); 119 | } catch (e: any) { 120 | return await this.createToolErrorResult(`Wasn't able to run ${command.key} because of ${e.message}`, options, token); 121 | } 122 | 123 | return await this.createToolResult({ commandId: command.key, result }, options, token); 124 | } 125 | 126 | private async createToolResult(resultProps: RunCommandResultSuccessProps, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 127 | let message = `Command ${resultProps.commandId} has been executed`; 128 | if (resultProps.result) { 129 | message += `The result of executing the command ${resultProps.commandId} is ${JSON.stringify(resultProps.result)}`; 130 | } 131 | 132 | return createLanguageModelToolResult( 133 | await renderElementJSON(RunCommandResult, resultProps, options.tokenizationOptions, token), 134 | ); 135 | } 136 | 137 | private async createToolErrorResult(errorMessage: string, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 138 | return createLanguageModelToolResult( 139 | await renderElementJSON(RunCommandResult, { error: errorMessage }, options.tokenizationOptions, token), 140 | ); 141 | } 142 | 143 | private async parseArguments(argsArray: string | undefined, command: Command, token: vscode.CancellationToken): Promise<{ errorMessage?: string, args?: any[] }> { 144 | if (!argsArray) { 145 | return { args: [] }; 146 | } 147 | 148 | let args: any[] = []; 149 | try { 150 | args = JSON.parse(argsArray); 151 | } catch (e) { 152 | this.logger.warn('Failed to parse args as JSON', e); 153 | } 154 | 155 | // If arguments are complex, we need to make sure they are valid 156 | if (commandsWithComplexArguments.has(command.key)) { 157 | await this.validateComplexArguments(command, args, token); 158 | if (token.isCancellationRequested) { 159 | return { errorMessage: 'Cancelled' }; 160 | } 161 | } 162 | 163 | return { args }; 164 | } 165 | 166 | private requiresEditorFocus(commandId: string): boolean { 167 | return commandId.startsWith('editor.') || 168 | (commandId.startsWith('cursor') && !commandId.includes('.')) || 169 | (commandId.startsWith('editor') && !commandId.includes('.')); 170 | } 171 | 172 | /** 173 | * Processes complex arguments for a given command and validates them against a schema. 174 | * @returns A promise that resolves to `true` if the arguments are valid, or a string with an error message if invalid. 175 | */ 176 | private async validateComplexArguments(command: Command, args: any[], token: vscode.CancellationToken): Promise { 177 | const argsSchema = command.argsSchema && typeof command.argsSchema !== 'string' ? JSON.stringify(command.argsSchema) : command.argsSchema; 178 | if (!argsSchema) { 179 | return; 180 | } 181 | 182 | // TODO support multiple arguments 183 | args[0] = await this.validateArguments(command.key, args[0], argsSchema, token); 184 | } 185 | 186 | private async validateArguments(key: string, argument: any, argsSchema: string, token: vscode.CancellationToken): Promise { 187 | const [model] = await vscode.lm.selectChatModels({ family: 'gpt-4o' }); 188 | 189 | let userMessage = ''; 190 | userMessage += `Given the users prompt, provide the arguments for the ${key} command in regards to the argument schema.`; 191 | userMessage += `Use step by step reasoning to explain your answer. When done, set the argument using the ${complexArgumentSetterTool.name} command.\n\n`; 192 | userMessage += `User Prompt: ${this.chatContext.prompt}\n\n`; 193 | userMessage += `Arguments Schema: ${argsSchema}`; 194 | 195 | const response = await model.sendRequest([vscode.LanguageModelChatMessage.User(userMessage)], { tools: [complexArgumentSetterTool], toolMode: vscode.LanguageModelChatToolMode.Required }, token); 196 | 197 | for await (const message of response.stream) { 198 | if (!(message instanceof vscode.LanguageModelToolCallPart)) { 199 | continue; 200 | } 201 | 202 | if ('argument' in message.input && typeof message.input.argument === 'string') { 203 | argument = JSON.parse(message.input.argument); 204 | break; 205 | } 206 | } 207 | 208 | return argument; 209 | } 210 | } -------------------------------------------------------------------------------- /src/tools/searchConfigurations.tsx: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { Command, Configurations, Setting } from '../configurationSearch'; 8 | import { BasePromptElementProps, PromptElement, renderElementJSON } from '@vscode/prompt-tsx'; 9 | import { createLanguageModelToolResult } from './utils'; 10 | 11 | type SearchConfigurationsResults = ((Setting & { currentValue: unknown }) | Command)[]; 12 | 13 | interface SearchConfigurationsResultSuccessProps extends BasePromptElementProps { 14 | readonly result: SearchConfigurationsResults; 15 | } 16 | 17 | interface SearchConfigurationsResultErrorProps extends BasePromptElementProps { 18 | readonly error: string; 19 | } 20 | 21 | type SearchConfigurationsResultProps = SearchConfigurationsResultSuccessProps | SearchConfigurationsResultErrorProps; 22 | 23 | function isSuccess(props: SearchConfigurationsResultProps): props is SearchConfigurationsResultSuccessProps { 24 | return !!(props as SearchConfigurationsResultSuccessProps).result; 25 | } 26 | 27 | class SearchConfigurationsResult extends PromptElement { 28 | 29 | render() { 30 | if (!isSuccess(this.props)) { 31 | return <>{this.props.error} ; 32 | } else { 33 | return <>{JSON.stringify(this.props.result)}; 34 | } 35 | } 36 | } 37 | 38 | export class SearchConfigurations implements vscode.LanguageModelTool<{ keywords?: string }> { 39 | 40 | static readonly ID = 'searchConfigurations'; 41 | 42 | constructor( 43 | private readonly configurations: Configurations, 44 | private readonly logger: vscode.LogOutputChannel 45 | ) { 46 | } 47 | 48 | prepareInvocation(options: vscode.LanguageModelToolInvocationPrepareOptions<{ keywords?: string }>, token: vscode.CancellationToken): vscode.ProviderResult { 49 | return { 50 | invocationMessage: `👀 for settings and commands`, 51 | }; 52 | } 53 | 54 | async invoke(options: vscode.LanguageModelToolInvocationOptions<{ keywords?: string }>, token: vscode.CancellationToken) { 55 | const keywords = options.input.keywords; 56 | if (!keywords) { 57 | return await this.createToolErrorResult('Unable to call searchConfigurations without keywords', options, token); 58 | } 59 | 60 | this.logger.info('Keywords:', keywords); 61 | const searchResults = await this.configurations.search(keywords, 50); 62 | this.logger.info('Configurations:', searchResults.map(c => ({ id: c.key, type: c.type }))); 63 | 64 | if (token.isCancellationRequested) { 65 | return await this.createToolErrorResult('Cancelled', options, token); 66 | } 67 | 68 | if (searchResults.length === 0) { 69 | return await this.createToolErrorResult('No configuration found', options, token); 70 | } 71 | 72 | const result: SearchConfigurationsResults = searchResults.map(c => { 73 | if (c.type === 'setting') { 74 | return { ...c, currentValue: vscode.workspace.getConfiguration().get(c.key) }; 75 | } 76 | return c; 77 | }); 78 | 79 | this.logger.trace('Sending Configurations:', JSON.stringify(result)); 80 | 81 | return await this.createToolResult({ result }, options, token); 82 | } 83 | 84 | private async createToolResult(resultProps: SearchConfigurationsResultSuccessProps, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 85 | return createLanguageModelToolResult( 86 | await renderElementJSON(SearchConfigurationsResult, resultProps, options.tokenizationOptions, token), 87 | ); 88 | } 89 | 90 | private async createToolErrorResult(errorMessage: string, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 91 | return createLanguageModelToolResult( 92 | await renderElementJSON(SearchConfigurationsResult, { error: errorMessage }, options.tokenizationOptions, token), 93 | ); 94 | } 95 | } -------------------------------------------------------------------------------- /src/tools/updateSettings.tsx: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { BasePromptElementProps, PromptElement, renderElementJSON, TextChunk } from '@vscode/prompt-tsx'; 8 | import { createLanguageModelToolResult } from './utils'; 9 | import { Configurations } from '../configurationSearch'; 10 | 11 | type Update = { key: string, oldValue: string, newValue: string }; 12 | type Unchanged = { key: string, value: string }; 13 | 14 | interface UpdateSettingsResultSuccessProps extends BasePromptElementProps { 15 | readonly updates: Update[]; 16 | readonly unchanged: Unchanged[]; 17 | } 18 | 19 | interface UpdateSettingsResultErrorProps extends BasePromptElementProps { 20 | readonly error: string; 21 | } 22 | 23 | type UpdateSettingsResultProps = UpdateSettingsResultSuccessProps | UpdateSettingsResultErrorProps; 24 | 25 | function isSuccess(props: UpdateSettingsResultProps): props is UpdateSettingsResultSuccessProps { 26 | return !!(props as UpdateSettingsResultSuccessProps).updates; 27 | } 28 | 29 | class UpdateSettingsResult extends PromptElement { 30 | render() { 31 | // Error 32 | if (!isSuccess(this.props)) { 33 | return <>{this.props.error}; 34 | } 35 | // 1 setting updated 36 | else if (this.props.updates.length === 1 && this.props.unchanged.length === 0) { 37 | const update = this.props.updates[0]; 38 | return <> 39 | Updated setting {update.key} from {update.oldValue} to {update.newValue}. 40 | ; 41 | } 42 | // 1 setting unchanged 43 | else if (this.props.updates.length === 0 && this.props.unchanged.length === 1) { 44 | const unchanged = this.props.unchanged[0]; 45 | return <> 46 | The setting {unchanged.key} remains unchanged with value {unchanged.value}. 47 | ; 48 | } 49 | // Multiple settings updated/unchanged 50 | else { 51 | return <> 52 | Updated {this.props.updates.length} settings:
53 | {this.props.updates.map(s => <>- {s.key}: from {s.oldValue} to {s.newValue}
)}
54 | {this.props.unchanged.length > 0 && `There were no changes to ${this.props.unchanged.length} settings: ${this.props.unchanged.map(s => s.key).join(', ')}.`} 55 | ; 56 | } 57 | } 58 | } 59 | 60 | export class UpdateSettings implements vscode.LanguageModelTool> { 61 | 62 | static readonly ID = 'updateSettings'; 63 | 64 | constructor( 65 | private readonly updatedSettings: { key: string, oldValue: any, newValue: any }[], 66 | private readonly configurations: Configurations, 67 | private readonly logger: vscode.LogOutputChannel, 68 | ) { 69 | } 70 | 71 | private validateSettings(settings: Record): { key: string, value: any }[] { 72 | const result: { key: string, value: any }[] = []; 73 | for (const [key, value] of Object.entries(settings)) { 74 | result.push({ key, value }); 75 | } 76 | return result; 77 | } 78 | 79 | async prepareInvocation(options: vscode.LanguageModelToolInvocationPrepareOptions>, token: vscode.CancellationToken): Promise { 80 | const settingsToUpdate = this.validateSettings(options.input ?? {}); 81 | 82 | if (settingsToUpdate.length === 0) { 83 | return undefined; 84 | } 85 | 86 | // Check if a setting is restricted. If so, create the confirmation message 87 | let message = new vscode.MarkdownString('', true); 88 | for (const { key, value } of settingsToUpdate) { 89 | const setting = this.configurations.getSetting(key); 90 | if (!setting || !setting.restricted) { 91 | continue; 92 | } 93 | 94 | message.value += `Updating \`${key}\` to \`${value}\`.\n\n`; 95 | message.value += `- **Description:** ${setting.description}\n\n`; 96 | } 97 | 98 | const confirmationMessages = message.value !== '' ? { title: 'Confirmation required', message } : undefined; 99 | 100 | // One setting to update 101 | if (settingsToUpdate.length === 1) { 102 | return { 103 | confirmationMessages, 104 | invocationMessage: `Updating \`${settingsToUpdate[0].key}\``, 105 | }; 106 | } 107 | 108 | // Multiple settings to update 109 | return { 110 | confirmationMessages, 111 | invocationMessage: `Updating ${settingsToUpdate.length} settings`, 112 | }; 113 | } 114 | 115 | async invoke(options: vscode.LanguageModelToolInvocationOptions>, token: vscode.CancellationToken) { 116 | const settingsToUpdate = this.validateSettings(options.input ?? {}); 117 | 118 | if (settingsToUpdate.length === 0) { 119 | return await this.createToolErrorResult('No settings to update', options, token); 120 | } 121 | 122 | if (token.isCancellationRequested) { 123 | return await this.createToolErrorResult(`Cancelled`, options, token); 124 | } 125 | 126 | const updates: Update[] = []; 127 | const unchanged: Unchanged[] = []; 128 | 129 | for (const { key, value } of settingsToUpdate) { 130 | let oldValue = vscode.workspace.getConfiguration().get(key); 131 | 132 | const oldStringified = JSON.stringify(oldValue); 133 | const newStringified = JSON.stringify(value); 134 | if (oldStringified === newStringified) { 135 | unchanged.push({ key, value: oldStringified }); 136 | continue; 137 | } 138 | 139 | updates.push({ key, oldValue: oldStringified, newValue: newStringified }); 140 | this.updatedSettings.push({ key, oldValue, newValue: value }); 141 | 142 | try { 143 | this.logger.info('Setting', key, 'to', value); 144 | await vscode.workspace.getConfiguration().update(key, value, vscode.ConfigurationTarget.Global); 145 | } catch (e: any) { 146 | return await this.createToolErrorResult(`Wasn't able to set ${key} to ${value} because of ${e.message}`, options, token); 147 | } 148 | } 149 | 150 | return await this.createToolResult({ updates, unchanged }, options, token); 151 | } 152 | 153 | private async createToolResult(resultProps: UpdateSettingsResultSuccessProps, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 154 | return createLanguageModelToolResult( 155 | await renderElementJSON(UpdateSettingsResult, resultProps, options.tokenizationOptions, token), 156 | ); 157 | } 158 | 159 | private async createToolErrorResult(errorMessage: string, options: vscode.LanguageModelToolInvocationOptions, token: vscode.CancellationToken): Promise { 160 | return createLanguageModelToolResult( 161 | await renderElementJSON(UpdateSettingsResult, { error: errorMessage }, options.tokenizationOptions, token), 162 | ); 163 | } 164 | } -------------------------------------------------------------------------------- /src/tools/utils.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | import * as vscode from 'vscode'; 7 | import { PromptElementJSON } from '@vscode/prompt-tsx/dist/base/jsonTypes'; 8 | 9 | export function createLanguageModelToolResult(tsx: PromptElementJSON): vscode.LanguageModelToolResult { 10 | return new vscode.LanguageModelToolResult([ 11 | new vscode.LanguageModelPromptTsxPart(tsx) 12 | ]); 13 | } 14 | 15 | function isTsxContent(content: vscode.LanguageModelTextPart | vscode.LanguageModelPromptTsxPart | unknown): content is vscode.LanguageModelPromptTsxPart { 16 | return content instanceof vscode.LanguageModelPromptTsxPart; 17 | } 18 | 19 | export function getTsxDataFromToolsResult(result: vscode.LanguageModelToolResult): PromptElementJSON | undefined { 20 | const tsxContents = result.content.filter(isTsxContent); 21 | if (tsxContents.length > 0) { 22 | return tsxContents[0].value as PromptElementJSON; 23 | } 24 | return undefined; 25 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "Node16", 4 | "target": "ES2022", 5 | "lib": [ 6 | "ES2022" 7 | ], 8 | "sourceMap": true, 9 | "rootDir": "src", 10 | "strict": true, /* enable all strict type-checking options */ 11 | "jsx": "react", 12 | "jsxFactory": "vscpp", 13 | "jsxFragmentFactory": "vscppf" 14 | /* Additional Checks */ 15 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 16 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 17 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 18 | } 19 | } -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | //@ts-check 7 | 8 | 'use strict'; 9 | 10 | const path = require('path'); 11 | 12 | //@ts-check 13 | /** @typedef {import('webpack').Configuration} WebpackConfig **/ 14 | 15 | /** @type WebpackConfig */ 16 | const extensionConfig = { 17 | target: 'node', // VS Code extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/ 18 | mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production') 19 | 20 | entry: './src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/ 21 | output: { 22 | // the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/ 23 | path: path.resolve(__dirname, 'dist'), 24 | filename: 'extension.js', 25 | libraryTarget: 'commonjs2' 26 | }, 27 | externals: { 28 | vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/ 29 | // modules added here also need to be added in the .vscodeignore file 30 | }, 31 | resolve: { 32 | // support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader 33 | extensions: ['.ts', '.tsx', '.js'] 34 | }, 35 | module: { 36 | rules: [ 37 | { 38 | test: /\.tsx?$/, 39 | exclude: /node_modules/, 40 | use: [ 41 | { 42 | loader: 'ts-loader' 43 | } 44 | ] 45 | } 46 | ] 47 | }, 48 | devtool: 'nosources-source-map', 49 | infrastructureLogging: { 50 | level: "log", // enables logging required for problem matchers 51 | }, 52 | }; 53 | module.exports = [extensionConfig]; --------------------------------------------------------------------------------