import { EventEmitter } from "events" import fs from "fs/promises" import * as path from "path" import * as os from "os" import * as vscode from "vscode" import deepEqual from "fast-deep-equal" import pWaitFor from "p-wait-for" import { type RooCodeAPI, type RooCodeTestOnlyApi, type GlobalState, type RooCodeSettings, type RooCodeEvents, type ProviderSettings, type ProviderSettingsEntry, type TaskEvent, type TaskLike, type TaskStartResponse, type CreateTaskOptions, type TaskApiConversationHistorySequence, type WebviewThemeFixture, RooCodeEventName, TaskCommandName, isGlobalStateKey, isSecretStateKey, isSensitiveProviderConfigKey, globalSettingsSchema, PROVIDER_SETTINGS_KEYS, IpcOrigin, IpcMessageType, TASK_START_FAILURE_ERROR_CODE, TASK_START_FAILURE_ERROR_MESSAGE, type MentionSegment, } from "@roo-code/types" import { IpcServer } from "@roo-code/ipc" import { userSegments } from "../shared/mentionSegments" import { Package } from "../shared/package" import { getAllModes, type Mode } from "../shared/modes" import { ClineProvider } from "../core/webview/ClineProvider" import type { ClineProviderFactory } from "../core/webview/ClineProviderFactory" import type { Task } from "../core/task/Task" import { isNonPortableSettingsKey } from "../core/config/ContextProxy" import { withoutInvalidDisplaySettings } from "../core/config/displaySettings" import { readTaskMessages, TaskMessagesReadError } from "../core/task-persistence/taskMessages" import { getErrorCode } from "../core/task-persistence/readFileWithMissingRetry" import { tracePersistenceEvent } from "../core/task-persistence/persistenceTrace" import { Terminal } from "../integrations/terminal/Terminal" import { TerminalRegistry } from "../integrations/terminal/TerminalRegistry" import { createClineTabPanel } from "../activate/registerCommands" import { getCommands } from "../services/command/commands" type TaskAskController = { approveAsk(): void denyAsk(): void handleWebviewAskResponse(response: "messageResponse", text?: string, images?: string[]): void } type RegisteredTask = { task: TaskAskController provider: ClineProvider } export class API extends EventEmitter implements RooCodeAPI, RooCodeTestOnlyApi { private readonly outputChannel: vscode.OutputChannel private readonly sidebarProvider: ClineProvider private readonly context: vscode.ExtensionContext private readonly ipc?: IpcServer private readonly tasksById = new Map() // Providers whose listeners are already wired (startNewTask is idempotent per provider). private readonly registeredProviders = new WeakSet() private readonly log: (...args: unknown[]) => void private logfile?: string constructor( outputChannel: vscode.OutputChannel, provider: ClineProvider, private readonly providerFactory: ClineProviderFactory, socketPath?: string, enableLogging = false, ) { super() this.outputChannel = outputChannel this.sidebarProvider = provider this.context = provider.context if (enableLogging) { this.log = (...args: unknown[]) => { this.outputChannelLog(...args) console.log(args) } this.logfile = path.join(os.tmpdir(), "roo-code-messages.log") } else { this.log = () => {} } this.registerListeners(this.sidebarProvider) if (socketPath) { const ipc = (this.ipc = new IpcServer(socketPath, this.log)) ipc.listen() this.log(`[API] ipc server started: socketPath=${socketPath}, pid=${process.pid}, ppid=${process.ppid}`) ipc.on(IpcMessageType.TaskCommand, async (clientId, command) => { const sendResponse = (eventName: RooCodeEventName, payload: unknown[]) => { ipc.send(clientId, { type: IpcMessageType.TaskEvent, origin: IpcOrigin.Server, data: { eventName, payload } as TaskEvent, }) } switch (command.commandName) { case TaskCommandName.StartNewTask: { // Neither prompt nor settings values enter the log. this.log("[API] StartNewTask", { promptLength: command.data.text.length, imageCount: command.data.images?.length ?? 0, newTab: command.data.newTab === true, requestId: command.data.requestId, }) const { requestId } = command.data if (requestId === undefined) { // IpcServer does not await async listeners: an uncaught rejection // here would surface as an unhandled rejection in the extension host. try { await this.startNewTask(command.data, { focusSidebar: false }) } catch (error) { this.log( `[API] StartNewTask failed: ${error instanceof Error ? error.message : String(error)}`, ) } break } // Exactly one sanitized, client-scoped response per // correlated start. The reply never echoes the failure. // Await actual startup, including configuration writes. // The smoke controller owns its timeout and terminates // its isolated host; shared-profile writes are not raced. let response: TaskStartResponse try { const taskId = await this.startNewTask(command.data, { focusSidebar: false, }) response = { requestId, success: true, taskId } } catch { this.log("[API] StartNewTask failed", { requestId }) response = { requestId, success: false, errorCode: TASK_START_FAILURE_ERROR_CODE, errorMessage: TASK_START_FAILURE_ERROR_MESSAGE, } } sendResponse(RooCodeEventName.TaskStartResponse, [response]) break } case TaskCommandName.CancelTask: this.log(`[API] CancelTask`) await this.cancelCurrentTask() break case TaskCommandName.CloseTask: this.log(`[API] CloseTask`) await vscode.commands.executeCommand("workbench.action.files.saveFiles") await vscode.commands.executeCommand("workbench.action.closeWindow") break case TaskCommandName.ResumeTask: this.log(`[API] ResumeTask -> ${command.data}`) try { await this.resumeTask(command.data) } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error) this.log(`[API] ResumeTask failed for taskId ${command.data}: ${errorMessage}`) // Don't rethrow - we want to prevent IPC server crashes. // The error is logged for debugging purposes. } break case TaskCommandName.SendMessage: this.log(`[API] SendMessage -> ${command.data.text}`) await this.sendMessage(command.data.text, command.data.images) break case TaskCommandName.GetCommands: try { const commands = await getCommands(this.sidebarProvider.cwd) sendResponse(RooCodeEventName.CommandsResponse, [ commands.map((cmd) => ({ name: cmd.name, source: cmd.source, filePath: cmd.filePath, description: cmd.description, argumentHint: cmd.argumentHint, })), ]) } catch { sendResponse(RooCodeEventName.CommandsResponse, [[]]) } break case TaskCommandName.GetModes: try { const modes = await this.sidebarProvider.getModes() sendResponse(RooCodeEventName.ModesResponse, [modes]) } catch { sendResponse(RooCodeEventName.ModesResponse, [[]]) } break case TaskCommandName.GetModels: try { sendResponse(RooCodeEventName.ModelsResponse, [{}]) } catch { sendResponse(RooCodeEventName.ModelsResponse, [{}]) } break case TaskCommandName.DeleteQueuedMessage: this.log(`[API] DeleteQueuedMessage -> ${command.data}`) try { this.deleteQueuedMessage(command.data) } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error) this.log(`[API] DeleteQueuedMessage failed for messageId ${command.data}: ${errorMessage}`) } break } }) } } public override emit( eventName: K, ...args: K extends keyof RooCodeEvents ? RooCodeEvents[K] : never ) { const data = { eventName: eventName as RooCodeEventName, payload: args } as TaskEvent this.ipc?.broadcast({ type: IpcMessageType.TaskEvent, origin: IpcOrigin.Server, data }) return super.emit(eventName, ...args) } public async startNewTask( { configuration, text, images, newTab, preserveOpenTabs, }: { configuration?: RooCodeSettings text?: string images?: string[] newTab?: boolean preserveOpenTabs?: boolean }, startOptions?: { focusSidebar?: boolean }, ) { let provider: ClineProvider if (newTab) { if (!preserveOpenTabs) { await vscode.commands.executeCommand("workbench.action.files.revert") await vscode.commands.executeCommand("workbench.action.closeAllEditors") } // A fresh tab: reusing the tracked tab would evict the task it is already serving. provider = await createClineTabPanel({ context: this.context, outputChannel: this.outputChannel, webviewFocusTracker: this.sidebarProvider.webviewFocusTracker, }) this.registerListeners(provider) } else { // IPC callers omit focus: executeCommand cannot be cancelled and a // stalled webview launch would block the whole start. if (startOptions?.focusSidebar ?? true) { await vscode.commands.executeCommand(`${Package.name}.SidebarProvider.focus`) } provider = this.sidebarProvider } // A new task must not consume shared default mode/profile state before the view's // stable state id is registered and its persisted view state loaded: webviewDidLaunch // may not have arrived yet. Bound the wait so a view that never launches cannot // hang task creation; if the bound expires, fail task creation rather than start // the task against stale shared defaults. let readinessTimer: ReturnType | undefined try { await Promise.race([ provider.viewStateReadiness, new Promise((_, reject) => { readinessTimer = setTimeout( () => reject(new Error("Timed out waiting for the view state to become ready")), 3000, ) }), ]).finally(() => { clearTimeout(readinessTimer) }) } catch (error) { if ( provider.viewLaunched || !(error instanceof Error) || error.message !== "Timed out waiting for the view state to become ready" ) { throw error } // Headless API callers create tasks without ever launching a webview: the // readiness bound expiring keeps the pre-existing shared-state fallback. // A launched view whose readiness failed is a real failure and rethrows. this.log("[API#startNewTask] webview not launched; continuing in headless mode") } // Disposal resolves viewStateReadiness to release waiters: a provider torn down while // the wait was pending must fail task creation rather than create a task against the // disposed view (its posts and task registration would be orphaned). if (provider.isDisposed) { throw new Error("The provider was disposed while waiting for the view state to become ready") } await provider.evictCurrentTask() await provider.postStateToWebview() await provider.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) await provider.postMessageToWebview({ type: "invoke", invoke: "newChat", text, images }) // API-driven tasks never stop to ask the user, so the hard stop is // effectively unlimited. The soft repetition tier is disabled too: // without a reachable hard stop it would reject every identical call // with no escalation. const options: CreateTaskOptions & { segments?: MentionSegment[] } = { consecutiveMistakeLimit: Number.MAX_SAFE_INTEGER, toolRepetitionSoftLimit: 0, // The API caller authored the task text. segments: userSegments(text ?? ""), } const task = await provider.createTask(text, images, undefined, options, configuration) if (!task) { throw new Error("Failed to create task due to policy restrictions") } return task.taskId } public async resumeTask(taskId: string): Promise { await vscode.commands.executeCommand(`${Package.name}.SidebarProvider.focus`) await this.waitForWebviewLaunch(5_000) const { historyItem } = await this.sidebarProvider.getTaskWithId(taskId) await this.sidebarProvider.createTaskWithHistoryItem(historyItem) if (this.sidebarProvider.viewLaunched) { await this.sidebarProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) } else { this.log( `[API#resumeTask] webview not launched after resume for task ${taskId}; continuing in headless mode`, ) } } public async isTaskInHistory(taskId: string): Promise { try { await this.sidebarProvider.getTaskWithId(taskId) return true } catch { return false } } public async getTaskHistoryItem(taskId: string) { const item = this.sidebarProvider.taskHistoryStore.get(taskId) return item ? structuredClone(item) : undefined } public async getTaskApiConversationHistoryLength(taskId: string): Promise { try { const { apiConversationHistory } = await this.sidebarProvider.getTaskWithId(taskId) return apiConversationHistory.length } catch { return 0 } } /** Checks persisted turn ordering without exposing conversation contents to tests. */ public async hasTaskApiConversationHistorySequence( taskId: string, sequence: TaskApiConversationHistorySequence, ): Promise { let apiConversationHistory: Awaited>["apiConversationHistory"] try { const task = await this.sidebarProvider.getTaskWithId(taskId) apiConversationHistory = task.apiConversationHistory } catch { return false } const userTurnIndex = apiConversationHistory.findIndex( (message) => message.role === "user" && Array.isArray(message.content) && message.content.some((block) => block.type === "text" && block.text.includes(sequence.userText)), ) if (userTurnIndex < 0) return false // Search all assistant turns that belong to the same generation: between // this user turn and the next genuine user text turn (or end of history). // tool_result messages also use role:"user", so we must skip them — // stopping at a tool_result would cut the search short before a later // attempt_completion in the same generation. const nextUserIndex = apiConversationHistory.findIndex( (m, i) => i > userTurnIndex && m.role === "user" && Array.isArray(m.content) && m.content.some((block) => block.type === "text"), ) const generationSlice = apiConversationHistory.slice( userTurnIndex + 1, nextUserIndex < 0 ? undefined : nextUserIndex, ) return generationSlice.some( (message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some( (block) => block.type === "tool_use" && block.name === sequence.assistantToolName && JSON.stringify(block.input).includes(sequence.assistantToolInputText), ), ) } /** Checks persisted ui_messages.json contents without exposing messages to tests. */ public async hasTaskUiMessageText(taskId: string, text: string): Promise { let uiMessages: Awaited> try { // Reject unknown ids first: readTaskMessages creates the task directory. await this.sidebarProvider.getTaskWithId(taskId) uiMessages = await readTaskMessages({ taskId, globalStoragePath: this.sidebarProvider.contextProxy.globalStorageUri.fsPath, }) } catch (error: unknown) { tracePersistenceEvent("ui-messages-marker-check", { taskId, result: "read-error", detail: error instanceof TaskMessagesReadError ? `${error.kind}:${getErrorCode(error.originalError) ?? "unknown"}` : (getErrorCode(error) ?? "unknown"), }) return false } const hasText = uiMessages.some((message) => message.text?.includes(text)) tracePersistenceEvent("ui-messages-marker-check", { taskId, result: hasText ? "match" : "no-match" }) return hasText } public getCurrentTaskStack() { return this.sidebarProvider.getCurrentTaskStack() } public async clearCurrentTask(_lastMessage?: string) { // Legacy finishSubTask removed; clear current by closing active task instance. await this.sidebarProvider.evictCurrentTask() await this.sidebarProvider.postStateToWebview() } public async cancelCurrentTask() { await this.sidebarProvider.cancelTask() } public async abandonSubtask(childTaskId: string): Promise { return this.sidebarProvider.abandonSubtask(childTaskId) } public async sendMessage(text?: string, images?: string[]) { const currentTask = this.sidebarProvider.getCurrentTask() // In headless/sandbox flows the webview may not be launched, so routing // through invoke=sendMessage drops the message. Deliver directly to the // task ask-response channel instead. if (!this.sidebarProvider.viewLaunched) { if (!currentTask) { this.log("[API#sendMessage] no current task in headless mode; message dropped") return } await currentTask.submitUserMessage(text ?? "", images, undefined, undefined, userSegments(text ?? "")) return } await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "sendMessage", text, images, segments: userSegments(text ?? ""), }) } public deleteQueuedMessage(messageId: string) { const currentTask = this.sidebarProvider.getCurrentTask() if (!currentTask) { this.log(`[API#deleteQueuedMessage] no current task; ignoring delete for messageId ${messageId}`) return } currentTask.messageQueueService.removeMessage(messageId) } public async pressPrimaryButton() { await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "primaryButtonClick" }) } public async pressSecondaryButton() { await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "secondaryButtonClick" }) } public async approveCurrentAsk() { this.sidebarProvider.getCurrentTask()?.approveAsk() } /** * The test-only surface (task ask control by ID and raw global-state reads) must not * be reachable from production callers: VS Code only reports ExtensionMode.Production on the extension context for installed extensions, so test hosts and the e2e * harness keep access. */ private assertTestOnlyApi(method: string): void { if (this.context.extensionMode === vscode.ExtensionMode.Production) { throw new Error(`${method} is a test-only API and is unavailable in production mode`) } } /** * Approves the pending ask for a specific task by its ID. * * @returns Whether a registered task with the given ID was found and approved. */ public async approveTaskAsk(taskId: string): Promise { this.assertTestOnlyApi("approveTaskAsk") const entry = this.tasksById.get(taskId) if (!entry) { return false } entry.task.approveAsk() return true } /** * Denies the pending ask for a specific task by its ID. * * @returns Whether a registered task with the given ID was found and denied. */ public async denyTaskAsk(taskId: string): Promise { this.assertTestOnlyApi("denyTaskAsk") const entry = this.tasksById.get(taskId) if (!entry) { return false } entry.task.denyAsk() return true } /** * Answers a task's pending ask with a follow-up suggestion, optionally switching that * task's provider to the suggestion's mode before responding. * * @returns Whether a registered task with the given ID was found and answered. */ public async selectTaskFollowupSuggestion({ taskId, answer, mode, }: { taskId: string answer: string mode?: string }): Promise { this.assertTestOnlyApi("selectTaskFollowupSuggestion") const entry = this.tasksById.get(taskId) if (!entry) { return false } if (mode) { try { const { customModes } = await entry.provider.getState() const isValidMode = getAllModes(customModes).some((modeConfig) => modeConfig.slug === mode) if (isValidMode) { // entry.task is the registered Task instance (TaskAskController narrows it // to the ask-response surface); pass it explicitly so the switch is scoped to // this task rather than the provider's currently focused task. await entry.provider.handleModeSwitch(mode, entry.task as Task) } else { this.log(`[API#selectTaskFollowupSuggestion] ignoring unknown mode "${mode}" for task ${taskId}`) } } catch (error) { // A failed mode switch must not swallow the follow-up answer: the task's // pending ask would otherwise stay unanswered. this.log( `[API#selectTaskFollowupSuggestion] mode switch failed for task ${taskId}: ${error instanceof Error ? error.message : String(error)}`, ) } } // The mode switch above awaits, so the registration can change underneath this call: // the task may have completed and been removed, or a replacement instance may have // taken the id. Answering the captured entry would then report success for a task the // registry no longer maps to that instance. if (this.tasksById.get(taskId) !== entry) { this.log( `[API#selectTaskFollowupSuggestion] task ${taskId} was unregistered or replaced during the mode switch; answer not delivered`, ) return false } entry.task.handleWebviewAskResponse("messageResponse", answer) return true } public isReady() { return this.sidebarProvider.viewLaunched } public captureWebviewThemeFixture(): Promise { return this.sidebarProvider.requestWebviewThemeFixture() } public getLatestAnnouncementId(): string { return this.sidebarProvider.latestAnnouncementId } private async waitForWebviewLaunch(timeoutMs: number): Promise { try { await pWaitFor(() => this.sidebarProvider.viewLaunched, { timeout: timeoutMs, interval: 50, }) return true } catch { this.log(`[API#waitForWebviewLaunch] webview did not launch within ${timeoutMs}ms`) return false } } /** * Removes a task's registration only if the registered entry still belongs to this * task instance: a replaced instance reusing the same taskId must not be dropped by * the previous instance's teardown events. */ private removeRegisteredTask(task: TaskLike): void { const entry = this.tasksById.get(task.taskId) // The stored controller is this exact instance (registered above with a cast to // the ask-response surface), so reference equality is the right identity check. if (entry?.task === (task as unknown as TaskAskController)) { this.tasksById.delete(task.taskId) } } private registerListeners(provider: ClineProvider) { // Idempotent per provider: repeated or concurrent startNewTask calls against a // reused tab provider must not stack duplicate listeners (duplicate API events, // duplicate file logging, and duplicate per-task listener sets). if (this.registeredProviders.has(provider)) { return } provider.on(RooCodeEventName.TaskCompleted, async (taskId, tokenUsage, toolUsage) => { const historyItem = provider.taskHistoryStore.get(taskId) this.emit(RooCodeEventName.TaskCompleted, taskId, tokenUsage, toolUsage, { isSubtask: !!historyItem?.parentTaskId, }) await this.fileLog( `[${new Date().toISOString()}] taskCompleted -> ${taskId} | ${JSON.stringify(tokenUsage, null, 2)} | ${JSON.stringify(toolUsage, null, 2)}\n`, ) }) provider.on(RooCodeEventName.TaskCreated, (task) => { this.tasksById.set(task.taskId, { task: task as unknown as TaskAskController, provider }) // Task Lifecycle task.on(RooCodeEventName.TaskStarted, async () => { this.emit(RooCodeEventName.TaskStarted, task.taskId) await this.fileLog(`[${new Date().toISOString()}] taskStarted -> ${task.taskId}\n`) }) // #1452 moved the TaskCompleted emit and file-log to the provider-level // listener above. This per-task listener remains only for the reference-safe // registry removal: the provider-level handler receives the taskId but not the // task instance, so it cannot verify the entry still belongs to this instance. task.on(RooCodeEventName.TaskCompleted, () => { this.removeRegisteredTask(task) }) task.on(RooCodeEventName.TaskAborted, () => { this.emit(RooCodeEventName.TaskAborted, task.taskId) this.removeRegisteredTask(task) }) task.on(RooCodeEventName.TaskFocused, () => { this.emit(RooCodeEventName.TaskFocused, task.taskId) }) task.on(RooCodeEventName.TaskUnfocused, () => { this.emit(RooCodeEventName.TaskUnfocused, task.taskId) this.removeRegisteredTask(task) }) task.on(RooCodeEventName.TaskActive, () => { this.emit(RooCodeEventName.TaskActive, task.taskId) }) task.on(RooCodeEventName.TaskInteractive, () => { this.emit(RooCodeEventName.TaskInteractive, task.taskId) }) task.on(RooCodeEventName.TaskResumable, () => { this.emit(RooCodeEventName.TaskResumable, task.taskId) }) task.on(RooCodeEventName.TaskIdle, () => { this.emit(RooCodeEventName.TaskIdle, task.taskId) }) // Subtask Lifecycle task.on(RooCodeEventName.TaskPaused, () => { this.emit(RooCodeEventName.TaskPaused, task.taskId) }) task.on(RooCodeEventName.TaskUnpaused, () => { this.emit(RooCodeEventName.TaskUnpaused, task.taskId) }) task.on(RooCodeEventName.TaskSpawned, (childTaskId) => { this.emit(RooCodeEventName.TaskSpawned, task.taskId, childTaskId) }) task.on(RooCodeEventName.TaskDelegated, (childTaskId: string) => { this.emit(RooCodeEventName.TaskDelegated, task.taskId, childTaskId) }) task.on(RooCodeEventName.TaskDelegationCompleted, (childTaskId: string, summary: string) => { this.emit(RooCodeEventName.TaskDelegationCompleted, task.taskId, childTaskId, summary) }) task.on(RooCodeEventName.TaskDelegationResumed, (childTaskId: string) => { this.emit(RooCodeEventName.TaskDelegationResumed, task.taskId, childTaskId) }) // Task Execution task.on(RooCodeEventName.Message, async (message) => { this.emit(RooCodeEventName.Message, { taskId: task.taskId, ...message }) if (message.message.partial !== true) { await this.fileLog(`[${new Date().toISOString()}] ${JSON.stringify(message.message, null, 2)}\n`) } }) task.on(RooCodeEventName.TaskModeSwitched, (taskId, mode) => { this.emit(RooCodeEventName.TaskModeSwitched, taskId, mode) }) task.on(RooCodeEventName.TaskAskResponded, () => { this.emit(RooCodeEventName.TaskAskResponded, task.taskId) }) task.on(RooCodeEventName.QueuedMessagesUpdated, (taskId, messages) => { this.emit(RooCodeEventName.QueuedMessagesUpdated, taskId, messages) }) // Task Analytics task.on(RooCodeEventName.TaskToolFailed, (taskId, tool, error) => { this.emit(RooCodeEventName.TaskToolFailed, taskId, tool, error) }) task.on(RooCodeEventName.TaskTokenUsageUpdated, (_, tokenUsage, toolUsage) => { this.emit(RooCodeEventName.TaskTokenUsageUpdated, task.taskId, tokenUsage, toolUsage) }) // Let's go! this.emit(RooCodeEventName.TaskCreated, task.taskId) }) // Delegation events are emitted by the provider, not by individual task instances. provider.on(RooCodeEventName.TaskDelegated, (parentTaskId, childTaskId) => { this.emit(RooCodeEventName.TaskDelegated, parentTaskId, childTaskId) }) provider.on(RooCodeEventName.TaskDelegationCompleted, (parentTaskId, childTaskId, summary) => { this.emit(RooCodeEventName.TaskDelegationCompleted, parentTaskId, childTaskId, summary) }) provider.on(RooCodeEventName.TaskDelegationResumed, (parentTaskId, childTaskId) => { this.emit(RooCodeEventName.TaskDelegationResumed, parentTaskId, childTaskId) }) this.registeredProviders.add(provider) } // Logging private outputChannelLog(...args: unknown[]) { for (const arg of args) { if (arg === null) { this.outputChannel.appendLine("null") } else if (arg === undefined) { this.outputChannel.appendLine("undefined") } else if (typeof arg === "string") { this.outputChannel.appendLine(arg) } else if (arg instanceof Error) { this.outputChannel.appendLine(`Error: ${arg.message}\n${arg.stack || ""}`) } else { try { this.outputChannel.appendLine( JSON.stringify( arg, (_key, value) => { if (typeof value === "bigint") return `BigInt(${value})` if (typeof value === "function") return `Function: ${value.name || "anonymous"}` if (typeof value === "symbol") return value.toString() return value }, 2, ), ) } catch { this.outputChannel.appendLine(`[Non-serializable object: ${Object.prototype.toString.call(arg)}]`) } } } } private async fileLog(message: string) { if (!this.logfile) { return } try { await fs.appendFile(this.logfile, message, "utf8") } catch (_) { this.logfile = undefined } } // Global Settings Management public getConfiguration(): RooCodeSettings { // getValues() merges view-local state, whose apiConfiguration is a nested object that // can carry provider secrets (e.g. apiKey). Flatten the provider settings onto the top // level (the pre-existing flat shape) so the secret filter removes them before return. const values = this.sidebarProvider.getValues() // viewStates is per-view durable state owned by the extension host: exposing it on // the flat configuration surface invites a caller to write a stale snapshot // back and clobber newer per-view selections, so it never leaves here. const { apiConfiguration, viewStates: _viewStates, ...rest } = values // A view-local profile is a complete snapshot, not a patch over the shared // store - getState() resolves it the same way. Drop the shared flat // provider-settings keys before flattening, or a key the view's profile // never defined (e.g. another profile's apiModelId or base URL) leaks in // from whichever profile owns the shared store. The shared apiProvider is // the one exception: getState() falls back to it when a pinned profile // carries no provider of its own, so keep that single key as a base the // profile's own apiProvider (when present) still overrides. const shared = apiConfiguration ? Object.fromEntries( Object.entries(rest).filter( ([key]) => key === "apiProvider" || !PROVIDER_SETTINGS_KEYS.some((k) => k === key), ), ) : rest // Secrets never leave the flattened surface: SECRET_STATE_KEYS covers the // *ApiKey shapes, and SENSITIVE_PROVIDER_CONFIG_KEYS covers credential // values that use other name shapes (header maps, session tokens, // service-account JSON, credential-file paths). // Retired providers keep their legacy fields through passthrough, and those // names (e.g. groqApiKey, huggingFaceSecurityToken) predate the explicit // secret lists and appear in neither. Treat credential-shaped key names as // secret on this flattened surface so a retired profile cannot expose them. const legacyCredentialKeyRe = /(?:ApiKey|ApiToken|SecurityToken|AccessToken|SessionToken|Credentials|Secret)$/ const configuration = Object.fromEntries( Object.entries({ ...shared, ...apiConfiguration }).filter( ([key]) => !isSecretStateKey(key) && !isSensitiveProviderConfigKey(key) && !legacyCredentialKeyRe.test(key), ), ) // An explicit apiProvider: undefined inside the nested profile clobbers the // retained shared fallback through the spread above; restore it the same way // getState() does with ?? so the provider never disappears from the result. if (configuration.apiProvider === undefined && shared.apiProvider !== undefined) { configuration.apiProvider = shared.apiProvider } return configuration } /** * Stores the settings, then the API profile and the mode profiles. The settings are written with * `ContextProxy.setValues`, which is not a transaction (see there): if a setting cannot be stored, * this rejects with a `SettingsWriteError` that lists the keys that were stored and the keys that * were not (the cache of the failed keys has been read back from storage), the stored settings * stay, and nothing after the settings is written. Invalid values of the display settings are * dropped and logged first. * * The profile writes that follow the settings are wrapped by this unit. The existence check, the * prior-record read and the save run inside the manager cross-instance critical section, while the * prior mode-mapping read runs just before that section so a failed read aborts the call with * nothing mutated, and the * compensation runs in its own section after re-reading the record, so a record another view * created is never deleted by this call rollback and a record another view rewrote is never restored * over: each branch re-reads the layer it writes and acts only while the stored value still equals * the one this call wrote (compare-and-set, step 1 of issue 2488), and a re-read that fails leaves * that key exactly as it stands. On failure the call restores the prior record, * the prior shared settings, the prior shared mode and profile pin, and the prior mapping of every * mode the payload touched, then replays only the settings keys this call itself wrote, taken from * the snapshot it captured; the replay is best effort - a restore that itself fails is logged * with the failing key and swallowed, so a rollback can leave some keys restored and others * not - and the original error is rethrown. */ public async setConfiguration(allValues: RooCodeSettings) { const values = withoutInvalidDisplaySettings(allValues, (key) => this.sidebarProvider.log(`[setConfiguration] Ignored an invalid value for ${key}`), ) // Derive the saved profile name once so the sibling refresh and the save // agree on the empty-string fallback. const savedProfileName = values.currentApiConfigName || "default" const manager = this.sidebarProvider.providerSettingsManager // The payload may carry machine-local state this call does not own (the host-owned viewStates // map above all): the forward write and the rollback below both filter it out, using the same // list the export schema and the import path consult (NON_PORTABLE_SETTINGS_KEYS). const forwardValues: RooCodeSettings = Object.fromEntries( Object.entries(values).filter(([key]) => !isNonPortableSettingsKey(key)), ) // The getter map carries viewStates: a snapshot of every view selection as of now. The rollback // below replays the snapshot through setValues, which would pin every other view back to where // this call found them, so the host-owned key is dropped here as well. const snapshotValues: RooCodeSettings = Object.fromEntries( Object.entries(this.getConfiguration()).filter(([key]) => !isNonPortableSettingsKey(key)), ) const previousSharedSettings = this.sidebarProvider.contextProxy.getProviderSettings() // The snapshot above is the filtered getter map: it drops every secret-shaped key and every // sensitive provider key, so it cannot hold the prior value of exactly the keys a settings // payload most often carries - apiKey, vertexKeyFile, openAiHeaders. Read each key this // call is about to write through a sensitive-aware reader before the write and keep those // reads: the shared provider-settings reader owns the profile-shaped keys, and the per-key // reader sees the secret cache and the flat sensitive values the getter surface hides. // The replay below takes the snapshot where the snapshot holds the key and this capture // everywhere the snapshot is blind, so a stored value is never written back as undefined // just because the getter map filtered the key out. const priorWrittenValues = new Map() for (const key of Object.keys(forwardValues)) { if (key in previousSharedSettings) { priorWrittenValues.set( key, previousSharedSettings[ key as keyof typeof previousSharedSettings ] as RooCodeSettings[keyof RooCodeSettings], ) continue } const priorValue = this.sidebarProvider.contextProxy.getValue(key as keyof RooCodeSettings) if (priorValue !== undefined) { priorWrittenValues.set(key, priorValue as RooCodeSettings[keyof RooCodeSettings]) } } // getConfiguration() folds this view overlay into the merged copy, so its mode and profile pin // are this view values rather than the shared ones. Snapshot the shared pair here: the rollback // below replays the merged copy through setValues, which writes both keys to shared global // state, and without this snapshot a failed call would leave every other unpinned view on this // view mode and profile. const previousSharedMode = this.sidebarProvider.contextProxy.getValue("mode") const previousSharedProfileName = this.sidebarProvider.contextProxy.getValue("currentApiConfigName") // Capture the prior mapping of every mode this payload touches, so a partial mode fan-out rolls // back completely - including mappings this call creates for the first time (an undefined prior // id restores the no-mapping semantics getModeConfigId reports) - and so that this read joins the // fail-closed reads below: a rejection here aborts the call before the profile record is created // or overwritten, which is the state the compensation cannot reconstruct. Held outside the // critical section on purpose - it lengthens no cross-instance hold, and the mode writes it // guards happen after the section anyway. const previousModeConfigs: Array<[Mode, string | undefined]> = [] // The provider-level write below lands in the provider's window-local map as well, // and that map out-ranks the shared mapping in getModeConfigId: snapshot it per mode // (undefined = the window had no entry) so compensation can put both layers back // instead of rewinding the local entry to a shared-store value it never held. const previousLocalModeConfigs = new Map() if (values.modeApiConfigs) { for (const mode of Object.keys(values.modeApiConfigs)) { previousModeConfigs.push([mode as Mode, await manager.getModeConfigId(mode as Mode)]) previousLocalModeConfigs.set(mode, this.sidebarProvider.getLocalModeConfigId(mode as Mode)) } } // The existence check, the prior-record read and the save run as one critical section of the // manager cross-instance lock - the same lock the profile rename, the persist path and the // handler deletions already join. Left unserialised the sequence is: we read the name as absent, // another view creates it through a locked writer, one of our own writes fails, and our rollback // deletes that view record together with its secrets. Nothing inside this section joins the // queue again: hasConfig, getProfile and saveConfig take only the per-instance lock, which is // the inner one, so the section cannot deadlock against itself. // The queue is a static in-memory map: it orders cooperating managers inside one extension // host and does not order a writer in another host. A cross-host compare-and-write needs a // shared lock or an atomic store operation, which this store does not have. // Existence comes from the store rather than the cached profile list: a stale list could hide an // existing record and let rollback delete it. A failed existence read is treated as "may exist" // so rollback never deletes blindly, and the prior-record read still fails closed before // anything is mutated. const { recordExisted, previousRecord, savedId, writtenSettings } = await manager.runExclusiveAcrossInstances( async () => { let existed: boolean try { existed = await manager.hasConfig(savedProfileName) } catch { existed = true } const priorRecord = existed ? await manager.getProfile({ name: savedProfileName }) : undefined // saveConfig validates before storing, so a rejected save leaves every domain // untouched and the call fails with nothing to roll back. The record takes the same // filtered payload as the shared write: a caller may hand this call a stale viewStates // snapshot (a map of every other view's selection), and storing it in a profile record // would pin those views to the snapshot the moment the record is re-applied. const id = await manager.saveConfig(savedProfileName, forwardValues) // Ownership base for both compensation branches: the value this call wrote, read back from // the layer it wrote while this section still holds it. The prior record is the value a restore // writes, not the value that says whether this call still owns the name - our own save is what // moved it - and saveConfig normalises the payload (a legacy downgrade plus a schema parse), // so comparing the compensation re-read against the caller object would compare two different // shapes and report a competing write that never happened. A failed read-back leaves ownership // unconfirmed, and an unconfirmed key is neither restored nor deleted. let writtenSettings: ProviderSettings | undefined try { const { name: _writtenName, id: _writtenId, ...writtenRecord } = await manager.getProfile({ name: savedProfileName }) writtenSettings = writtenRecord } catch { writtenSettings = undefined } return { recordExisted: existed, previousRecord: priorRecord, savedId: id, writtenSettings } }, ) try { await this.sidebarProvider.setValues( // Only the keys this call owns travel forward; see the filter comment above. forwardValues, { savedProfileName }, ) if (values.modeApiConfigs) { await Promise.all( Object.entries(values.modeApiConfigs).map(([mode, configId]) => this.sidebarProvider.setModeConfig(mode as Mode, configId), ), ) } } catch (error) { // The save landed: roll back every domain this mutation touched - the // profile record, the sibling overlays pinned to it, the complete // settings round trip (global values, view-local state, and sibling // overlays), the shared provider settings, and the mode mappings. // Each restore is independent and logged; the original failure is // what the caller sees. let previousSettings: ProviderSettings | undefined if (previousRecord) { const { name: _previousName, id: _previousId, ...rest } = previousRecord previousSettings = rest } // Compare-and-set restore (rule R3 of issue 2488, step 1). Both branches re-read the layer they // are about to write and act only while the stored value still equals the value this call wrote, // read back from that same layer in the section above. The comparison is the one the manager // itself uses to decide whether a profile changed - deepEqual from fast-deep-equal over records, // plain equality over ids - rather than a hand-rolled one. When the value moved under us the key is skipped, every other compensation // still runs, and the skip is logged with the profile name. A re-read that fails is // unconfirmed: the key keeps whatever it holds and nothing is written over it, neither the // prior record nor a delete. Value equality cannot separate two writes of the same value (rule // R5): a second view that rewrote this profile with an identical value has its write cleared // here, which is harmless because the surviving value is the value this call would have // restored anyway; record-level write revision - step 2 of the same issue - is what tells the // two writes apart. let survivingRecordSettings: ProviderSettings | undefined let recordStateConfirmed = true // Both branches read through this helper so a failed read is reported once, with the key it // concerns, instead of throwing out of the section and losing the compare. const readSurvivingRecord = async (onFailure: (error: unknown) => void) => { try { const { name: _readName, ...surviving } = await manager.getProfile({ name: savedProfileName }) return surviving } catch (readError) { onFailure(readError) return undefined } } // A compensation write that fails does not report what it left behind: the restore save may have // rejected before storing anything, and a delete may have rejected with the record still in the // store. Inferring the outcome from the read taken before the write - or from the value the write // meant to store - is the blind write the compare-and-set above exists to prevent, one step further // on: it would replay the prior record, or an empty overlay, to every sibling pinned to a profile // the store has not changed, or no longer holds. So the record is read again and the outcome // follows what the store holds now: its settings while it survives, an empty overlay when it is // confirmed gone, and nothing at all when this confirmation cannot read it either (rule R3 of the // write-ownership issue: an unconfirmed record gets no write, neither a restore nor a refresh of // the overlays pinned to it). The write is already logged; this only decides what follows it. const confirmRecordOutcomeAfterFailedCompensation = async (failure: unknown): Promise => { let exists: boolean try { exists = await manager.hasConfig(savedProfileName) } catch (probeError) { recordStateConfirmed = false this.log( "[setConfiguration] left the overlays pinned to '" + savedProfileName + "' alone: the compensation write failed and the record existence could not be confirmed (" + (probeError instanceof Error ? probeError.message : String(probeError)) + ").", ) return } if (!exists) { survivingRecordSettings = {} this.log( "[setConfiguration] confirmed the profile record '" + savedProfileName + "' is gone after the failed compensation write, so the overlays pinned to it are refreshed from an empty profile (" + (failure instanceof Error ? failure.message : String(failure)) + ").", ) return } const reread = await readSurvivingRecord((readError) => { recordStateConfirmed = false this.log( "[setConfiguration] left the overlays pinned to '" + savedProfileName + "' alone: the compensation write failed and the record could not be read afterwards (" + (readError instanceof Error ? readError.message : String(readError)) + ").", ) }) if (!reread) { return } const { id: _confirmedId, ...confirmedSettings } = reread survivingRecordSettings = confirmedSettings this.log( "[setConfiguration] confirmed the profile record '" + savedProfileName + "' after the failed compensation write: the overlays pinned to it are refreshed from what the store holds now, not from the value the failed write meant to store (" + (failure instanceof Error ? failure.message : String(failure)) + ").", ) } try { await manager.runExclusiveAcrossInstances(async () => { if (recordExisted && previousSettings) { const surviving = await readSurvivingRecord((readError) => { recordStateConfirmed = false this.log( "[setConfiguration] left the profile record '" + savedProfileName + "' unrestored: its current value could not be read, so this call does not " + "write over it (" + (readError instanceof Error ? readError.message : String(readError)) + ").", ) }) if (!surviving) { return } const { id: _survivingId, ...survivingSettings } = surviving // The base is the record this call saved, not the record it found: our own save is what moved // the value, so any other value in the store belongs to a writer this call does not own. // It cannot tell "nothing wrote while I was away" from "another view wrote exactly the same values": // both leave the store equal to what this call wrote, so an identical-value re-save is restored over. // Telling the two readings apart needs a write revision, which #2488 tracks as step 2 and has not // decided in code; until it is decided the identical-value case is pinned in // api-configuration.spec.ts rather than assumed harmless. if (writtenSettings === undefined || !deepEqual(survivingSettings, writtenSettings)) { if (writtenSettings === undefined) { recordStateConfirmed = false } else { survivingRecordSettings = survivingSettings } this.log( "[setConfiguration] skipped restoring the profile record '" + savedProfileName + "': " + (writtenSettings === undefined ? "the value this call wrote could not be read back, so the restore is unconfirmed" : "another view rewrote it under this call (id '" + surviving.id + "', this call wrote '" + savedId + "')") + ", so the surviving value is kept.", ) return } await manager.saveConfig(savedProfileName, previousSettings) return } // This call created the name. A locked writer may have replaced the record between the // section above and this one, so re-read before deleting: only the record our own save // wrote is ours to remove, and the id that save returned identifies it. if (!(await manager.hasConfig(savedProfileName))) { return } const surviving = await readSurvivingRecord((readError) => { recordStateConfirmed = false this.log( "[setConfiguration] left the profile record '" + savedProfileName + "' undeleted: its current value could not be read, so this call does not delete " + "blind (" + (readError instanceof Error ? readError.message : String(readError)) + ").", ) }) if (!surviving) { return } if (surviving.id !== savedId) { const { id: _keptId, ...keptSettings } = surviving survivingRecordSettings = keptSettings this.log( `[setConfiguration] kept the profile record '${savedProfileName}': another view wrote ` + `it (id '${surviving.id}', this call wrote '${savedId}').`, ) return } // A view that saves the same profile keeps its id - saveConfig preserves it - so the id // alone does not prove this call still owns the record. Compare what the store holds // against the values our own save wrote, read back from the store above. // Same limit as the restore branch: a re-save with identical values passes both checks, so the delete // stands until #2488 decides the write-revision ownership that case needs. The rows named above are // the pins for those cases. const { id: _ownId, ...ownSettings } = surviving if (writtenSettings === undefined || !deepEqual(ownSettings, writtenSettings)) { if (writtenSettings === undefined) { recordStateConfirmed = false } else { survivingRecordSettings = ownSettings } this.log( "[setConfiguration] skipped deleting the profile record '" + savedProfileName + "': " + (writtenSettings === undefined ? "the value this call wrote could not be read back, so the delete is " + "unconfirmed" : "another view rewrote it under this call with the same id '" + savedId + "'") + ", so the surviving value is kept.", ) return } await manager.deleteConfig(savedProfileName) }) } catch (restoreError) { this.log( `[setConfiguration] failed to restore the profile record '${savedProfileName}': ` + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) // The outcome of that write is unknown, not the prior record and not an absent profile. Confirm it // from the store before the overlay replay below decides what to send the siblings pinned to this // profile; a confirmation that itself cannot read leaves the replay skipped. if (recordStateConfirmed) { await confirmRecordOutcomeAfterFailedCompensation(restoreError) } } // A rollback may restore only what this call wrote, taken from the snapshot it captured. // Every key this call wrote is replayed, including one the snapshot did not hold: replaying // only the keys the snapshot held left such a key holding what this call wrote, a profile pin // to the record the compensation had just deleted being the clearest case. Anything the // snapshot holds that this call did not write belongs to a writer that has moved on since // then, so replaying it would roll another view change back into this one. That subsumes the // host-owned viewStates map and the pass-through taskHistory key: neither is replayed unless // this call own payload carried it. const writtenKeys = Object.keys(forwardValues) const replayValues = Object.fromEntries( writtenKeys.map((key) => [ key, key in snapshotValues ? snapshotValues[key as keyof RooCodeSettings] : priorWrittenValues.get(key), ]), ) as RooCodeSettings // Which profile the views return to is read from the snapshot, not from the replay // filter: a payload that never wrote currentApiConfigName leaves the pin out of the // replay, and defaulting it here would refresh the overlays pinned to "default" with // this profile settings and skip the credential replay for the profile that was // actually active. When the payload did write the pin the two readings are the same // value, because the replay holds the snapshot value for every key it carries. const previousProfileName = snapshotValues.currentApiConfigName || "default" // The configuration restore drives a sibling refresh of its own: production setValues refreshes the // overlays pinned to the profile the payload names from the provider keys the replay carries, and a // rollback replay often carries only a key whose snapshot value is undefined, which filters down to an // empty object - enough to strip the credentials a sibling already holds. That refresh is safe only // because the record replay below follows it with the record real settings. When the record outcome is // unconfirmed nothing follows it, so the restore must not refresh: omitting the saved profile name // pins those siblings to the overlay they already hold instead of overwriting it with an empty one. try { await this.sidebarProvider.setValues( replayValues, recordStateConfirmed ? { savedProfileName: previousProfileName } : undefined, ) } catch (restoreError) { this.log( "[setConfiguration] failed to restore the previous configuration values: " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } // The merged replay above wrote this view's mode and pin into shared state, which // belongs to every unpinned view: put the shared pair back from the pre-write snapshot. // This touches the shared store only - this view's own overlay keeps the same pair the // replay just wrote there, so nothing about this view changes. try { await this.sidebarProvider.contextProxy.setValues({ mode: previousSharedMode, currentApiConfigName: previousSharedProfileName, }) } catch (restoreError) { this.log( "[setConfiguration] failed to restore the shared mode and profile pin: " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } // Replay the restored record to the sibling overlays pinned to the // saved profile AFTER the configuration restore: when the saved profile // is also the active profile, the restore above refreshes the same // siblings with non-secret values, and this replay must be the last // refresh so the overlays end on the restored record's settings. An // absent prior profile restores an empty overlay. // // What counts as the record's settings now follows the ownership decision above rather than // the pre-write snapshot alone: when another view owns the surviving record this call has no // claim on it, and replaying this call view of the profile would overwrite the newer record - // for a profile this call created, that view is an empty overlay, which strips the newer // record credentials from every sibling pinned to it. So the replay carries the values the // store holds now when ownership moved, the prior record when this call still owns the // rollback, and an empty overlay when the record is gone. When the re-read failed nothing is // replayed at all, and the configuration restore above is told not to refresh them either, so they keep // what they hold - the same rule the record compensation follows for an unconfirmed read. const overlaySettingsForSavedProfile: ProviderSettings | undefined = recordStateConfirmed ? (survivingRecordSettings ?? previousSettings ?? {}) : undefined if (overlaySettingsForSavedProfile) { try { await this.sidebarProvider.refreshViewLocalStateForUpdatedProfile( savedProfileName, overlaySettingsForSavedProfile, ) } catch (restoreError) { this.log( "[setConfiguration] failed to refresh the overlays pinned to '" + savedProfileName + "': " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } } else { this.log( "[setConfiguration] skipped refreshing the overlays pinned to '" + savedProfileName + "': the record compensation could not read its current value, so this call left " + "those overlays as they are.", ) } // When the mutation switched profiles, the configuration restore above // refreshed siblings pinned to the previous profile from non-secret // values; replay that profile's complete stored record so those // overlays keep their credentials. A previous profile that cannot be // read keeps the restore's non-secret refresh. if (previousProfileName !== savedProfileName) { try { const previousProfileRecord = await manager.getProfile({ name: previousProfileName }) const { name: _ppName, id: _ppId, ...previousProfileSettings } = previousProfileRecord await this.sidebarProvider.refreshViewLocalStateForUpdatedProfile( previousProfileName, previousProfileSettings, ) } catch (restoreError) { this.log( "[setConfiguration] failed to refresh the overlays pinned to '" + previousProfileName + "': " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } } try { await this.sidebarProvider.contextProxy.setProviderSettings(previousSharedSettings) } catch (restoreError) { this.log( "[setConfiguration] failed to restore the shared provider settings: " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } try { // The forward fan-out went through the provider wrapper, which records the id in this // window local mode mapping next to the store write, so the rollback restores both // layers, each from its own snapshot: the store from previousModeConfigs (read off the // manager) and this window entry from previousLocalModeConfigs. Absence is restored by // dropping the local entry, which is how getModeConfigId returns to the opening // snapshot: an entry kept here would out-rank the shared mapping this leg restores. // The two differ whenever this window chose a profile the shared store did not hold, and // rewinding the local entry to the store value would leave the mode resolving through an // id this window never picked. A defined prior mapping travels through the wrapper for // that reason; an absent prior mapping keeps the manager write, the only one that accepts // an undefined clear. The local layer is restored in both shapes, including dropping the // entry a failed write created for a mode this window had not mapped. await Promise.all( previousModeConfigs.map(async ([mode, configId]) => { if (configId === undefined) { await manager.setModeConfig(mode, undefined) } else { await this.sidebarProvider.setModeConfig(mode, configId) } this.sidebarProvider.restoreLocalModeConfig(mode, previousLocalModeConfigs.get(mode)) }), ) } catch (restoreError) { this.log( "[setConfiguration] failed to restore the mode API config mappings: " + (restoreError instanceof Error ? restoreError.message : String(restoreError)), ) } throw error } await this.sidebarProvider.postStateToWebview() } public getGlobalState(key: K): GlobalState[K] { this.assertTestOnlyApi("getGlobalState") // The generic only constrains typed callers; a crafted runtime key can be any // string. Credential-bearing keys are refused first: they may not even be part // of the current settings schema, and the test-only API must never read them. if (isSecretStateKey(String(key)) || isSensitiveProviderConfigKey(String(key))) { throw new Error(`getGlobalState received a credential-bearing key: ${String(key)}`) } // Refuse keys outside the settings schema before storage sees them, so the // test-only API cannot read arbitrary global state. if (!isGlobalStateKey(key)) { throw new Error(`getGlobalState received a key outside the settings schema: ${String(key)}`) } // Task history carries user PII (task texts): out of bounds for this surface // even though it is a plain GlobalState key. if (key === "taskHistory") { throw new Error(`getGlobalState received a PII-bearing key: ${String(key)}`) } return this.context.globalState.get(key) } public async setGlobalState(key: K, value: GlobalState[K]): Promise { this.assertTestOnlyApi("setGlobalState") // Same runtime boundary as getGlobalState: an unvalidated key must not be // persisted into global state. if (isSecretStateKey(String(key)) || isSensitiveProviderConfigKey(String(key))) { throw new Error(`setGlobalState received a credential-bearing key: ${String(key)}`) } // Same credential boundary as getGlobalState: a crafted runtime key must not // be able to persist secrets through the test-only surface. if (!isGlobalStateKey(key)) { throw new Error(`setGlobalState received a key outside the settings schema: ${String(key)}`) } // Task history carries user PII (task texts): out of bounds for this surface // even though it is a plain GlobalState key. if (key === "taskHistory") { throw new Error(`setGlobalState received a PII-bearing key: ${String(key)}`) } // The value is runtime data: parse it against the key's schema so malformed // state never reaches durable storage. Keys without a global-settings schema // entry (provider settings) are not seedable through this surface. const valueSchema = ( globalSettingsSchema.shape as Record< string, { safeParse: (value: unknown) => { success: boolean; data: unknown } } | undefined > )[String(key)] if (!valueSchema) { throw new Error(`setGlobalState received a key without a value schema: ${String(key)}`) } const parsedValue = valueSchema.safeParse(value) if (!parsedValue.success) { throw new Error(`setGlobalState received an invalid value for key: ${String(key)}`) } // Persist the parsed value: the object schemas in the settings map are // non-strict, so the raw payload can carry extra credential- or PII-shaped // fields that the schema strips; storing parsed data keeps unknown fields // out of durable global state. await this.context.globalState.update(key, parsedValue.data as GlobalState[K]) } public setTerminalProfile(name: string | undefined): void { const previousProfile = Terminal.getTerminalProfile() Terminal.setTerminalProfile(name) if (Terminal.getTerminalProfile() !== previousProfile) { TerminalRegistry.closeIdleTerminals() } } // Provider Profile Management public getProfiles(): string[] { return this.sidebarProvider.getProviderProfileEntries().map(({ name }) => name) } public getProfileEntry(name: string): ProviderSettingsEntry | undefined { return this.sidebarProvider.getProviderProfileEntry(name) } public async createProfile(name: string, profile?: ProviderSettings, activate: boolean = true) { const entry = this.getProfileEntry(name) if (entry) { throw new Error(`Profile with name "${name}" already exists`) } const id = await this.sidebarProvider.upsertProviderProfile(name, profile ?? {}, activate) if (!id) { throw new Error(`Failed to create profile with name "${name}"`) } return id } public async updateProfile( name: string, profile: ProviderSettings, activate: boolean = true, ): Promise { const entry = this.getProfileEntry(name) if (!entry) { throw new Error(`Profile with name "${name}" does not exist`) } const id = await this.sidebarProvider.upsertProviderProfile(name, profile, activate) if (!id) { throw new Error(`Failed to update profile with name "${name}"`) } return id } public async upsertProfile( name: string, profile: ProviderSettings, activate: boolean = true, ): Promise { const id = await this.sidebarProvider.upsertProviderProfile(name, profile, activate) if (!id) { throw new Error(`Failed to upsert profile with name "${name}"`) } return id } public async deleteProfile(name: string): Promise { const entry = this.getProfileEntry(name) if (!entry) { throw new Error(`Profile with name "${name}" does not exist`) } await this.sidebarProvider.deleteProviderProfile(entry) } public getActiveProfile(): string | undefined { return this.getConfiguration().currentApiConfigName } public async setActiveProfile(name: string): Promise { const entry = this.getProfileEntry(name) if (!entry) { throw new Error(`Profile with name "${name}" does not exist`) } await this.sidebarProvider.activateProviderProfile({ name }) return this.getActiveProfile() } }