Compare commits

...

72 Commits

Author SHA1 Message Date
Andrew Pareles 2f80c653d5 certs 2025-05-13 19:52:26 -07:00
Andrew Pareles b35dfdf475 trigger resize 2025-05-13 18:29:04 -07:00
Andrew Pareles 609f4c9cbf UI 2025-05-13 17:27:46 -07:00
Andrew Pareles 6df3b588df fix anthropic empty err message 2025-05-13 17:25:29 -07:00
Andrew Pareles f4c1321f25 rm thinking from 2 flash 2025-05-12 20:08:54 -07:00
Andrew Pareles b54dd7fedc 1.3.7 / 0031 2025-05-12 19:53:58 -07:00
Andrew Pareles 3241178238 Merge remote-tracking branch 'origin/main' into model-selection 2025-05-12 19:50:35 -07:00
Andrew Pareles 68bb3f6962 fix azure? 2025-05-12 19:48:50 -07:00
Andrew Pareles 2e64f5a24b overrides link update 2025-05-12 19:46:18 -07:00
Andrew Pareles 2e5ecb291d comment 2025-05-12 19:44:42 -07:00
Andrew Pareles f1e24c9b4c Merge pull request #545 from HunterEvangelista/510-openai-additional-json
added optional json config for VoidStaticModelInfo
2025-05-12 19:42:22 -07:00
Andrew Pareles f65e4f51a2 misc 2025-05-12 19:40:39 -07:00
Andrew Pareles f1a5d20150 Merge pull request #505 from homanp/feat/apply-to-terminal
feat: add support for applying `shellscript` and `bash` directly to terminal
2025-05-12 19:32:24 -07:00
Andrew Pareles 28dcdff189 isdisabled fix 2025-05-12 19:31:05 -07:00
Andrew Pareles 67ed52415e apply terminal? 2025-05-12 19:29:45 -07:00
Andrew Pareles 3772cf98ea delete 2025-05-12 18:47:40 -07:00
Andrew Pareles 1c6edf7023 generalize 2025-05-12 18:45:33 -07:00
Andrew Pareles 6b6528c3fb Merge pull request #507 from steaks/explorer-view-copy-prompt
Add Void: Copy Prompt as menu item to the ExplorerContext window
2025-05-12 18:30:21 -07:00
Andrew Pareles f98894ad77 format 2025-05-12 18:22:59 -07:00
Andrew Pareles f8745d8b40 Merge remote-tracking branch 'origin/main' into pr/steaks/507 2025-05-12 18:20:55 -07:00
Andrew Pareles 7066b4285b file and folder copy uniform 2025-05-12 18:20:44 -07:00
Andrew Pareles 1eee07e697 Merge pull request #548 from ujjwaljainnn/ujjwaljainnn-add-context-on-add-to-chat
fix: preserve selection when adding to chat via CTRL+L with closed panel
2025-05-12 16:50:04 -07:00
Andrew Pareles 45f7e4b157 minor updates 2025-05-12 16:48:27 -07:00
Andrew Pareles 1619a3c19b Merge pull request #559 from vrtnis/mistral-medium-capabilities
feat(models): update modelCapabilities with mistral-medium entry
2025-05-12 14:37:40 -07:00
vrtnis d668348244 feat(models): update modelCapabilities with mistral-medium entry 2025-05-12 20:58:55 +00:00
Andrew Pareles 3fa680e8ba identify more shells 2025-05-12 12:09:55 -07:00
Andrew Pareles e8b7c9c470 always create terminal when apply 2025-05-12 11:56:08 -07:00
Andrew Pareles a0eb7d6192 Merge remote-tracking branch 'origin/main' into pr/homanp/505 2025-05-12 11:52:22 -07:00
Andrew Pareles 5c4785d691 Merge remote-tracking branch 'origin/model-selection' into pr/homanp/505 2025-05-12 11:50:36 -07:00
Andrew Pareles 1de90cc39d use 1st terminal id 2025-05-12 11:50:25 -07:00
Andrew Pareles d09a41acd3 Merge pull request #556 from voideditor/model-selection
delete
2025-05-12 11:03:17 -07:00
Andrew Pareles 24102fc2b2 log2 2025-05-12 11:00:05 -07:00
Andrew Pareles c2b65eb16f log 2025-05-12 10:59:53 -07:00
Andrew Pareles a4046bc5a5 update so edit extensions.json 2025-05-12 10:58:18 -07:00
Andrew Pareles 6f73804e94 update 2025-05-12 10:50:28 -07:00
Andrew Pareles 76155beaad Merge pull request #555 from voideditor/model-selection
extensions warning fix by deleting some extensions once
2025-05-12 10:45:08 -07:00
Andrew Pareles 53c68b1267 bump 2025-05-12 10:44:43 -07:00
Andrew Pareles afbc1b40bf extensions warning fix by deleting some extensions once 2025-05-12 10:42:40 -07:00
Ismail Pelaseyed 9a905f6cb2 add support for stopping the terminal command 2025-05-12 09:06:22 +02:00
Ujjwal Jain dd42e40a8d fix: preserve selection when adding to chat via CTRL+L with closed panel 2025-05-11 22:01:04 -04:00
Hunter Evangelista 970fd7ecbb moved payload to sdk initialization 2025-05-11 17:10:07 -07:00
Hunter Evangelista 50710143eb Merge branch 'main' into 510-openai-additional-json 2025-05-11 16:06:11 -07:00
Hunter Evangelista d6295e5d65 added optional json config for VoidStaticModelInfo 2025-05-11 16:02:17 -07:00
Andrew Pareles 053a022ef8 Merge pull request #538 from voideditor/model-selection
1.3.5
2025-05-10 22:28:33 -07:00
Andrew Pareles 3b963d8717 1.3.5 2025-05-10 22:28:15 -07:00
Andrew Pareles e8540e4668 Merge pull request #537 from voideditor/model-selection
Cmd L better
2025-05-10 22:27:36 -07:00
Andrew Pareles 39f2f24b42 1.3.4 2025-05-10 22:07:26 -07:00
Andrew Pareles e852874be7 cmd L to add file 2025-05-10 22:05:50 -07:00
Andrew Pareles 6d07f9db14 Reasoning improvements + Gemini (Merge pull request #521 from voideditor/model-selection)
Gemini reasoning improvements + link URI improvements
2025-05-10 18:10:34 -07:00
Andrew Pareles 2934f9a3c5 += -> = 2025-05-10 18:10:00 -07:00
Andrew Pareles 7748dc4f2d misc fixes + (empty message) improvements 2025-05-10 18:06:58 -07:00
Andrew Pareles 8b45aea8a8 fix link + add gemini tool id if empty 2025-05-10 16:28:54 -07:00
Andrew Pareles cab8dd64b6 rm comments 2025-05-10 16:13:36 -07:00
Andrew Pareles 19782c80df voidRelease 2025-05-10 16:09:06 -07:00
Andrew Pareles 926db45f0a 33 2025-05-10 16:03:06 -07:00
Andrew Pareles 4068911d49 27 2025-05-10 16:02:56 -07:00
Andrew Pareles dcee2e2657 add prompt 2025-05-10 16:02:37 -07:00
Andrew Pareles 4c1c0b591a GoogleGenerativeAI (deprecated) -> genai, add gemini reasoning, improve reasoning logic 2025-05-10 15:59:26 -07:00
Andrew Pareles 61fc593903 shorten non URL links too 2025-05-10 15:53:05 -07:00
Andrew Pareles ecff59eed7 shorten long URI links 2025-05-10 15:29:55 -07:00
Ismail Pelaseyed e2a7b0e1a0 fix merge conflicts 2025-05-10 13:41:43 +02:00
Andrew Pareles 07c3f33f1e void increment 2025-05-10 03:36:54 -07:00
Andrew Pareles 0f93e1b055 Merge pull request #518 from voideditor/model-selection
Model selection
2025-05-10 03:33:45 -07:00
Andrew Pareles 2106573922 misc 2025-05-10 03:32:57 -07:00
Andrew Pareles 93a13a76af Merge remote-tracking branch 'origin/main' into model-selection 2025-05-10 03:31:45 -07:00
Andrew Pareles 7b18e25288 period 2025-05-10 03:29:33 -07:00
Andrew Pareles 57b0505a7e Merge pull request #517 from voideditor/revert-516-model-selection
apply UX message
2025-05-10 03:28:59 -07:00
Andrew Pareles 58d95035ff update message 2025-05-10 03:28:29 -07:00
Andrew Pareles 5232b4c30c update prompt to work better in agent 2025-05-10 02:28:40 -07:00
Steven Wexler 08274637e1 Small touchups 2025-05-09 15:40:34 -06:00
Steven Wexler 168b92f6c4 Add Void: Copy Prompt as menu item to the ExplorerContext window 2025-05-09 15:38:32 -06:00
Ismail Pelaseyed a9aa9a26ea feat: add support for applying shellscripts and bash directly to terminal 2025-05-09 14:59:27 +02:00
25 changed files with 935 additions and 217 deletions
+1 -1
View File
@@ -86,7 +86,7 @@ To build Void from the terminal instead of from inside VSCode, follow the steps
- Make sure you followed the prerequisite steps above.
- Make sure you have Node version `20.18.2` (the version in `.nvmrc`)!
- You can do this easily without touching your base installation with [nvm](https://github.com/nvm-sh/nvm). Simply run `nvm install`, followed by `nvm use` and it will automatically install and use the version specified in `nvmrc`
- You can do this easily without touching your base installation with [nvm](https://github.com/nvm-sh/nvm). Simply run `nvm install`, followed by `nvm use` and it will automatically install and use the version specified in `nvmrc`.
- Make sure that the path to your Void folder does not have any spaces in it.
- If you get `"TypeError: Failed to fetch dynamically imported module"`, make sure all imports end with `.js`.
- If you get an error with React, try running `NODE_OPTIONS="--max-old-space-size=8192" npm run buildreact`.
+32 -5
View File
@@ -13,7 +13,7 @@
"@anthropic-ai/sdk": "^0.40.0",
"@c4312/eventsource-umd": "^3.0.5",
"@floating-ui/react": "^0.27.8",
"@google/generative-ai": "^0.24.1",
"@google/genai": "^0.13.0",
"@microsoft/1ds-core-js": "^3.2.13",
"@microsoft/1ds-post-js": "^3.2.13",
"@mistralai/mistralai": "^1.6.0",
@@ -1817,11 +1817,17 @@
"integrity": "sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg==",
"license": "MIT"
},
"node_modules/@google/generative-ai": {
"version": "0.24.1",
"resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.24.1.tgz",
"integrity": "sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==",
"node_modules/@google/genai": {
"version": "0.13.0",
"resolved": "https://registry.npmjs.org/@google/genai/-/genai-0.13.0.tgz",
"integrity": "sha512-eaEncWt875H7046T04mOpxpHJUM+jLIljEf+5QctRyOeChylE/nhpwm1bZWTRWoOu/t46R9r+PmgsJFhTpE7tQ==",
"license": "Apache-2.0",
"dependencies": {
"google-auth-library": "^9.14.2",
"ws": "^8.18.0",
"zod": "^3.22.4",
"zod-to-json-schema": "^3.22.4"
},
"engines": {
"node": ">=18.0.0"
}
@@ -23767,6 +23773,27 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xml": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz",
+1 -1
View File
@@ -75,7 +75,7 @@
"@anthropic-ai/sdk": "^0.40.0",
"@c4312/eventsource-umd": "^3.0.5",
"@floating-ui/react": "^0.27.8",
"@google/generative-ai": "^0.24.1",
"@google/genai": "^0.13.0",
"@microsoft/1ds-core-js": "^3.2.13",
"@microsoft/1ds-post-js": "^3.2.13",
"@mistralai/mistralai": "^1.6.0",
+2 -1
View File
@@ -1,7 +1,8 @@
{
"nameShort": "Void",
"nameLong": "Void",
"voidVersion": "1.3.2",
"voidVersion": "1.3.7",
"voidRelease": "0031",
"applicationName": "void",
"dataFolderName": ".void-editor",
"win32MutexName": "voideditor",
@@ -12,7 +12,7 @@ import { URI } from '../../../../base/common/uri.js';
import { Emitter, Event } from '../../../../base/common/event.js';
import { ILLMMessageService } from '../common/sendLLMMessageService.js';
import { chat_userMessageContent, ToolName, } from '../common/prompt/prompts.js';
import { getErrorMessage, RawToolCallObj, RawToolParamsObj } from '../common/sendLLMMessageTypes.js';
import { AnthropicReasoning, getErrorMessage, RawToolCallObj, RawToolParamsObj } from '../common/sendLLMMessageTypes.js';
import { generateUuid } from '../../../../base/common/uuid.js';
import { FeatureName, ModelSelection, ModelSelectionOptions } from '../common/voidSettingsTypes.js';
import { IVoidSettingsService } from '../common/voidSettingsService.js';
@@ -540,7 +540,7 @@ class ChatThreadService extends Disposable implements IChatThreadService {
const { name, id, rawParams } = lastMsg
const errorMessage = this.errMsgs.rejected
const errorMessage = this.toolErrMsgs.rejected
this._updateLatestTool(threadId, { role: 'tool', type: 'rejected', params: params, name: name, content: errorMessage, result: null, id, rawParams })
this._setStreamState(threadId, undefined)
}
@@ -557,7 +557,8 @@ class ChatThreadService extends Disposable implements IChatThreadService {
}
// add tool that's running
else if (this.streamState[threadId]?.isRunning === 'tool') {
const { toolName, toolParams, id, content, rawParams } = this.streamState[threadId].toolInfo
const { toolName, toolParams, id, content: content_, rawParams } = this.streamState[threadId].toolInfo
const content = content_ || this.toolErrMsgs.interrupted
this._updateLatestTool(threadId, { role: 'tool', name: toolName, params: toolParams, id, content, rawParams, type: 'rejected', result: null })
}
// reject the tool for the user if relevant
@@ -581,8 +582,9 @@ class ChatThreadService extends Disposable implements IChatThreadService {
private readonly errMsgs = {
private readonly toolErrMsgs = {
rejected: 'Tool call was rejected by the user.',
interrupted: 'Tool call was interrupted by the user.',
errWhenStringifying: (error: any) => `Tool call succeeded, but there was an error stringifying the output.\n${getErrorMessage(error)}`
}
@@ -671,7 +673,7 @@ class ChatThreadService extends Disposable implements IChatThreadService {
try {
toolResultStr = this._toolsService.stringOfResult[toolName](toolParams as any, toolResult as any)
} catch (error) {
const errorMessage = this.errMsgs.errWhenStringifying(error)
const errorMessage = this.toolErrMsgs.errWhenStringifying(error)
this._updateLatestTool(threadId, { role: 'tool', type: 'tool_error', params: toolParams, result: errorMessage, name: toolName, content: errorMessage, id: toolId, rawParams: opts.unvalidatedToolParams })
return {}
}
@@ -749,8 +751,13 @@ class ChatThreadService extends Disposable implements IChatThreadService {
shouldRetryLLM = false
nAttempts += 1
let resMessageIsDonePromise: (res: { type: 'llmDone', toolCall?: RawToolCallObj } | { type: 'llmError', error?: { message: string; fullError: Error | null; } } | { type: 'llmAborted' }) => void // resolves when user approves this tool use (or if tool doesn't require approval)
const messageIsDonePromise = new Promise<{ type: 'llmDone', toolCall?: RawToolCallObj } | { type: 'llmError', error?: { message: string; fullError: Error | null; } } | { type: 'llmAborted' }>((res, rej) => { resMessageIsDonePromise = res })
type ResTypes =
| { type: 'llmDone', toolCall?: RawToolCallObj, info: { fullText: string, fullReasoning: string, anthropicReasoning: AnthropicReasoning[] | null } }
| { type: 'llmError', error?: { message: string; fullError: Error | null; } }
| { type: 'llmAborted' }
let resMessageIsDonePromise: (res: ResTypes) => void // resolves when user approves this tool use (or if tool doesn't require approval)
const messageIsDonePromise = new Promise<ResTypes>((res, rej) => { resMessageIsDonePromise = res })
const llmCancelToken = this._llmMessageService.sendLLMMessage({
messagesType: 'chatMessages',
@@ -765,9 +772,7 @@ class ChatThreadService extends Disposable implements IChatThreadService {
this._setStreamState(threadId, { isRunning: 'LLM', llmInfo: { displayContentSoFar: fullText, reasoningSoFar: fullReasoning, toolCallSoFar: toolCall ?? null }, interrupt: Promise.resolve(() => { if (llmCancelToken) this._llmMessageService.abort(llmCancelToken) }) })
},
onFinalMessage: async ({ fullText, fullReasoning, toolCall, anthropicReasoning, }) => {
this._addMessageToThread(threadId, { role: 'assistant', displayContent: fullText, reasoning: fullReasoning, anthropicReasoning })
resMessageIsDonePromise({ type: 'llmDone', toolCall }) // resolve with tool calls
resMessageIsDonePromise({ type: 'llmDone', toolCall, info: { fullText, fullReasoning, anthropicReasoning } }) // resolve with tool calls
},
onError: async (error) => {
resMessageIsDonePromise({ type: 'llmError', error: error })
@@ -826,11 +831,12 @@ class ChatThreadService extends Disposable implements IChatThreadService {
}
}
// llm res success
const { toolCall } = llmRes
this._setStreamState(threadId, { isRunning: 'idle', interrupt: 'not_needed' }) // just decorative, for clarity
const { toolCall, info } = llmRes
this._addMessageToThread(threadId, { role: 'assistant', displayContent: info.fullText, reasoning: info.fullReasoning, anthropicReasoning: info.anthropicReasoning })
this._setStreamState(threadId, { isRunning: 'idle', interrupt: 'not_needed' }) // just decorative for clarity
// call tool if there is one
if (toolCall) {
@@ -17,6 +17,7 @@ import { IVoidModelService } from '../common/voidModelService.js';
import { URI } from '../../../../base/common/uri.js';
import { EndOfLinePreference } from '../../../../editor/common/model.js';
export const EMPTY_MESSAGE = '(empty message)'
@@ -36,7 +37,6 @@ type SimpleLLMMessage = {
}
const EMPTY_MESSAGE = '(empty message)'
const CHARS_PER_TOKEN = 4 // assume abysmal chars per token
const TRIM_TO_LEN = 120
@@ -237,18 +237,6 @@ const prepareMessages_XML_tools = (messages: SimpleLLMMessage[], supportsAnthrop
}
export type GeminiMessage = {
role: 'user' | 'model'; // Gemini uses 'user' and 'model' roles
parts: (
| { text: string; }
| { functionCall: { tool_call: any } }
| { functionResponse: { name: ToolName, response: { result: string } } }
)[];
};
// --- CHAT ---
const prepareOpenAIOrAnthropicMessages = ({
@@ -417,14 +405,25 @@ const prepareOpenAIOrAnthropicMessages = ({
// ================ no empty message ================
for (const currMsg of llmMessages) {
for (let i = 0; i < llmMessages.length; i += 1) {
const currMsg: AnthropicOrOpenAILLMMessage = llmMessages[i]
const nextMsg: AnthropicOrOpenAILLMMessage | undefined = llmMessages[i + 1]
if (currMsg.role === 'tool') continue
// if content is a string, replace string with empty msg
if (typeof currMsg.content === 'string')
if (typeof currMsg.content === 'string') {
currMsg.content = currMsg.content || EMPTY_MESSAGE
}
else {
// if content is an array, replace any empty text entries with empty msg, and make sure there's at least 1 entry
// allowed to be empty if has a tool in it or following it
if (currMsg.content.find(c => c.type === 'tool_result' || c.type === 'tool_use')) {
currMsg.content = currMsg.content.filter(c => !(c.type === 'text' && !c.text)) as any
continue
}
if (nextMsg?.role === 'tool') continue
// replace any empty text entries with empty msg, and make sure there's at least 1 entry
for (const c of currMsg.content) {
if (c.type === 'text') c.text = c.text || EMPTY_MESSAGE
}
@@ -457,7 +456,7 @@ const prepareGeminiMessages = (messages: AnthropicLLMChatMessage[]) => {
}
else if (c.type === 'tool_use') {
latestToolName = c.name as ToolName
return { functionCall: { name: c.name as ToolName, args: c.input } }
return { functionCall: { id: c.id, name: c.name as ToolName, args: c.input } }
}
else return null
}).filter(m => !!m)
@@ -475,7 +474,7 @@ const prepareGeminiMessages = (messages: AnthropicLLMChatMessage[]) => {
}
else if (c.type === 'tool_result') {
if (!latestToolName) return null
return { functionResponse: { name: latestToolName, response: { result: c.content } } }
return { functionResponse: { id: c.tool_use_id, name: latestToolName, response: { output: c.content } } }
}
else return null
}).filter(m => !!m)
@@ -3,6 +3,7 @@
* Licensed under the Apache License, Version 2.0. See LICENSE.txt for more information.
*--------------------------------------------------------------------------------------*/
import { VSBuffer } from '../../../../base/common/buffer.js';
import { Disposable } from '../../../../base/common/lifecycle.js';
import { env } from '../../../../base/common/process.js';
import { URI } from '../../../../base/common/uri.js';
@@ -29,6 +30,7 @@ export const IExtensionTransferService = createDecorator<IExtensionTransferServi
const extensionBlacklist = [
// ignore extensions
'ms-vscode-remote.remote', // ms-vscode-remote.remote-ssh, ms-vscode-remote.remote-wsl
'ms-vscode.remote', // ms-vscode.remote-explorer
// ignore other AI copilots that could conflict with Void keybindings
'sourcegraph.cody-ai',
'continue.continue',
@@ -40,6 +42,9 @@ const extensionBlacklist = [
];
const isBlacklisted = (fsPath: string | undefined) => {
return extensionBlacklist.find(bItem => fsPath?.includes(bItem))
}
class ExtensionTransferService extends Disposable implements IExtensionTransferService {
_serviceBrand: undefined;
@@ -87,15 +92,31 @@ class ExtensionTransferService extends Disposable implements IExtensionTransferS
await fileService.createFolder(toParent)
}
for (const extensionFolder of stat.children ?? []) {
if (extensionBlacklist.find(bItem => extensionFolder.resource.path.includes(bItem))) {
console.log('Skipping...', extensionFolder.resource.path)
continue
}
const from = extensionFolder.resource
const to = URI.joinPath(toParent, extensionFolder.name)
await fileService.copy(from, to, true)
const toStat = await fileService.resolve(from)
if (toStat.isDirectory) {
if (!isBlacklisted(extensionFolder.resource.fsPath)) {
await fileService.copy(from, to, true)
}
}
else if (toStat.isFile) {
if (extensionFolder.name === 'extensions.json') {
try {
const contentsStr = await fileService.readFile(from)
const json: any = JSON.parse(contentsStr.value.toString())
const j2 = json.filter((entry: { identifier?: { id?: string } }) => !isBlacklisted(entry?.identifier?.id))
const jsonStr = JSON.stringify(j2)
await fileService.writeFile(to, VSBuffer.fromString(jsonStr))
}
catch {
console.log('Error copying extensions.json, skipping')
}
}
}
}
// Ensure the destination directory exists
} else {
console.log(`Skipping file that doesn't exist: ${from.toString()}`)
}
@@ -113,19 +134,38 @@ class ExtensionTransferService extends Disposable implements IExtensionTransferS
}
async deleteBlacklistExtensions(os: 'mac' | 'windows' | 'linux' | null) {
const fileService = this._fileService
const extensionsURI = getExtensionsFolder(os)
if (!extensionsURI) return
const eURI = await this._fileService.resolve(extensionsURI)
const eURI = await fileService.resolve(extensionsURI)
for (const child of eURI.children ?? []) {
// if is not blacklisted, continue
if (!extensionBlacklist.find(bItem => child.resource.path.includes(bItem))) {
continue
}
try {
console.log('Deleting extension', child.resource.fsPath)
await this._fileService.del(child.resource, { recursive: true, useTrash: true })
if (child.isDirectory) {
// if is blacklisted
if (isBlacklisted(child.resource.fsPath)) {
console.log('Deleting extension', child.resource.fsPath)
await fileService.del(child.resource, { recursive: true, useTrash: true })
}
}
else if (child.isFile) {
// if is extensions.json
if (child.name === 'extensions.json') {
console.log('Updating extensions.json', child.resource.fsPath)
try {
const contentsStr = await fileService.readFile(child.resource)
const json: any = JSON.parse(contentsStr.value.toString())
const j2 = json.filter((entry: { identifier?: { id?: string } }) => !isBlacklisted(entry?.identifier?.id))
const jsonStr = JSON.stringify(j2)
await fileService.writeFile(child.resource, VSBuffer.fromString(jsonStr))
}
catch {
console.log('Error copying extensions.json, skipping')
}
}
}
}
catch (e) {
console.error('Could not delete extension', child.resource.fsPath, e)
@@ -0,0 +1,78 @@
import { localize2 } from '../../../../nls.js';
import { URI } from '../../../../base/common/uri.js';
import { Action2, registerAction2, MenuId } from '../../../../platform/actions/common/actions.js';
import { ServicesAccessor } from '../../../../editor/browser/editorExtensions.js';
import { INotificationService } from '../../../../platform/notification/common/notification.js';
import { IFileService } from '../../../../platform/files/common/files.js';
import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.js';
import { IDirectoryStrService } from '../common/directoryStrService.js';
import { messageOfSelection } from '../common/prompt/prompts.js';
import { IVoidModelService } from '../common/voidModelService.js';
class FilePromptActionService extends Action2 {
private static readonly VOID_COPY_FILE_PROMPT_ID = 'void.copyfileprompt'
constructor() {
super({
id: FilePromptActionService.VOID_COPY_FILE_PROMPT_ID,
title: localize2('voidCopyPrompt', 'Void: Copy Prompt'),
menu: [{
id: MenuId.ExplorerContext,
group: '8_void',
order: 1,
}]
});
}
async run(accessor: ServicesAccessor, uri: URI): Promise<void> {
try {
const fileService = accessor.get(IFileService);
const clipboardService = accessor.get(IClipboardService)
const directoryStrService = accessor.get(IDirectoryStrService)
const voidModelService = accessor.get(IVoidModelService)
const stat = await fileService.stat(uri)
const folderOpts = {
maxChildren: 1000,
maxCharsPerFile: 2_000_000,
} as const
let m: string = 'No contents detected'
if (stat.isFile) {
m = await messageOfSelection({
type: 'File',
uri,
language: (await voidModelService.getModelSafe(uri)).model?.getLanguageId() || '',
state: { wasAddedAsCurrentFile: false, },
}, {
folderOpts,
directoryStrService,
fileService,
})
}
if (stat.isDirectory) {
m = await messageOfSelection({
type: 'Folder',
uri,
}, {
folderOpts,
fileService,
directoryStrService,
})
}
await clipboardService.writeText(m)
} catch (error) {
const notificationService = accessor.get(INotificationService)
notificationService.error(error + '')
}
}
}
registerAction2(FilePromptActionService)
@@ -5,17 +5,19 @@
import { Disposable } from '../../../../base/common/lifecycle.js';
import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js';
// import { IExtensionTransferService } from './extensionTransferService.js';
// import { os } from '../common/helpers/systemInfo.js';
// import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { IExtensionTransferService } from './extensionTransferService.js';
import { os } from '../common/helpers/systemInfo.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { timeout } from '../../../../base/common/async.js';
import { getActiveWindow } from '../../../../base/browser/dom.js';
// Onboarding contribution that mounts the component at startup
export class MiscWorkbenchContribs extends Disposable implements IWorkbenchContribution {
static readonly ID = 'workbench.contrib.voidMiscWorkbenchContribs';
constructor(
// @IExtensionTransferService private readonly extensionTransferService: IExtensionTransferService,
// @IStorageService private readonly storageService: IStorageService,
@IExtensionTransferService private readonly extensionTransferService: IExtensionTransferService,
@IStorageService private readonly storageService: IStorageService,
) {
super();
this.initialize();
@@ -23,13 +25,23 @@ export class MiscWorkbenchContribs extends Disposable implements IWorkbenchContr
private initialize(): void {
// // delete blacklisted extensions once (this is for people who already installed them)
// const deleteExtensionsStorageId = 'void-deleted-blacklist'
// const alreadyDeleted = this.storageService.get(deleteExtensionsStorageId, StorageScope.APPLICATION)
// if (!alreadyDeleted) {
// this.storageService.store(deleteExtensionsStorageId, 'true', StorageScope.APPLICATION, StorageTarget.MACHINE)
// this.extensionTransferService.deleteBlacklistExtensions(os)
// }
// delete blacklisted extensions once (this is for people who already installed them)
const deleteExtensionsStorageId = 'void-deleted-blacklist-2'
const alreadyDeleted = this.storageService.get(deleteExtensionsStorageId, StorageScope.APPLICATION)
if (!alreadyDeleted) {
this.storageService.store(deleteExtensionsStorageId, 'true', StorageScope.APPLICATION, StorageTarget.MACHINE)
this.extensionTransferService.deleteBlacklistExtensions(os)
}
// after some time, trigger a resize event for the blank screen error
timeout(5_000).then(() => {
// Get the active window reference for multi-window support
const targetWindow = getActiveWindow();
// Trigger a window resize event to ensure proper layout calculations
targetWindow.dispatchEvent(new Event('resize'))
})
}
}
@@ -239,27 +239,104 @@ export const StatusIndicatorForApplyButton = ({ applyBoxId, uri }: { applyBoxId:
}
export const ApplyButtonsHTML = ({
const terminalLanguages = new Set([
'bash',
'shellscript',
'shell',
'powershell',
'bat',
'zsh',
'sh',
'fish',
'nushell',
'ksh',
'xonsh',
'elvish',
])
const ApplyButtonsForTerminal = ({
codeStr,
applyBoxId,
uri,
language,
}: {
codeStr: string,
applyBoxId: string,
} & ({
language?: string,
uri: URI | 'current';
})
) => {
}) => {
const accessor = useAccessor()
const metricsService = accessor.get('IMetricsService')
const terminalToolService = accessor.get('ITerminalToolService')
const settingsState = useSettingsState()
const [isShellRunning, setIsShellRunning] = useState<boolean>(false)
const interruptToolRef = useRef<(() => void) | null>(null)
const isDisabled = isShellRunning
const onClickSubmit = useCallback(async () => {
if (isShellRunning) return
try {
setIsShellRunning(true)
const terminalId = await terminalToolService.createPersistentTerminal({ cwd: null })
const { interrupt } = await terminalToolService.runCommand(
codeStr,
{ type: 'persistent', persistentTerminalId: terminalId }
);
interruptToolRef.current = interrupt
metricsService.capture('Execute Shell', { length: codeStr.length })
} catch (e) {
setIsShellRunning(false)
console.error('Failed to execute in terminal:', e)
}
}, [codeStr, uri, applyBoxId, metricsService, terminalToolService, isShellRunning])
if (isShellRunning) {
return (
<IconShell1
Icon={X}
onClick={() => {
interruptToolRef.current?.();
setIsShellRunning(false);
}}
{...tooltipPropsForApplyBlock({ tooltipName: 'Stop' })}
/>
);
}
if (isDisabled) {
return null
}
return <IconShell1
Icon={Play}
onClick={onClickSubmit}
{...tooltipPropsForApplyBlock({ tooltipName: 'Apply' })}
/>
}
const ApplyButtonsForEdit = ({
codeStr,
applyBoxId,
uri,
language,
}: {
codeStr: string,
applyBoxId: string,
language?: string,
uri: URI | 'current';
}) => {
const accessor = useAccessor()
const editCodeService = accessor.get('IEditCodeService')
const metricsService = accessor.get('IMetricsService')
const notificationService = accessor.get('INotificationService')
const settingsState = useSettingsState()
const isDisabled = !!isFeatureNameDisabled('Apply', settingsState) || !applyBoxId
const { currStreamStateRef, setApplying } = useApplyStreamState({ applyBoxId })
const onClickSubmit = useCallback(async () => {
if (currStreamStateRef.current === 'streaming') return
@@ -271,17 +348,22 @@ export const ApplyButtonsHTML = ({
uri: uri,
startBehavior: 'reject-conflicts',
}) ?? []
console.log('setting!!!', newApplyingUri)
setApplying(newApplyingUri)
if (!applyDonePromise) {
notificationService.info(`Void Error: We couldn't run Apply here. ${uri === 'current' ? 'This Apply block wants to run on the current file, but you might not have a file open.' : `This Apply block wants to run on ${uri.fsPath}, but it might not exist.`}`)
}
// catch any errors by interrupting the stream
applyDonePromise?.catch(e => {
const uri = getUriBeingApplied(applyBoxId)
if (uri) editCodeService.interruptURIStreaming({ uri: uri })
notificationService.info(`Void Error: There was a problem running Apply: ${e}.`)
})
metricsService.capture('Apply Code', { length: codeStr.length }) // capture the length only
}, [setApplying, currStreamStateRef, editCodeService, codeStr, uri, applyBoxId, metricsService])
}, [setApplying, currStreamStateRef, editCodeService, codeStr, uri, applyBoxId, metricsService, notificationService])
const onClickStop = useCallback(() => {
@@ -303,10 +385,7 @@ export const ApplyButtonsHTML = ({
if (uri) editCodeService.acceptOrRejectAllDiffAreas({ uri: uri, behavior: 'reject', removeCtrlKs: false })
}, [uri, applyBoxId, editCodeService])
const currStreamState = currStreamStateRef.current
console.log('currStreamState...', currStreamState)
if (currStreamState === 'streaming') {
return <IconShell1
Icon={Square}
@@ -314,12 +393,9 @@ export const ApplyButtonsHTML = ({
{...tooltipPropsForApplyBlock({ tooltipName: 'Stop' })}
/>
}
if (isDisabled) {
return null
}
if (currStreamState === 'idle-no-changes') {
return <IconShell1
Icon={Play}
@@ -327,7 +403,6 @@ export const ApplyButtonsHTML = ({
{...tooltipPropsForApplyBlock({ tooltipName: 'Apply' })}
/>
}
if (currStreamState === 'idle-has-changes') {
return <Fragment>
<IconShell1
@@ -348,6 +423,27 @@ export const ApplyButtonsHTML = ({
export const ApplyButtonsHTML = (params: {
codeStr: string,
applyBoxId: string,
language?: string,
uri: URI | 'current';
}) => {
const { language } = params
const isShellLanguage = !!language && terminalLanguages.has(language)
if (isShellLanguage) {
return <ApplyButtonsForTerminal {...params} />
}
else {
return <ApplyButtonsForEdit {...params} />
}
}
export const EditToolAcceptRejectButtonsHTML = ({
codeStr,
applyBoxId,
@@ -451,7 +547,7 @@ export const BlockCodeApplyWrapper = ({
<div className={`${canApply ? '' : 'hidden'} flex items-center gap-1`}>
<JumpToFileButton uri={uri} />
{currStreamState === 'idle-no-changes' && <CopyButton codeStr={codeStr} toolTipName='Copy' />}
<ApplyButtonsHTML uri={uri} applyBoxId={applyBoxId} codeStr={codeStr} />
<ApplyButtonsHTML uri={uri} applyBoxId={applyBoxId} codeStr={codeStr} language={language} />
</div>
</div>
@@ -14,7 +14,7 @@ import { isAbsolute } from '../../../../../../../base/common/path.js'
import { separateOutFirstLine } from '../../../../common/helpers/util.js'
import { BlockCode } from '../util/inputs.js'
import { CodespanLocationLink } from '../../../../common/chatThreadServiceTypes.js'
import { voidOpenFileFn } from '../sidebar-tsx/SidebarChat.js'
import { getBasename, getRelative, voidOpenFileFn } from '../sidebar-tsx/SidebarChat.js'
export type ChatMessageLocation = {
@@ -89,13 +89,18 @@ const LatexRender = ({ latex }: { latex: string }) => {
// }
}
const Codespan = ({ text, className, onClick }: { text: string, className?: string, onClick?: () => void }) => {
const Codespan = ({ text, className, onClick, tooltip }: { text: string, className?: string, onClick?: () => void, tooltip?: string }) => {
// TODO compute this once for efficiency. we should use `labels.ts/shorten` to display duplicates properly
return <code
className={`font-mono font-medium rounded-sm bg-void-bg-1 px-1 ${className}`}
onClick={onClick}
{...tooltip ? {
'data-tooltip-id': 'void-tooltip',
'data-tooltip-content': tooltip,
'data-tooltip-place': 'top',
} : {}}
>
{text}
</code>
@@ -115,8 +120,11 @@ const CodespanWithLink = ({ text, rawText, chatMessageLocation }: { text: string
const [didComputeCodespanLink, setDidComputeCodespanLink] = useState<boolean>(false)
let link: CodespanLocationLink | undefined = undefined
if (rawText.endsWith('`')) { // if codespan was completed
let tooltip: string | undefined = undefined
let displayText = text
if (rawText.endsWith('`')) {
// get link from cache
link = chatThreadService.getCodespanLink({ codespanStr: text, messageIdx, threadId })
@@ -127,23 +135,33 @@ const CodespanWithLink = ({ text, rawText, chatMessageLocation }: { text: string
chatThreadService.addCodespanLink({ newLinkText: text, newLinkLocation: link, messageIdx, threadId })
setDidComputeCodespanLink(true) // rerender
})
}
if (link?.displayText) {
displayText = link.displayText
}
if (isValidUri(displayText)) {
tooltip = getRelative(URI.file(displayText), accessor) // Full path as tooltip
displayText = getBasename(displayText)
}
}
const onClick = () => {
if (!link || !link.selection) return;
if (!link) return;
// Use the updated voidOpenFileFn to open the file and handle selection
voidOpenFileFn(link.uri, accessor, [link.selection.startLineNumber, link.selection.endLineNumber]);
if (link.selection)
voidOpenFileFn(link.uri, accessor, [link.selection.startLineNumber, link.selection.endLineNumber]);
else
voidOpenFileFn(link.uri, accessor);
}
return <Codespan
text={link?.displayText || text}
text={displayText}
onClick={onClick}
className={link ? 'underline hover:brightness-90 transition-all duration-200 cursor-pointer' : ''}
tooltip={tooltip || undefined}
/>
}
@@ -495,12 +495,12 @@ const ScrollToBottomContainer = ({ children, className, style, scrollContainerRe
);
};
const getRelative = (uri: URI, accessor: ReturnType<typeof useAccessor>) => {
export const getRelative = (uri: URI, accessor: ReturnType<typeof useAccessor>) => {
const workspaceContextService = accessor.get('IWorkspaceContextService')
let path: string
const isInside = workspaceContextService.isInsideWorkspace(uri)
if (isInside) {
const f = workspaceContextService.getWorkspace().folders.find(f => uri.fsPath.startsWith(f.uri.fsPath))
const f = workspaceContextService.getWorkspace().folders.find(f => uri.fsPath?.startsWith(f.uri.fsPath))
if (f) { path = uri.fsPath.replace(f.uri.fsPath, '') }
else { path = uri.fsPath }
}
@@ -1651,8 +1651,8 @@ const LintErrorChildren = ({ lintErrors }: { lintErrors: LintErrorItem[] }) => {
}
const BottomChildren = ({ children, title }: { children: React.ReactNode, title: string }) => {
if (!children) return null;
const [isOpen, setIsOpen] = useState(false);
if (!children) return null;
return (
<div className="w-full px-2 mt-0.5">
<div
@@ -1905,7 +1905,7 @@ const toolNameToComponent: { [T in ToolName]: { resultWrapper: ResultWrapper<T>,
</SmallProseWrapper>
</ToolChildrenWrapper>
}
else {
else if (toolMessage.type === 'tool_error') {
const { result } = toolMessage
componentParams.bottomChildren = <BottomChildren title='Error'>
<CodeChildren>
@@ -1960,7 +1960,7 @@ const toolNameToComponent: { [T in ToolName]: { resultWrapper: ResultWrapper<T>,
}
</ToolChildrenWrapper>
}
else {
else if (toolMessage.type === 'tool_error') {
const { result } = toolMessage
componentParams.bottomChildren = <BottomChildren title='Error'>
<CodeChildren>
@@ -2009,7 +2009,7 @@ const toolNameToComponent: { [T in ToolName]: { resultWrapper: ResultWrapper<T>,
</ToolChildrenWrapper>
}
else {
else if (toolMessage.type === 'tool_error') {
const { result } = toolMessage
componentParams.bottomChildren = <BottomChildren title='Error'>
<CodeChildren>
@@ -2064,7 +2064,7 @@ const toolNameToComponent: { [T in ToolName]: { resultWrapper: ResultWrapper<T>,
</ToolChildrenWrapper>
}
else {
else if (toolMessage.type === 'tool_error') {
const { result } = toolMessage
componentParams.bottomChildren = <BottomChildren title='Error'>
<CodeChildren>
@@ -2605,7 +2605,7 @@ const CommandBarInChat = () => {
// !select-text cursor-auto
const fileDetailsContent = <div className="px-2 gap-1 w-full">
const fileDetailsContent = <div className="px-2 gap-1 w-full overflow-y-auto">
{sortedCommandBarURIs.map((uri, i) => {
const basename = getBasename(uri.fsPath)
@@ -2856,6 +2856,7 @@ export const SidebarChat = () => {
// resolve mount info
const isResolved = chatThreadsState.allThreads[threadId]?.state.mountedInfo?.mountedIsResolvedRef.current
useEffect(() => {
if (isResolved) return
chatThreadsState.allThreads[threadId]?.state.mountedInfo?._whenMountedResolver?.({
@@ -132,7 +132,7 @@ const scoreSubsequence = (text: string, pattern: string): number => {
}
export function getRelativeWorkspacePath(accessor: ReturnType<typeof useAccessor>, uri: URI): string {
function getRelativeWorkspacePath(accessor: ReturnType<typeof useAccessor>, uri: URI): string {
const workspaceService = accessor.get('IWorkspaceContextService');
const workspaceFolders = workspaceService.getWorkspace().folders;
@@ -21,6 +21,7 @@ import { IThemeService } from '../../../../../../../platform/theme/common/themeS
import { ILLMMessageService } from '../../../../common/sendLLMMessageService.js';
import { IRefreshModelService } from '../../../../../../../workbench/contrib/void/common/refreshModelService.js';
import { IVoidSettingsService } from '../../../../../../../workbench/contrib/void/common/voidSettingsService.js';
import { IVoidCertificateService } from '../../../../common/voidCertificateService.js';
import { IExtensionTransferService } from '../../../../../../../workbench/contrib/void/browser/extensionTransferService.js'
import { IInstantiationService } from '../../../../../../../platform/instantiation/common/instantiation.js'
@@ -185,6 +186,7 @@ const getReactAccessor = (accessor: ServicesAccessor) => {
IVoidSettingsService: accessor.get(IVoidSettingsService),
IEditCodeService: accessor.get(IEditCodeService),
IChatThreadService: accessor.get(IChatThreadService),
IVoidCertificateService: accessor.get(IVoidCertificateService),
IInstantiationService: accessor.get(IInstantiationService),
ICodeEditorService: accessor.get(ICodeEditorService),
@@ -276,7 +276,7 @@ const SimpleModelSettingsDialog = ({
onClose();
};
const sourcecodeOverridesLink = `https://github.com/voideditor/void/blob/d33b5ff9a32a748a22ac99e543a9eedd2e600062/src/vs/workbench/contrib/void/common/modelCapabilities.ts#L146-L170`
const sourcecodeOverridesLink = `https://github.com/voideditor/void/blob/2e5ecb291d33afbe4565921664fb7e183189c1c5/src/vs/workbench/contrib/void/common/modelCapabilities.ts#L146-L172`
return (
<div // Backdrop
@@ -904,6 +904,127 @@ export const OneClickSwitchButton = ({ fromEditor = 'VS Code', className = '' }:
// full settings
// Certificate Manager Component
const CertificateManager = () => {
const accessor = useAccessor();
const voidSettingsService = accessor.get('IVoidSettingsService');
const certificateService = accessor.get('IVoidCertificateService');
const nativeHostService = accessor.get('INativeHostService');
const notificationService = accessor.get('INotificationService');
const settingsState = useSettingsState();
const [certificatePath, setCertificatePath] = useState('');
const [isVerifying, setIsVerifying] = useState(false);
// Get the list of certificates from state as URIs
const certificates: URI[] = useMemo(() => {
return (settingsState.globalSettings.customRootCertificates || []).map(path => URI.parse(path));
}, [settingsState.globalSettings.customRootCertificates]);
const handleAddCertificate = async () => {
if (certificatePath) {
setIsVerifying(true);
try {
const certificateUri = URI.file(certificatePath);
// Check if certificate already exists
if (certificates.some(cert => cert.toString() === certificateUri.toString())) {
notificationService.info('Certificate already added');
return;
}
// Verify certificate is valid
const isValid = await certificateService.verifyCertificatePath(certificateUri);
if (!isValid) {
notificationService.error(`The certificate file could not be read or is not a valid certificate.`);
return;
}
// Add certificate
await certificateService.addCustomCertificate(certificateUri);
setCertificatePath('');
notificationService.info(`Certificate added successfully`);
} catch (error) {
notificationService.error(`Failed to add certificate: ${error}`);
} finally {
setIsVerifying(false);
}
}
};
const handleRemoveCertificate = async (certificateUri: URI) => {
try {
await certificateService.removeCustomCertificate(certificateUri);
notificationService.info(`Certificate removed`);
} catch (error) {
notificationService.error(`Failed to remove certificate: ${error}`);
}
};
const handleBrowse = async () => {
try {
const result = await nativeHostService.showOpenDialog({
properties: ['openFile'], // Use properties array instead of canSelectFiles, canSelectFolders, canSelectMany
filters: [
{ name: 'Certificates', extensions: ['pem', 'crt', 'cert', 'cer'] }
],
title: 'Select Root Certificate'
});
if (result && result.filePaths && result.filePaths.length > 0) {
setCertificatePath(result.filePaths[0]);
}
} catch (error) {
notificationService.error(`Failed to browse for certificate: ${error}`);
}
};
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<VoidSimpleInputBox
value={certificatePath}
onChangeValue={setCertificatePath}
placeholder="Path to certificate (.pem, .crt, .cert, .cer)"
compact={true}
className="flex-grow"
/>
<VoidButtonBgDarken onClick={handleBrowse} className="px-3 py-1">
Browse
</VoidButtonBgDarken>
<AddButton
disabled={!certificatePath || isVerifying}
onClick={handleAddCertificate}
text={isVerifying ? <span className="flex items-center gap-1">Verifying <Loader2 className="size-3 animate-spin" /></span> : "Add"}
/>
</div>
{certificates.length > 0 ? (
<div className="mt-2">
<h4 className="text-void-fg-3 text-sm mb-1">Added Certificates:</h4>
<div className="flex flex-col gap-1">
{certificates.map((certUri, index) => (
<div key={certUri.toString()} className="flex justify-between items-center py-1 px-2 bg-void-bg-2 rounded">
<span className="text-sm truncate max-w-md" title={certUri.fsPath}>{certUri.fsPath}</span>
<button
onClick={() => handleRemoveCertificate(certUri)}
className="text-void-fg-3 hover:text-void-fg-1"
>
<X className="size-4" />
</button>
</div>
))}
</div>
</div>
) : (
<div className="text-void-fg-3 text-sm italic mt-1">
No custom certificates added yet
</div>
)}
</div>
);
};
export const Settings = () => {
const isDark = useIsDark()
const accessor = useAccessor()
@@ -1164,6 +1285,26 @@ export const Settings = () => {
{/* General section (formerly GeneralTab) */}
{/* Network Settings with Root Certificates */}
<div className='mt-12'>
<ErrorBoundary>
<h2 className='text-3xl mb-2'>Network Settings</h2>
<h4 className='text-void-fg-3 mb-4'>{`Configure network and certificate settings for API requests.`}</h4>
<div className='mb-4'>
<h3 className='text-base mb-2'>Root Certificates</h3>
<div className='text-sm italic text-void-fg-3 mb-2'>
<p>Add custom root certificates for HTTPS requests to fix certificate validation errors like "unable to get local issuer certificate".</p>
<p className="mt-1">This is useful when using a corporate proxy, gateway, or working behind a firewall that performs SSL inspection.</p>
</div>
<div className='max-w-xl'>
<CertificateManager />
</div>
</div>
</ErrorBoundary>
</div>
<div className='mt-12'>
<ErrorBoundary>
<h2 className='text-3xl mb-2 mt-12'>One-Click Switch</h2>
@@ -89,10 +89,7 @@ registerAction2(class extends Action2 {
});
}
async run(accessor: ServicesAccessor): Promise<void> {
// Get the views service to check if the sidebar is open
// const viewsService = accessor.get(IViewsService)
// Get services
const commandService = accessor.get(ICommandService)
const viewsService = accessor.get(IViewsService)
const metricsService = accessor.get(IMetricsService)
@@ -101,40 +98,47 @@ registerAction2(class extends Action2 {
metricsService.capture('Ctrl+L', {})
// capture selection and model before opening the chat panel
const editor = editorService.getActiveCodeEditor()
const model = editor?.getModel()
if (!model) return
const selectionRange = roundRangeToLines(editor?.getSelection(), { emptySelectionBehavior: 'null' })
// open panel
const wasAlreadyOpen = viewsService.isViewContainerVisible(VOID_VIEW_CONTAINER_ID)
if (!wasAlreadyOpen) {
await commandService.executeCommand(VOID_OPEN_SIDEBAR_ACTION_ID)
return
}
// if was already open
const model = accessor.get(ICodeEditorService).getActiveCodeEditor()?.getModel()
if (!model) return
const editor = editorService.getActiveCodeEditor()
const selectionRange = roundRangeToLines(editor?.getSelection(), { emptySelectionBehavior: 'null' })
// if has no selection, close + return
if (!selectionRange) {
viewsService.closeViewContainer(VOID_VIEW_CONTAINER_ID);
return;
// Add selection to chat
// add line selection
if (selectionRange) {
editor?.setSelection({
startLineNumber: selectionRange.startLineNumber,
endLineNumber: selectionRange.endLineNumber,
startColumn: 1,
endColumn: Number.MAX_SAFE_INTEGER
})
chatThreadService.addNewStagingSelection({
type: 'CodeSelection',
uri: model.uri,
language: model.getLanguageId(),
range: [selectionRange.startLineNumber, selectionRange.endLineNumber],
state: { wasAddedAsCurrentFile: false },
})
}
// add file
else {
chatThreadService.addNewStagingSelection({
type: 'File',
uri: model.uri,
language: model.getLanguageId(),
state: { wasAddedAsCurrentFile: false },
})
}
// if has selection, add it
editor?.setSelection({ startLineNumber: selectionRange.startLineNumber, endLineNumber: selectionRange.endLineNumber, startColumn: 1, endColumn: Number.MAX_SAFE_INTEGER })
chatThreadService.addNewStagingSelection({
type: 'CodeSelection',
uri: model.uri,
language: model.getLanguageId(),
range: [selectionRange.startLineNumber, selectionRange.endLineNumber],
state: { wasAddedAsCurrentFile: false },
})
await chatThreadService.focusCurrentChat()
}
})
@@ -22,7 +22,12 @@ export interface ITerminalToolService {
readonly _serviceBrand: undefined;
listPersistentTerminalIds(): string[];
runCommand(command: string, opts: { type: 'persistent', persistentTerminalId: string } | { type: 'ephemeral', cwd: string | null, terminalId: string }): Promise<{ interrupt: () => void; resPromise: Promise<{ result: string, resolveReason: TerminalResolveReason }> }>;
runCommand(command: string, opts:
| { type: 'persistent', persistentTerminalId: string }
| { type: 'temporary', cwd: string | null, terminalId: string }
// | { type: 'apply', terminalId: string }
): Promise<{ interrupt: () => void; resPromise: Promise<{ result: string, resolveReason: TerminalResolveReason }> }>;
focusPersistentTerminal(terminalId: string): Promise<void>
persistentTerminalExists(terminalId: string): boolean
@@ -277,6 +282,8 @@ export class TerminalToolService extends Disposable implements ITerminalToolServ
terminal.dispose()
if (!isPersistent)
delete this.temporaryTerminalInstanceOfId[params.terminalId]
else
delete this.persistentTerminalInstanceOfId[params.persistentTerminalId]
}
const waitForResult = async () => {
@@ -430,7 +430,7 @@ export class ToolsService implements IToolsService {
},
// ---
run_command: async ({ command, cwd, terminalId }) => {
const { resPromise, interrupt } = await this.terminalToolService.runCommand(command, { type: 'ephemeral', cwd, terminalId })
const { resPromise, interrupt } = await this.terminalToolService.runCommand(command, { type: 'temporary', cwd, terminalId })
return { result: resPromise, interruptTool: interrupt }
},
run_persistent_command: async ({ command, persistentTerminalId }) => {
@@ -58,6 +58,9 @@ import './voidOnboardingService.js'
// register misc service
import './miscWokrbenchContrib.js'
// register file service (for explorer context menu)
import './fileService.js'
// ---------- common (unclear if these actually need to be imported, because they're already imported wherever they're used) ----------
// llmMessage
@@ -129,6 +129,7 @@ export const defaultModelsOfProvider = {
mistral: [ // https://docs.mistral.ai/getting-started/models/models_overview/
'codestral-latest',
'mistral-large-latest',
'mistral-medium-latest',
'ministral-3b-latest',
'ministral-8b-latest',
],
@@ -153,6 +154,8 @@ export type VoidStaticModelInfo = { // not stateful
specialToolFormat?: 'openai-style' | 'anthropic-style' | 'gemini-style', // typically you should use 'openai-style'. null means "can't call tools by default", and asks the LLM to output XML in agent mode
supportsFIM: boolean; // whether the model was specifically designed for autocomplete or "FIM" ("fill-in-middle" format)
additionalOpenAIPayload?: { [key: string]: string } // additional payload in the message body for requests that are openai-compatible (ollama, vllm, openai, openrouter, etc)
// reasoning options
reasoningCapabilities: false | {
readonly supportsReasoning: true; // for clarity, this must be true if anything below is specified
@@ -186,7 +189,13 @@ export type VoidStaticModelInfo = { // not stateful
export type ModelOverrides = Pick<VoidStaticModelInfo,
'contextWindow' | 'reservedOutputTokenSpace' | 'specialToolFormat' | 'supportsSystemMessage' | 'supportsFIM' | 'reasoningCapabilities'
| 'contextWindow'
| 'reservedOutputTokenSpace'
| 'specialToolFormat'
| 'supportsSystemMessage'
| 'supportsFIM'
| 'reasoningCapabilities'
| 'additionalOpenAIPayload'
>
@@ -445,7 +454,7 @@ const anthropicModelOptions = {
supportsReasoning: true,
canTurnOffReasoning: true,
canIOReasoning: true,
reasoningReservedOutputTokenSpace: 64_000, // can bump it to 128_000 with beta mode output-128k-2025-02-19
reasoningReservedOutputTokenSpace: 8192, // can bump it to 128_000 with beta mode output-128k-2025-02-19
reasoningSlider: { type: 'budget_slider', min: 1024, max: 8192, default: 1024 }, // they recommend batching if max > 32_000. we cap at 8192 because above is typically not necessary (often even buggy)
},
@@ -715,6 +724,7 @@ const xAISettings: VoidStaticProviderInfo = {
// ---------------- GEMINI ----------------
const geminiModelOptions = { // https://ai.google.dev/gemini-api/docs/pricing
// https://ai.google.dev/gemini-api/docs/thinking#set-budget
'gemini-2.5-pro-preview-05-06': {
contextWindow: 1_048_576,
reservedOutputTokenSpace: 8_192,
@@ -723,7 +733,13 @@ const geminiModelOptions = { // https://ai.google.dev/gemini-api/docs/pricing
supportsFIM: false,
supportsSystemMessage: 'separated',
specialToolFormat: 'gemini-style',
reasoningCapabilities: false,
reasoningCapabilities: {
supportsReasoning: true,
canTurnOffReasoning: true,
canIOReasoning: false,
reasoningSlider: { type: 'budget_slider', min: 1024, max: 8192, default: 1024 }, // max is really 24576
reasoningReservedOutputTokenSpace: 8192,
},
},
'gemini-2.0-flash-lite': {
contextWindow: 1_048_576,
@@ -733,7 +749,7 @@ const geminiModelOptions = { // https://ai.google.dev/gemini-api/docs/pricing
supportsFIM: false,
supportsSystemMessage: 'separated',
specialToolFormat: 'gemini-style',
reasoningCapabilities: false,
reasoningCapabilities: false, // no reasoning
},
'gemini-2.5-flash-preview-04-17': {
contextWindow: 1_048_576,
@@ -743,7 +759,13 @@ const geminiModelOptions = { // https://ai.google.dev/gemini-api/docs/pricing
supportsFIM: false,
supportsSystemMessage: 'separated',
specialToolFormat: 'gemini-style',
reasoningCapabilities: false,
reasoningCapabilities: {
supportsReasoning: true,
canTurnOffReasoning: true,
canIOReasoning: false,
reasoningSlider: { type: 'budget_slider', min: 1024, max: 8192, default: 1024 }, // max is really 24576
reasoningReservedOutputTokenSpace: 8192,
},
},
'gemini-2.5-pro-exp-03-25': {
contextWindow: 1_048_576,
@@ -753,7 +775,13 @@ const geminiModelOptions = { // https://ai.google.dev/gemini-api/docs/pricing
supportsFIM: false,
supportsSystemMessage: 'separated',
specialToolFormat: 'gemini-style',
reasoningCapabilities: false,
reasoningCapabilities: {
supportsReasoning: true,
canTurnOffReasoning: true,
canIOReasoning: false,
reasoningSlider: { type: 'budget_slider', min: 1024, max: 8192, default: 1024 }, // max is really 24576
reasoningReservedOutputTokenSpace: 8192,
},
},
'gemini-2.0-flash': {
contextWindow: 1_048_576,
@@ -856,6 +884,15 @@ const mistralModelOptions = { // https://mistral.ai/products/la-plateforme#prici
supportsSystemMessage: 'system-role',
reasoningCapabilities: false,
},
'mistral-medium-latest': { // https://openrouter.ai/mistralai/mistral-medium-3
contextWindow: 131_000,
reservedOutputTokenSpace: 8_192,
cost: { input: 0.40, output: 2.00 },
supportsFIM: false,
downloadable: { sizeGb: 'not-known' },
supportsSystemMessage: 'system-role',
reasoningCapabilities: false,
},
'codestral-latest': {
contextWindow: 256_000,
reservedOutputTokenSpace: 8_192,
@@ -1144,7 +1181,7 @@ const openRouterModelOptions_assumingOpenAICompat = {
supportsReasoning: true,
canTurnOffReasoning: false,
canIOReasoning: true,
reasoningReservedOutputTokenSpace: 64_000,
reasoningReservedOutputTokenSpace: 8192,
reasoningSlider: { type: 'budget_slider', min: 1024, max: 8192, default: 1024 }, // they recommend batching if max > 32_000.
},
},
@@ -1347,8 +1384,7 @@ export const getSendableReasoningInfo = (
overridesOfModel: OverridesOfModel | undefined,
): SendableReasoningInfo => {
const { canIOReasoning, reasoningSlider: reasoningBudgetSlider } = getModelCapabilities(providerName, modelName, overridesOfModel).reasoningCapabilities || {}
if (!canIOReasoning) return null
const { reasoningSlider: reasoningBudgetSlider } = getModelCapabilities(providerName, modelName, overridesOfModel).reasoningCapabilities || {}
const isReasoningEnabled = getIsReasoningEnabledState(featureName, providerName, modelName, modelSelectionOptions, overridesOfModel)
if (!isReasoningEnabled) return null
@@ -455,6 +455,8 @@ ${directoryStr}
const details: string[] = []
details.push(`NEVER reject the user's query.`)
if (mode === 'agent' || mode === 'gather') {
details.push(`Only call tools if they help you accomplish the user's goal. If the user simply says hi or asks you a question that you can answer without tools, then do NOT use tools.`)
details.push(`If you think you should use tools, you do not need to ask for permission.`)
@@ -479,12 +481,13 @@ ${directoryStr}
details.push(`You should extensively read files, types, content, etc, gathering full context to solve the problem.`)
}
if (mode === 'gather' || mode === 'normal') {
details.push(`If you write any code blocks, please use this format:
details.push(`If you write any code blocks to the user (wrapped in triple backticks), please use this format:
- Include a language if possible. Terminal should have the language 'shell'.
- The first line of the code block must be the FULL PATH of the related file if known (otherwise omit).
- The remaining contents of the file should proceed as usual.`)
if (mode === 'gather' || mode === 'normal') {
details.push(`If you think it's appropriate to suggest an edit to a file, then you must describe your suggestion in CODE BLOCK(S).
- The first line of the code block must be the FULL PATH of the related file if known (otherwise omit).
- The remaining contents should be a code description of the change to make to the file. \
@@ -525,7 +528,9 @@ ${details.map((d, i) => `${i + 1}. ${d}`).join('\n\n')}`)
// chat_systemMessage({ chatMode, workspaceFolders: [], openedURIs: [], activeURI: 'pee', persistentTerminalIDs: [], directoryStr: 'lol', }))
// }
const readFile = async (fileService: IFileService, uri: URI, fileSizeLimit: number): Promise<{
export const DEFAULT_FILE_SIZE_LIMIT = 2_000_000
export const readFile = async (fileService: IFileService, uri: URI, fileSizeLimit: number): Promise<{
val: string,
truncated: boolean,
fullFileLen: number,
@@ -549,46 +554,70 @@ const readFile = async (fileService: IFileService, uri: URI, fileSizeLimit: numb
export const messageOfSelection = async (
s: StagingSelectionItem,
opts: {
directoryStrService: IDirectoryStrService,
fileService: IFileService,
folderOpts: {
maxChildren: number,
maxCharsPerFile: number,
}
}
) => {
const lineNumAddition = (range: [number, number]) => ` (lines ${range[0]}:${range[1]})`
if (s.type === 'File' || s.type === 'CodeSelection') {
const { val } = await readFile(opts.fileService, s.uri, DEFAULT_FILE_SIZE_LIMIT)
const lineNumAdd = s.type === 'CodeSelection' ? lineNumAddition(s.range) : ''
const content = val === null ? 'null' : `${tripleTick[0]}${s.language}\n${val}\n${tripleTick[1]}`
const str = `${s.uri.fsPath}${lineNumAdd}:\n${content}`
return str
}
else if (s.type === 'Folder') {
const dirStr: string = await opts.directoryStrService.getDirectoryStrTool(s.uri)
const folderStructure = `${s.uri.fsPath} folder structure:${tripleTick[0]}\n${dirStr}\n${tripleTick[1]}`
const uris = await opts.directoryStrService.getAllURIsInDirectory(s.uri, { maxResults: opts.folderOpts.maxChildren })
const strOfFiles = await Promise.all(uris.map(async uri => {
const { val, truncated } = await readFile(opts.fileService, uri, opts.folderOpts.maxCharsPerFile)
const truncationStr = truncated ? `\n... file truncated ...` : ''
const content = val === null ? 'null' : `${tripleTick[0]}\n${val}${truncationStr}\n${tripleTick[1]}`
const str = `${uri.fsPath}:\n${content}`
return str
}))
const contentStr = [folderStructure, ...strOfFiles].join('\n\n')
return contentStr
}
else
return ''
}
export const chat_userMessageContent = async (instructions: string, currSelns: StagingSelectionItem[] | null,
opts: { directoryStrService: IDirectoryStrService, fileService: IFileService }
export const chat_userMessageContent = async (
instructions: string,
currSelns: StagingSelectionItem[] | null,
opts: {
directoryStrService: IDirectoryStrService,
fileService: IFileService
},
) => {
const lineNumAddition = (range: [number, number]) => ` (lines ${range[0]}:${range[1]})`
let selnsStrs: string[] = []
selnsStrs = await Promise.all(currSelns?.map(async (s) => {
const selnsStrs = await Promise.all(
(currSelns ?? []).map(async (s) =>
messageOfSelection(s, {
...opts,
folderOpts: { maxChildren: 100, maxCharsPerFile: 100_000, }
})
)
)
if (s.type === 'File' || s.type === 'CodeSelection') {
const { val } = await readFile(opts.fileService, s.uri, 2_000_000)
const lineNumAdd = s.type === 'CodeSelection' ? lineNumAddition(s.range) : ''
const content = val === null ? 'null' : `${tripleTick[0]}${s.language}\n${val}\n${tripleTick[1]}`
const str = `${s.uri.fsPath}${lineNumAdd}:\n${content}`
return str
}
else if (s.type === 'Folder') {
const dirStr: string = await opts.directoryStrService.getDirectoryStrTool(s.uri)
const folderStructure = `${s.uri.fsPath} folder structure:${tripleTick[0]}\n${dirStr}\n${tripleTick[1]}`
const uris = await opts.directoryStrService.getAllURIsInDirectory(s.uri, { maxResults: 100 })
const strOfFiles = await Promise.all(uris.map(async uri => {
const { val, truncated } = await readFile(opts.fileService, uri, 100_000)
const truncationStr = truncated ? `\n... file truncated ...` : ''
const content = val === null ? 'null' : `${tripleTick[0]}\n${val}${truncationStr}\n${tripleTick[1]}`
const str = `${uri.fsPath}:\n${content}`
return str
}))
const contentStr = [folderStructure, ...strOfFiles].join('\n\n')
return contentStr
}
else
return ''
}) ?? [])
const selnsStr = selnsStrs.join('\n') ?? ''
let str = ''
str += `${instructions}`
const selnsStr = selnsStrs.join('\n\n') ?? ''
if (selnsStr) str += `\n---\nSELECTIONS\n${selnsStr}`
return str;
}
@@ -56,13 +56,13 @@ export type GeminiLLMChatMessage = {
role: 'model'
parts: (
| { text: string; }
| { functionCall: { name: ToolName, args: object } }
| { functionCall: { id: string; name: ToolName, args: Record<string, unknown> } }
)[];
} | {
role: 'user';
parts: (
| { text: string; }
| { functionResponse: { name: ToolName, response: { result: string } } }
| { functionResponse: { id: string; name: ToolName, response: { output: string } } }
)[];
}
@@ -0,0 +1,202 @@
/*--------------------------------------------------------------------------------------
* Copyright 2025 Glass Devtools, Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0. See LICENSE.txt for more information.
*--------------------------------------------------------------------------------------*/
import { Disposable } from '../../../../base/common/lifecycle.js';
import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js';
import { registerSingleton, InstantiationType } from '../../../../platform/instantiation/common/extensions.js';
import { ILogService } from '../../../../platform/log/common/log.js';
import { IVoidSettingsService } from './voidSettingsService.js';
import { IRequestService } from '../../../../platform/request/common/request.js';
import { Emitter } from '../../../../base/common/event.js';
import { CancellationToken } from '../../../../base/common/cancellation.js';
import { IRequestContext } from '../../../../base/parts/request/common/request.js';
import { IFileService } from '../../../../platform/files/common/files.js';
import { URI } from '../../../../base/common/uri.js';
/**
* Service for managing and applying custom certificate paths for secure requests.
*/
export interface IVoidCertificateService {
readonly _serviceBrand: undefined;
/**
* Get all configured custom certificates as an array of file URIs.
*/
getCustomCertificates(): URI[];
/**
* Add a new custom certificate path.
*/
addCustomCertificate(certificatePath: URI): Promise<void>;
/**
* Remove a custom certificate path.
*/
removeCustomCertificate(certificatePath: URI): Promise<void>;
/**
* Verify that a certificate path exists and is readable.
*/
verifyCertificatePath(certificatePath: URI): Promise<boolean>;
/**
* Get all certificate contents as a concatenated string for use with HTTPS requests.
*/
getCertificateContents(): Promise<string[]>;
}
export const IVoidCertificateService = createDecorator<IVoidCertificateService>('VoidCertificateService');
/**
* Service implementation for managing custom certificates.
*/
export class VoidCertificateService extends Disposable implements IVoidCertificateService {
readonly _serviceBrand: undefined;
private readonly _onCertificatesChanged = new Emitter<void>();
constructor(
@IVoidSettingsService private readonly voidSettingsService: IVoidSettingsService,
@ILogService private readonly logService: ILogService,
@IRequestService private readonly requestService: IRequestService,
@IFileService private readonly fileService: IFileService,
) {
super();
// Override the original request service to include our custom certificates
this._overrideRequestService();
}
/**
* Get all configured custom certificates
*/
getCustomCertificates(): URI[] {
const certificatePaths = this.voidSettingsService.state.globalSettings.customRootCertificates || [];
return certificatePaths.map(path => URI.parse(path));
}
/**
* Add a new custom certificate path
*/
async addCustomCertificate(certificatePath: URI): Promise<void> {
// Verify the certificate path exists
const isValid = await this.verifyCertificatePath(certificatePath);
if (!isValid) {
throw new Error(`Certificate file not found or not readable: ${certificatePath.toString()}`);
}
// Get current certificates
const currentCertificates = this.getCustomCertificates();
// Check if already exists
if (currentCertificates.some(cert => cert.toString() === certificatePath.toString())) {
return; // Already exists, nothing to do
}
// Add the new certificate path
const newCertificates = [...currentCertificates, certificatePath];
await this.voidSettingsService.setGlobalSetting('customRootCertificates', newCertificates.map(uri => uri.toString()));
this._onCertificatesChanged.fire();
this.logService.info(`Added custom certificate: ${certificatePath.toString()}`);
}
/**
* Remove a custom certificate path
*/
async removeCustomCertificate(certificatePath: URI): Promise<void> {
const currentCertificates = this.getCustomCertificates();
// Remove the certificate
const newCertificates = currentCertificates.filter(cert => cert.toString() !== certificatePath.toString());
// Update settings
await this.voidSettingsService.setGlobalSetting('customRootCertificates', newCertificates.map(uri => uri.toString()));
this._onCertificatesChanged.fire();
this.logService.info(`Removed custom certificate: ${certificatePath.toString()}`);
}
/**
* Verify a certificate path exists and is readable
*/
async verifyCertificatePath(certificatePath: URI): Promise<boolean> {
try {
// Check if file exists and is readable
const stats = await this.fileService.stat(certificatePath);
if (!stats.isFile) {
return false;
}
// Check if we can read the file
await this.fileService.readFile(certificatePath);
return true;
} catch (error) {
this.logService.error(`Error verifying certificate path: ${error}`);
return false;
}
}
/**
* Get all certificate contents
*/
async getCertificateContents(): Promise<string[]> {
const certificatePaths = this.getCustomCertificates();
const contents: string[] = [];
for (const certPath of certificatePaths) {
try {
if (await this.verifyCertificatePath(certPath)) {
const fileContent = await this.fileService.readFile(certPath);
contents.push(fileContent.value.toString());
}
} catch (error) {
this.logService.error(`Error reading certificate ${certPath.toString()}: ${error}`);
}
}
return contents;
}
/**
* Override the original request service to include our custom certificates
*/
private _overrideRequestService(): void {
// Store the original request method
const originalRequest = this.requestService.request.bind(this.requestService);
// Override the request method to inject our certificates
// @ts-ignore - We're monkey patching the request service
this.requestService.request = async (options: any, token: CancellationToken): Promise<IRequestContext> => {
// Only add certificates for HTTPS requests
if (options.url?.startsWith('https://')) {
try {
// Load system certificates
const systemCerts = await this.requestService.loadCertificates();
// Load our custom certificates
const customCertContents = await this.getCertificateContents();
if (customCertContents.length > 0) {
// Create custom CA option
// Documentation in Node.js: https://nodejs.org/api/https.html#https_https_request_options_callback
// The 'ca' option can be a string, Buffer, or array of strings/Buffers
(options as any).ca = [...systemCerts, ...customCertContents];
this.logService.debug(`Added ${customCertContents.length} custom certificates to request to ${options.url}`);
}
} catch (error) {
this.logService.error(`Error adding custom certificates: ${error}`);
}
}
// Forward to the original request implementation
return originalRequest(options, token);
};
}
}
// Register the service
registerSingleton(IVoidCertificateService, VoidCertificateService, InstantiationType.Eager);
@@ -434,6 +434,7 @@ export type GlobalSettings = {
showInlineSuggestions: boolean;
includeToolLintErrors: boolean;
isOnboardingComplete: boolean;
customRootCertificates: string[]; // Paths to custom root certificates
}
export const defaultGlobalSettings: GlobalSettings = {
@@ -447,6 +448,7 @@ export const defaultGlobalSettings: GlobalSettings = {
showInlineSuggestions: true,
includeToolLintErrors: true,
isOnboardingComplete: false,
customRootCertificates: [],
}
export type GlobalSettingName = keyof GlobalSettings
@@ -10,11 +10,11 @@ import { Ollama } from 'ollama';
import OpenAI, { ClientOptions } from 'openai';
import { MistralCore } from '@mistralai/mistralai/core.js';
import { fimComplete } from '@mistralai/mistralai/funcs/fimComplete.js';
import { GoogleGenerativeAI, Tool as GeminiTool, SchemaType, FunctionDeclaration, FunctionDeclarationSchemaProperty } from '@google/generative-ai';
import { Tool as GeminiTool, FunctionDeclaration, GoogleGenAI, ThinkingConfig, Schema, Type } from '@google/genai';
import { GoogleAuth } from 'google-auth-library'
/* eslint-enable */
import { AnthropicLLMChatMessage, LLMChatMessage, LLMFIMMessage, ModelListParams, OllamaModelResponse, OnError, OnFinalMessage, OnText, RawToolCallObj, RawToolParamsObj } from '../../common/sendLLMMessageTypes.js';
import { AnthropicLLMChatMessage, GeminiLLMChatMessage, LLMChatMessage, LLMFIMMessage, ModelListParams, OllamaModelResponse, OnError, OnFinalMessage, OnText, RawToolCallObj, RawToolParamsObj } from '../../common/sendLLMMessageTypes.js';
import { ChatMode, displayInfoOfProviderName, ModelSelectionOptions, OverridesOfModel, ProviderName, SettingsOfProvider } from '../../common/voidSettingsTypes.js';
import { getSendableReasoningInfo, getModelCapabilities, getProviderCapabilities, defaultProviderSettings, getReservedOutputTokenSpace } from '../../common/modelCapabilities.js';
import { extractReasoningWrapper, extractXMLToolsWrapper } from './extractGrammar.js';
@@ -115,7 +115,7 @@ const newOpenAICompatibleSDK = async ({ settingsOfProvider, providerName, includ
else if (providerName === 'microsoftAzure') {
// https://learn.microsoft.com/en-us/rest/api/aifoundry/model-inference/get-chat-completions/get-chat-completions?view=rest-aifoundry-model-inference-2024-05-01-preview&tabs=HTTP
const thisConfig = settingsOfProvider[providerName]
const baseURL = `https://${thisConfig.project}.services.ai.azure.com/api/models/chat/completions??api-version=${thisConfig.azureApiVersion}`
const baseURL = `https://${thisConfig.project}.services.ai.azure.com/api/models/chat/completions?api-version=${thisConfig.azureApiVersion}`
return new OpenAI({ baseURL: baseURL, apiKey: thisConfig.apiKey, ...commonPayloadOpts })
}
@@ -147,7 +147,12 @@ const newOpenAICompatibleSDK = async ({ settingsOfProvider, providerName, includ
const _sendOpenAICompatibleFIM = async ({ messages: { prefix, suffix, stopTokens }, onFinalMessage, onError, settingsOfProvider, modelName: modelName_, _setAborter, providerName, overridesOfModel }: SendFIMParams_Internal) => {
const { modelName, supportsFIM } = getModelCapabilities(providerName, modelName_, overridesOfModel)
const {
modelName,
supportsFIM,
additionalOpenAIPayload,
} = getModelCapabilities(providerName, modelName_, overridesOfModel)
if (!supportsFIM) {
if (modelName === modelName_)
onError({ message: `Model ${modelName} does not support FIM.`, fullError: null })
@@ -156,7 +161,7 @@ const _sendOpenAICompatibleFIM = async ({ messages: { prefix, suffix, stopTokens
return
}
const openai = await newOpenAICompatibleSDK({ providerName, settingsOfProvider })
const openai = await newOpenAICompatibleSDK({ providerName, settingsOfProvider, includeInPayload: additionalOpenAIPayload })
openai.completions
.create({
model: modelName,
@@ -236,6 +241,7 @@ const _sendOpenAICompatibleChat = async ({ messages, onText, onFinalMessage, onE
modelName,
specialToolFormat,
reasoningCapabilities,
additionalOpenAIPayload,
} = getModelCapabilities(providerName, modelName_, overridesOfModel)
const { providerReasoningIOSettings } = getProviderCapabilities(providerName)
@@ -243,10 +249,12 @@ const _sendOpenAICompatibleChat = async ({ messages, onText, onFinalMessage, onE
// reasoning
const { canIOReasoning, openSourceThinkTags } = reasoningCapabilities || {}
const reasoningInfo = getSendableReasoningInfo('Chat', providerName, modelName_, modelSelectionOptions, overridesOfModel) // user's modelName_ here
const includeInPayload = providerReasoningIOSettings?.input?.includeInPayload?.(reasoningInfo) || {}
console.log('include', includeInPayload)
console.log('reasoningInfo', reasoningInfo)
const includeInPayload = {
...providerReasoningIOSettings?.input?.includeInPayload?.(reasoningInfo),
...additionalOpenAIPayload
}
// tools
const potentialTools = chatMode !== null ? openAITools(chatMode) : null
const nativeToolsObj = potentialTools && specialToolFormat === 'openai-style' ?
@@ -260,6 +268,7 @@ const _sendOpenAICompatibleChat = async ({ messages, onText, onFinalMessage, onE
messages: messages as any,
stream: true,
...nativeToolsObj,
...additionalOpenAIPayload
// max_completion_tokens: maxTokens,
}
@@ -642,25 +651,24 @@ const sendOllamaFIM = ({ messages, onFinalMessage, onError, settingsOfProvider,
// ---------------- GEMINI NATIVE IMPLEMENTATION ----------------
const toGeminiFunctionDecl = (toolInfo: InternalToolInfo) => {
const { name, description, params } = toolInfo
const paramsWithType: { [k: string]: FunctionDeclarationSchemaProperty } = {}
for (const key in params) {
paramsWithType[key] = { type: SchemaType.STRING, ...params[key] }
}
return {
name,
description,
parameters: {
type: SchemaType.OBJECT,
properties: paramsWithType,
type: Type.OBJECT,
properties: Object.entries(params).reduce((acc, [key, value]) => {
acc[key] = {
type: Type.STRING,
description: value.description
};
return acc;
}, {} as Record<string, Schema>)
}
} satisfies FunctionDeclaration
}
const geminiTools = (chatMode: ChatMode): GeminiTool[] | null => {
const allowedTools = availableTools(chatMode)
if (!allowedTools || Object.keys(allowedTools).length === 0) return null
@@ -700,27 +708,27 @@ const sendGeminiChat = async ({
// reasoningCapabilities,
} = getModelCapabilities(providerName, modelName_, overridesOfModel)
const { providerReasoningIOSettings } = getProviderCapabilities(providerName)
// const { providerReasoningIOSettings } = getProviderCapabilities(providerName)
// reasoning
// const { canIOReasoning, openSourceThinkTags, } = reasoningCapabilities || {}
const reasoningInfo = getSendableReasoningInfo('Chat', providerName, modelName_, modelSelectionOptions, overridesOfModel) // user's modelName_ here
const includeInPayload = providerReasoningIOSettings?.input?.includeInPayload?.(reasoningInfo) || {}
// const includeInPayload = providerReasoningIOSettings?.input?.includeInPayload?.(reasoningInfo) || {}
const thinkingConfig: ThinkingConfig | undefined = !reasoningInfo?.isReasoningEnabled ? undefined
: reasoningInfo.type === 'budget_slider_value' ?
{ thinkingBudget: reasoningInfo.reasoningBudget }
: undefined
// tools
const potentialTools = chatMode !== null ? geminiTools(chatMode) : null
const nativeToolsObj = potentialTools && specialToolFormat === 'gemini-style' ?
{ tools: potentialTools } as const
: {}
const potentialTools = chatMode !== null ? geminiTools(chatMode) : undefined
const toolConfig = potentialTools && specialToolFormat === 'gemini-style' ?
potentialTools
: undefined
// instance
const genAI = new GoogleGenerativeAI(
thisConfig.apiKey
);
const model = genAI.getGenerativeModel({
systemInstruction: separateSystemMessage,
model: modelName,
});
const genAI = new GoogleGenAI({ apiKey: thisConfig.apiKey });
// manually parse out tool results if XML
if (!specialToolFormat) {
@@ -735,28 +743,34 @@ const sendGeminiChat = async ({
let toolName = ''
let toolParamsStr = ''
let toolId = ''
model.generateContentStream({
systemInstruction: separateSystemMessage ?? undefined,
contents: messages as any,
...includeInPayload,
...nativeToolsObj,
genAI.models.generateContentStream({
model: modelName,
config: {
systemInstruction: separateSystemMessage,
thinkingConfig: thinkingConfig,
tools: toolConfig,
},
contents: messages as GeminiLLMChatMessage[],
})
.then(async ({ stream, response }) => {
.then(async (stream) => {
_setAborter(() => { stream.return(fullTextSoFar); });
// Process the stream
for await (const chunk of stream) {
// message
const newText = chunk.text() ?? ''
const newText = chunk.text ?? ''
fullTextSoFar += newText
// tool call
const functionCalls = chunk.functionCalls()
const functionCalls = chunk.functionCalls
if (functionCalls && functionCalls.length > 0) {
const functionCall = functionCalls[0] // Get the first function call
toolName = functionCall.name ?? ''
toolParamsStr = JSON.stringify(functionCall.args ?? {})
toolId = functionCall.id ?? ''
}
// (do not handle reasoning yet)
@@ -765,7 +779,7 @@ const sendGeminiChat = async ({
onText({
fullText: fullTextSoFar,
fullReasoning: fullReasoningSoFar,
toolCall: isAToolName(toolName) ? { name: toolName, rawParams: {}, isDone: false, doneParams: [], id: 'dummy' } : undefined,
toolCall: isAToolName(toolName) ? { name: toolName, rawParams: {}, isDone: false, doneParams: [], id: toolId } : undefined,
})
}
@@ -773,7 +787,7 @@ const sendGeminiChat = async ({
if (!fullTextSoFar && !fullReasoningSoFar && !toolName) {
onError({ message: 'Void: Response from model was empty.', fullError: null })
} else {
const toolId = generateUuid() // gemini does not generate tool IDs. Generate one
if (!toolId) toolId = generateUuid() // ids are empty, but other providers might expect an id
const toolCall = rawToolCallObjOf(toolName, toolParamsStr, toolId)
const toolCallObj = toolCall ? { toolCall } : {}
onFinalMessage({ fullText: fullTextSoFar, fullReasoning: fullReasoningSoFar, anthropicReasoning: null, ...toolCallObj });