Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* Marks a {@link ToolConfirmKind.ConfirmationNotNeeded} decision that came from the session
* auto-approving everything, rather than a per-tool setting or an explicit user action. Shared so
* `shouldAutoConfirm`, the Autopilot risk gate, and approval telemetry use the same string.
*/
const
=
'auto-approve-all'
;
// This tool will always require user confirmation even in auto approval mode.
// Users cannot auto approve this tool via settings either, as this is a tool used before the agentic loop.
const
=
new
Set
(
[
'vscode_get_confirmation_with_options'
,
'vscode_get_modified_files_confirmation'
,
]
)
;
// Fetch uses two tools: the model-facing 'copilot_fetchWebPage' and the internal
// 'vscode_fetchWebPage_internal' it delegates to. Both auto-approve themselves, so the Autopilot
// risk gate classifies them to catch dangerous fetches (leaking secrets to an attacker URL,
'Global auto approve also known as "YOLO mode" disables manual approval completely for _all tools in all workspaces_, allowing the agent to act fully autonomously. This is extremely dangerous and is *never* recommended, even containerized environments like [Codespaces](https://github.com/features/codespaces) and [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) have user keys forwarded into the container that could be compromised.\n\n**This feature disables [critical security protections](https://code.visualstudio.com/docs/agents/run/security) and makes it much easier for an attacker to compromise the machine.**\n\nNote: This setting only controls tool approval and does not prevent the agent from asking questions. To automatically answer agent questions, use the [`chat.autoReply`](command:workbench.action.openSettings?%5B%22chat.autoReply%22%5D) setting.'
/** Throttle tools updates because it sends all tools and runs on context key updates */
private
readonly
=
this
.
_register
(
new
RunOnceScheduler
(
(
)
=>
this
.
.
fire
(
)
,
750
)
)
;
private
readonly
=
new
Map<string, IToolEntry>
(
)
;
private
readonly
=
new
Set<string>
(
)
;
private
readonly
:
<
number
>
;
private
readonly
=
new
Map<string, ITrackedCall[]>
(
)
;
/** Pending tool calls in the streaming phase, keyed by toolCallId */
private
readonly
=
new
Map<string, ChatToolInvocation>
(
)
;
/** Deduplicates _checkGlobalAutoApprove calls within this window */
private
:
Promise
<
boolean
>
|
undefined
;
private
readonly
:
<
boolean
>
;
constructor
(
@IInstantiationService
private
readonly
:
,
@IExtensionService
private
readonly
:
,
@IContextKeyService
private
readonly
:
,
@IChatService
private
readonly
:
,
@IDialogService
private
readonly
:
,
@ITelemetryService
private
readonly
:
,
@ILogService
private
readonly
:
,
@IConfigurationService
private
readonly
:
,
@IAccessibilityService
private
readonly
:
,
@IAccessibilitySignalService
private
readonly
:
,
@IStorageService
private
readonly
:
,
@ILanguageModelToolsConfirmationService
private
readonly
:
,
@ICommandService
private
readonly
:
,
@IChatWidgetService
private
readonly
:
,
@IToolResultCompressor
private
readonly
:
,
@IChatToolRiskAssessmentService
private
readonly
:
,
)
{
super
(
)
;
this
.
=
observableConfigValue
(
.
,
true
,
this
.
)
;
this
.
_register
(
this
.
.
onDidChangeContext
(
=>
{
if
(
.
affectsSome
(
this
.
)
)
{
// Not worth it to compute a delta here unless we have many tools changing often
this
.
.
schedule
(
)
;
}
}
)
)
;
this
.
_register
(
this
.
.
onDidChangeConfiguration
(
=>
{
if
(
.
affectsConfiguration
(
.
)
||
.
affectsConfiguration
(
.
)
||
.
affectsConfiguration
(
.
)
)
{
this
.
.
schedule
(
)
;
}
}
)
)
;
// Clear out warning accepted state if the setting is disabled
this
.
_register
(
.
runAndSubscribe
(
this
.
.
,
=>
{
if
(
!
||
.
affectsConfiguration
(
.
)
)
{
if
(
this
.
.
getValue
(
.
)
!==
true
)
{
this
.
.
remove
(
.
,
.
APPLICATION
)
;
}
}
}
)
)
;
this
.
=
.
.
.
bindTo
(
)
;
// Create the internal VS Code tool set
this
.
=
this
.
_register
(
this
.
createToolSet
(
.
,
'vscode'
,
.
,
{
:
.
fromId
(
.
.
)
,
:
localize
(
'copilot.toolSet.vscode.description'
,
'Use VS Code features'
)
,
:
true
,
}
)
)
;
// Create the internal Execute tool set
this
.
=
this
.
_register
(
this
.
createToolSet
(
.
,
'execute'
,
.
,
{
:
.
fromId
(
.
.
)
,
:
localize
(
'copilot.toolSet.execute.description'
,
'Execute code and applications on your machine'
)
,
:
true
,
}
)
)
;
// Create the internal Read tool set
this
.
=
this
.
_register
(
this
.
createToolSet
(
.
,
'read'
,
.
,
{
:
.
fromId
(
.
.
)
,
:
localize
(
'copilot.toolSet.read.description'
,
'Read files in your workspace'
)
,
:
true
,
}
)
)
;
// Create the internal Agent tool set
this
.
=
this
.
_register
(
this
.
createToolSet
(
.
,
'agent'
,
.
,
{
:
.
fromId
(
.
.
)
,
:
localize
(
'copilot.toolSet.agent.description'
,
'Delegate tasks to other agents'
)
,
:
true
,
}
)
)
;
}
private
isToolEnabledForModel
(
:
,
:
|
undefined
)
:
boolean
{
if
(
!
toolMatchesModel
(
,
)
)
{
return
false
;
}
if
(
.
===
.
&&
?.
.
startsWith
(
'gpt-5.5'
)
&&
this
.
.
getValue<boolean>
(
.
)
===
false
)
{
return
false
;
}
return
true
;
}
/**
* Returns if the given tool or toolset is permitted in the current context.
* When agent mode is enabled, all tools are permitted (no restriction)
* When agent mode is disabled only a subset of read-only tools are permitted in agentic-loop contexts.
*/
private
isPermitted
(
:
|
,
?
:
)
:
boolean
{
const
=
this
.
.
read
(
)
;
if
(
!==
false
)
{
return
true
;
}
// Internal tools that explicitly cannot be referenced in prompts are always permitted
// since they are infrastructure tools (e.g. inline_chat_exit), not user-facing agent tools
`[LanguageModelToolsService#invokeTool] Tool ${dto.toolId} denied by preToolUse hook: ${hookReason}`
)
;
if
(
)
{
if
(
)
{
.
=
.
;
.
cancelFromStreaming
(
.
,
)
;
}
else
if
(
)
{
const
=
.
createCancelled
(
{
:
.
,
:
.
,
,
:
.
,
:
.
}
,
.
,
.
,
)
;
.
=
.
;
this
.
.
appendProgress
(
,
)
;
}
}
return
{
:
[
{
:
'text'
,
:
`Tool execution denied: ${hookReason}`
}
]
,
:
,
}
;
}
/**
* Validate updatedInput from a preToolUse hook against the tool's input schema
* using the json.validate command from the JSON extension.
* @returns An error message string if validation fails, or undefined if valid.
*/
private
async
_validateUpdatedInput
(
:
string
,
:
|
undefined
,
:
)
:
Promise
<
string
|
undefined
>
{
if
(
!
?.
)
{
return
undefined
;
}
type
JsonDiagnostic
=
{
:
string
;
:
{
:
number
;
:
number
}
[
]
;
:
string
;
?
:
string
|
number
;
}
;
try
{
const
=
createToolSchemaUri
(
)
;
const
=
JSON
.
stringify
(
)
;
const
=
await
this
.
.
executeCommand<JsonDiagnostic[]>
(
'json.validate'
,
,
)
||
[
]
;
if
(
.
>
0
)
{
return
.
map
(
=>
.
)
.
join
(
'; '
)
;
}
}
catch
(
)
{
// json extension may not be available; skip validation
`[LanguageModelToolsService#invokeTool] Tool ${dto.toolId} input modified by preToolUse hook`
)
;
.
=
.
;
}
}
// Fire the event to notify listeners that a tool is being invoked
this
.
.
fire
(
{
:
.
,
:
.
?.
,
:
.
,
:
.
,
}
)
;
// When invoking a tool, don't validate the "when" clause. An extension may have invoked a tool just as it was becoming disabled, and just let it go through rather than throw and break the chat.
let
=
this
.
.
get
(
.
)
;
if
(
!
)
{
throw
new
Error
(
`Tool ${dto.toolId} was not contributed`
)
;
}
if
(
!
.
)
{
await
this
.
.
activateByEvent
(
`onLanguageModelTool:${dto.toolId}`
)
;
// Extension should activate and register the tool implementation
=
this
.
.
get
(
.
)
;
if
(
!
?.
)
{
throw
new
Error
(
`Tool ${dto.toolId} does not have an implementation registered.`
)
;
}
}
// Note: pending invocation lookup was already done above for the hook check
const
=
!
!
;
if
(
&&
)
{
// Remove from pending since we're now invoking it
this
.
.
delete
(
)
;
}
let
:
|
undefined
;
let
:
|
undefined
;
let
:
|
undefined
;
let
:
|
undefined
;
let
=
;
try
{
if
(
.
)
{
if
(
!
)
{
throw
new
Error
(
`Tool called for unknown chat session`
)
;
}
if
(
!
)
{
throw
new
Error
(
`Tool called for unknown chat request`
)
;
}
.
=
.
;
.
=
.
&&
{
...
.
}
;
=
.
create
(
true
)
;
=
await
this
.
prepareToolInvocationWithHookResult
(
,
,
,
)
;
.
stop
(
)
;
const
{
:
,
:
}
=
await
this
.
resolveAutoConfirmFromHook
(
,
,
,
,
.
?.
)
;
=
;
// A caller (e.g. the agent host) may have resolved auto-approval
// out-of-band. Treat it like a local auto-confirmation so the
// invocation never briefly enters `WaitingForConfirmation`. A
// preToolUse hook that returned `ask` explicitly forces a
// confirmation, so never let `preApproved` override it.
const
=
??
(
?.
===
'ask'
?
undefined
:
.
)
;
// In Autopilot, run the risk classifier on an auto-approved call that would
// otherwise show a confirmation. A "red" rating skips the call; anything else
// (including a classifier failure) keeps the original auto-confirmation.
const
{
,
:
}
=
await
this
.
_maybeApplyAutopilotRiskGate
(
,
,
,
,
)
;
// Important: a tool invocation that will be autoconfirmed should never
// be in the chat response in the `NeedsConfirmation` state, even briefly,
// as that triggers notifications and causes issues in eval.
if
(
&&
)
{
if
(
.
.
get
(
)
.
===
.
.
)
{
.
transitionFromStreaming
(
,
.
,
)
;
}
else
{
.
updatePreparedInvocation
(
,
.
)
;
}
}
else
{
// Create a new tool invocation (no streaming phase)
=
new
ChatToolInvocation
(
,
.
,
.
??
.
,
.
,
.
)
;
if
(
)
{
.
confirmWith
(
,
)
;
}
this
.
.
appendProgress
(
,
)
;
}
.
=
?.
;
// Enforce a risk skip here, before the confirmation flow below: run_in_terminal
// suppresses its own confirmation under Autopilot and never reaches it. The tool
// is not run, and an info note explains why.
if
(
)
{
this
.
_logToolApprovalTelemetry
(
,
,
{
:
.
}
)
;
// Terminal and edit tools hide their invocation part once complete, so show the
// reason as a separate info note.
this
.
.
appendProgress
(
,
{
:
'info'
,
:
new
MarkdownString
(
localize
(
'autopilotRiskSkipped'
,
"Autopilot skipped \"{0}\" because it was assessed as high-risk: {1}"
,
.
.
,
)
)
,
}
)
;
=
{
:
[
{
:
'text'
,
:
`Autopilot skipped this tool call because it was automatically assessed as high-risk: ${riskSkipExplanation} The action was not performed. Do not retry it as-is — choose a safer approach or leave it for the user to run manually.`
}
]
}
;
return
;
}
if
(
?.
?.
)
{
if
(
!
.
executionConfirmedOrDenied
(
)
&&
!
)
{
this
.
playAccessibilitySignal
(
[
]
,
.
?.
)
;
}
const
=
await
.
awaitConfirmation
(
,
)
;
this
.
_logToolApprovalTelemetry
(
,
,
)
;
if
(
.
===
.
)
{
throw
new
CancellationError
(
)
;
}
if
(
.
===
.
)
{
=
{
:
[
{
:
'text'
,
:
'The user chose to skip the tool call, they want to proceed without running it'
}
]
}
;
return
;
}
if
(
.
===
.
&&
.
)
{
.
=
.
;
}
if
(
.
?.
===
'input'
)
{
.
=
.
.
;
.
=
undefined
;
}
}
else
{
this
.
_logToolApprovalTelemetry
(
,
,
??
{
:
.
}
)
;
}
}
else
{
=
.
create
(
true
)
;
=
await
this
.
prepareToolInvocationWithHookResult
(
,
,
,
)
;
.
stop
(
)
;
const
{
:
,
:
}
=
await
this
.
resolveAutoConfirmFromHook
(
,
,
,
,
undefined
)
;
=
;
const
=
??
(
?.
===
'ask'
?
undefined
:
.
)
;
if
(
?.
?.
&&
!
)
{
const
=
await
this
.
.
confirm
(
{
:
renderAsPlaintext
(
.
.
)
,
:
renderAsPlaintext
(
.
.
!
)
}
)
;
if
(
!
.
)
{
throw
new
CancellationError
(
)
;
}
}
.
=
?.
;
}
if
(
.
)
{
throw
new
CancellationError
(
)
;
}
=
.
create
(
true
)
;
const
=
this
.
.
get
(
.
)
;
if
(
!
)
{
throw
new
Error
(
`Tool ${dto.toolId} was not contributed`
)
;
}
if
(
!
.
)
{
throw
new
Error
(
`Tool ${dto.toolId} does not have an implementation registered.`
)
;
}
=
;
=
await
.
.
invoke
(
,
,
{
report
:
=>
{
?.
acceptProgress
(
)
;
}
}
,
)
;
.
stop
(
)
;
// Apply post-processing compression (e.g. for run_in_terminal output)
// before the result reaches the model. Returns undefined when no
// compression applied.
const
=
this
.
.
maybeCompress
(
.
.
,
.
,
)
;
if
(
)
{
=
;
}
this
.
ensureToolDetails
(
,
,
.
,
)
;
const
=
await
?.
didExecuteTool
(
,
undefined
,
(
)
=>
this
.
shouldAutoConfirmPostExecution
(
.
.
,
.
.
,
.
.
,
.
,
.
?.
,
.
,
.
?.
)
)
;
if
(
&&
?.
===
.
.
)
{
const
=
await
.
awaitPostConfirmation
(
,
)
;
if
(
.
===
.
)
{
throw
new
CancellationError
(
)
;
}
if
(
.
===
.
)
{
=
{
:
[
{
:
'text'
,
:
'The tool executed but the user chose not to share the results'
/**
* Determines the auto-confirm decision based on a preToolUse hook result.
* If the hook returned 'allow', auto-approves. If 'ask', forces confirmation
* and ensures confirmation messages exist on `preparedInvocation`. Otherwise
* falls back to normal auto-confirm logic.
*
* Returns the possibly-updated preparedInvocation along with the auto-confirm decision,
* since when the hook returns 'ask' and preparedInvocation was undefined, we create one.
*/
private
async
resolveAutoConfirmFromHook
(
:
|
undefined
,
:
,
:
,
:
|
undefined
,
:
URI
|
undefined
,
)
:
Promise
<
{
:
|
undefined
;
:
|
undefined
}
>
{
if
(
?.
===
'allow'
)
{
this
.
.
debug
(
`[LanguageModelToolsService#invokeTool] Tool ${dto.toolId} auto-approved by preToolUse hook`
)
;
return
{
:
{
:
.
,
:
localize
(
'hookAllowed'
,
"Allowed by hook"
)
}
,
}
;
}
if
(
?.
===
'ask'
)
{
this
.
.
debug
(
`[LanguageModelToolsService#invokeTool] Tool ${dto.toolId} requires confirmation (preToolUse hook returned 'ask')`
)
;
// Ensure confirmation messages exist when hook requires confirmation
if
(
!
?.
?.
)
{
if
(
!
)
{
=
{
}
;
}
const
=
getToolFullReferenceName
(
.
)
;
const
=
.
;
const
=
?
localize
(
'hookRequiresConfirmation.messageWithReason'
,
"{0} hook required confirmation: {1}"
,
.
,
)
:
localize
(
'hookRequiresConfirmation.message'
,
"{0} hook required confirmation"
,
.
)
;
.
=
{
...
.
,
:
localize
(
'hookRequiresConfirmation.title'
,
"Use the '{0}' tool?"
,
)
,
:
new
MarkdownString
(
`_${hookNote}_`
)
,
:
false
,
}
;
.
=
{
:
'input'
,
:
.
,
}
;
}
else
{
// Tool already has its own confirmation - prepend hook note
const
=
.
;
const
=
?
localize
(
'hookRequiresConfirmation.note'
,
"{0} hook required confirmation: {1}"
,
.
,
)
:
localize
(
'hookRequiresConfirmation.noteNoReason'
,
"{0} hook required confirmation"
,
.
)
;
const
=
.
!
;
if
(
.
?.
===
'terminal'
)
{
// Terminal tools render message as hover only; use disclaimer for visible text
const
=
.
?
(
typeof
.
===
'string'
?
.
:
.
.
)
:
undefined
;
const
=
?
`${hookNote}\n\n${existingDisclaimerText}`
:
;
.
=
{
...
,
:
,
:
false
,
}
;
}
else
{
// Edit/other tools: prepend hook note to the message body
const
=
typeof
.
===
'string'
?
.
:
.
?.
??
''
;
.
=
{
...
,
:
new
MarkdownString
(
`_${hookNote}_\n\n${msgText}`
)
,
:
false
,
}
;
}
}
return
{
:
undefined
,
}
;
}
// No hook decision - use normal auto-confirm logic
const
=
?.
?.
;
let
:
{
:
string
;
:
string
}
|
undefined
;
if
(
)
{
=
{
:
typeof
.
===
'string'
?
.
:
.
.
,
:
.
,
}
;
}
const
=
await
this
.
shouldAutoConfirm
(
.
.
,
.
.
,
.
.
,
.
,
,
.
,
,
.
?.
)
;
return
{
,
}
;
}
/**
* In Autopilot, runs the risk classifier on an auto-approved call and skips it when the rating
* is {@link ToolRiskLevel.Red}. Any other result returns the original auto-confirmation
* unchanged.
*
* To keep the classifier off the hot path, it only runs when all of these hold:
* - the call was auto-approved by the session approving everything, or is a `run_in_terminal` /
* fetch call that self-approved (these can run risky commands or prompt-injected URLs without
* ever showing a confirmation);
* - it would otherwise show a confirmation (the self-approving tools above are the exception);
* - the session is a local panel session at the Autopilot level with Advanced Autopilot on.
*
* This is independent of `chat.tools.riskAssessment.enabled`, which only controls the
* confirmation risk badge. CLI and agent-host sessions handle their own confirmations and are
* excluded.
*
* Fails open: a cancelled, unavailable, or failed assessment keeps the original
* auto-confirmation so Autopilot keeps moving.
*/
private
async
_maybeApplyAutopilotRiskGate
(
:
,
:
,
:
|
undefined
,
:
|
undefined
,
:
,
)
:
Promise
<
{
:
|
undefined
;
?
:
string
}
>
{
const
=
.
.
===
.
;
const
=
.
has
(
.
.
)
;
const
=
||
;
// Normally only gate calls the session auto-approved wholesale (the `autoApproveAllReason`
// sentinel). A per-tool setting, user action, or hook carries a concrete reason and is
// respected as-is.
//
// Exception: run_in_terminal and fetch self-approve without a confirmation, so a risky command
// or a prompt-injected URL would run unclassified. Gate them when they arrive self-approved
// (no reason and no confirmation of their own); an explicit allow carries a concrete reason
// instead of `undefined`, so it stays respected.
const
=
?.
===
.
&&
.
===
;
const
=
&&
===
undefined
&&
!
?.
?.
;
if
(
!
&&
!
)
{
return
{
}
;
}
// Only gate calls that would otherwise show a confirmation, plus the self-approving tools above.
if
(
!
&&
!
?.
?.
)
{
return
{
}
;
}
// Check the Advanced Autopilot flag first: it is default-off, so the common case bails before
// the session lookups below. This does not consult `chat.tools.riskAssessment.enabled`, which
// only controls the confirmation risk badge.
if
(
this
.
.
getValue<boolean>
(
.
)
!==
true
)
{
return
{
}
;
}
// Scope to local panel sessions at the Autopilot level. CLI and agent-host sessions handle
// their own confirmations.
const
=
.
?.
;
if
(
!
||
getChatSessionType
(
)
!==
)
{
return
{
}
;
}
if
(
!
this
.
_isSessionInAutopilotLevel
(
)
)
{
return
{
}
;
}
try
{
// ignoreEnablement: assess even when the risk-badge setting is off.
const
=
await
this
.
.
assess
(
.
,
.
,
,
undefined
,
{
:
true
}
)
;
if
(
.
)
{
return
{
}
;
}
if
(
?.
===
.
)
{
const
=
localize
(
'autopilotRiskSkipFallback'
,
"The action was assessed as potentially destructive or irreversible."
`[LanguageModelToolsService#invokeTool] Autopilot risk assessment failed for tool ${tool.data.id}, allowing: ${toErrorMessage(err)}`
)
;
}
// Green/orange, no assessment, or a failure: keep the original auto-confirmation (fail open).
return
{
}
;
}
private
async
prepareToolInvocation
(
:
,
:
,
:
string
|
undefined
,
:
)
:
Promise
<
|
undefined
>
{
let
:
|
undefined
;
if
(
.
!
.
)
{
const
=
.
!
.
prepareToolInvocation
(
{
:
.
,
:
.
,
:
.
,
:
.
?.
,
:
.
,
:
.
,
:
,
:
.
?.
,
}
,
)
;
const
=
await
Promise
.
race
(
[
timeout
(
3000
,
)
.
then
(
(
)
=>
'timeout'
)
,
]
)
;
if
(
===
'timeout'
&&
.
)
{
this
.
.
fire
(
{
:
.
.
,
:
.
}
)
;
}
=
await
;
}
const
=
this
.
isToolEligibleForAutoApproval
(
.
)
;
// Default confirmation messages if tool is not eligible for auto-approval
if
(
!
&&
!
?.
?.
)
{
if
(
!
)
{
=
{
}
;
}
const
=
getToolFullReferenceName
(
.
)
;
// TODO: This should be more detailed per tool.
.
=
{
...
.
,
:
localize
(
'defaultToolConfirmation.title'
,
'Confirm tool execution'
)
,
:
localize
(
'defaultToolConfirmation.message'
,
'Run the \'{0}\' tool?'
,
)
,
:
.
has
(
.
.
)
?
undefined
:
new
MarkdownString
(
localize
(
'defaultToolConfirmation.disclaimer'
,
'Auto approval for \'{0}\' is restricted via {1}.'
,
getToolFullReferenceName
(
.
)
,
createMarkdownCommandLink
(
{
:
'`'
+
.
+
'`'
,
:
'workbench.action.openSettings'
,
:
[
.
]
,
:
localize
(
'openSettings.autoApproval.tooltip'
,
'Open settings to configure auto-approval'
)
}
,
false
)
)
,
{
:
true
}
)
,
:
false
,
}
;
}
if
(
!
&&
?.
?.
)
{
// Always overwrite the disclaimer if not eligible for auto-approval
.
.
=
.
has
(
.
.
)
?
undefined
:
new
MarkdownString
(
localize
(
'defaultToolConfirmation.disclaimer'
,
'Auto approval for \'{0}\' is restricted via {1}.'
,
getToolFullReferenceName
(
.
)
,
createMarkdownCommandLink
(
{
:
'`'
+
.
+
'`'
,
:
'workbench.action.openSettings'
,
:
[
.
]
,
:
localize
(
'openSettings.autoApproval.tooltip'
,
'Open settings to configure auto-approval'
)
}
,
false
)
)
,
{
:
true
}
)
;
}
if
(
?.
?.
)
{
if
(
this
.
_isAutoApprovePolicyRestricted
(
)
)
{
.
.
=
false
;
}
else
if
(
.
?.
!==
'terminal'
&&
.
.
!==
false
)
{
.
.
=
;
}
if
(
!
.
&&
.
.
)
{
.
=
{
:
'input'
,
:
.
,
}
;
}
}
return
;
}
beginToolCall
(
:
)
:
|
undefined
{
// First try to look up by tool ID (the package.json "name" field),
// then fall back to looking up by toolReferenceName
const
=
this
.
.
get
(
.
)
;
if
(
!
)
{
return
undefined
;
}
// Don't create a streaming invocation for tools that don't implement handleToolStream.
// These tools will have their invocation created directly in invokeToolInternal.
// Callers that need a handle regardless (e.g. to observe confirmation state) can pass `force`.
if
(
!
.
&&
!
.
?.
)
{
return
undefined
;
}
// Create the invocation in streaming state
const
=
.
createStreaming
(
{
:
.
,
:
.
,
:
.
,
:
.
,
:
.
,
}
)
;
// Track the pending tool call
this
.
.
set
(
.
,
)
;
// If we have a session, append the invocation to the chat as progress
if
(
.
)
{
const
=
this
.
.
getSession
(
.
)
;
if
(
)
{
// Find the request by chatRequestId if available, otherwise use the last request
const
=
(
.
?
.
getRequests
(
)
.
find
(
=>
.
===
.
)
:
undefined
)
??
.
getRequests
(
)
.
at
(
-
1
)
;
if
(
)
{
this
.
.
appendProgress
(
,
)
;
}
}
}
// Call handleToolStream to get initial streaming message
this
.
_callHandleToolStream
(
,
,
.
,
undefined
,
.
)
;
return
;
}
private
async
_callHandleToolStream
(
:
,
:
,
:
string
,
:
unknown
,
:
)
:
Promise
<
void
>
{
if
(
!
.
?.
)
{
return
;
}
try
{
const
=
await
.
.
handleToolStream
(
{
,
,
:
.
,
}
,
)
;
if
(
?.
)
{
.
updateStreamingMessage
(
.
)
;
}
}
catch
(
)
{
this
.
.
error
(
`[LanguageModelToolsService#_callHandleToolStream] Error calling handleToolStream for tool ${toolEntry.data.id}:`
,
)
;
}
}
async
updateToolStream
(
:
string
,
:
unknown
,
:
)
:
Promise
<
void
>
{
const
=
this
.
.
get
(
)
;
if
(
!
)
{
return
;
}
// Update the partial input on the invocation
.
updatePartialInput
(
)
;
// Call handleToolStream if the tool implements it
const
=
this
.
.
get
(
.
)
;
if
(
)
{
await
this
.
_callHandleToolStream
(
,
,
,
,
)
;
}
}
private
playAccessibilitySignal
(
:
[
]
,
:
URI
|
undefined
)
:
void
{
const
=
this
.
.
getValue
(
.
)
;
if
(
)
{
return
;
}
// Autopilot/auto-approve permission levels auto-approve all tools, skip signal
if
(
)
{
const
=
this
.
.
getSession
(
)
;
const
=
?.
getRequests
(
)
.
at
(
-
1
)
;
if
(
isAutoApproveLevel
(
?.
?.
)
||
this
.
_isSessionLiveAutoApproveLevel
(
)
)
{
return
;
}
}
// Filter out any tool invocations that have already been confirmed/denied.
// This is a defensive check - normally the call site should prevent this,
// but tools may be auto-approved through various mechanisms (per-session rules,
// per-workspace rules, etc.) that could cause a race condition.
const
=
.
filter
(
=>
!
.
executionConfirmedOrDenied
(
)
)
;
if
(
.
===
0
)
{
return
;
}
const
:
{
?
:
'auto'
|
'on'
|
'off'
;
?
:
'auto'
|
'off'
}
|
undefined
=
this
.
.
getValue
(
.
.
)
;
if
(
!
)
{
return
;
}
const
=
.
===
'on'
||
(
.
===
'auto'
&&
(
this
.
.
isScreenReaderOptimized
(
)
)
)
;
const
=
this
.
.
isScreenReaderOptimized
(
)
&&
.
===
'auto'
;
if
(
||
)
{
this
.
.
playSignal
(
.
,
{
:
this
.
.
invokeFunction
(
,
)
,
:
true
,
:
!
?
'announcement'
:
undefined
}
)
;
}
}
private
ensureToolDetails
(
:
,
:
,
:
,
:
|
undefined
)
:
void
{
if
(
!
.
&&
(
.
||
(
this
.
toolResultHasImages
(
)
&&
!
this
.
toolResultMessageHasImageFileWidgets
(
,
)
)
)
)
{
.
=
{
:
this
.
formatToolInput
(
)
,
:
this
.
toolResultToIO
(
)
,
}
;
}
}
private
toolResultHasImages
(
:
)
:
boolean
{
return
.
.
some
(
=>
.
===
'data'
&&
.
.
?.
startsWith
(
'image/'
)
)
;
}
/**
* Returns true if the tool result message (or falling back to the tool invocation's
* pastTenseMessage from streaming) contains empty markdown links pointing to image
* files (the `[](imageUri)
` pattern) that will be rendered as file pills by renderFileWidgets.
*/
private toolResultMessageHasImageFileWidgets(toolResult: IToolResult, toolInvocation: ChatToolInvocation | undefined): boolean {
// Check toolResult.toolResultMessage first — this is what didExecuteTool will
// copy into pastTenseMessage, and it's already available at this point.
// Fall back to pastTenseMessage which may have been set during the streaming phase.
const message = toolResult.toolResultMessage ?? toolInvocation?.pastTenseMessage;
if (!message) {
return false;
}
const value = typeof message === 'string' ? message : message.value;
// Match empty-text markdown links: [](uri) or [ ](uri), capturing the uri
const linkPattern = /\[\s*\]\((?<uri>[^)]+)\)/g;
let match: RegExpExecArray | null;
while ((match = linkPattern.exec(value)) !== null) {
try {
const parsed = URI.parse(match.groups!.uri);
const mime = getMediaMime(parsed.path);
if (mime?.startsWith('image/')) {
return true;
}
} catch {
// Invalid URI, skip
}
}
return false;
}
private formatToolInput(dto: IToolInvocation): string {
return JSON.stringify(dto.parameters, undefined, 2);
}
private toolResultToIO(toolResult: IToolResult): IToolResultInputOutputDetails['output'] {
return toolResult.content.map(part => {
if (part.kind === 'text') {
return { type: 'embed', isText: true, value: part.value };
} else if (part.kind === 'promptTsx') {
return { type: 'embed', isText: true, value: stringifyPromptTsxPart(part) };
} else if (part.kind === 'data') {
return { type: 'embed', value: encodeBase64(part.value.data), mimeType: part.value.mimeType };
} else {
assertNever(part);
}
});
}
/**
* Returns true if enterprise policy has explicitly disabled the global auto-approve setting.
* When this is the case, Bypass Approvals and Autopilot permission levels should not auto-approve tools.
*/
private _isAutoApprovePolicyRestricted(): boolean {
const inspected = this._configurationService.inspect<boolean>(ChatConfiguration.GlobalAutoApprove);
return inspected.policyValue === false;
}
/**
* Returns true if the session's current (live) permission picker level is auto-approve.
* This checks the widget's current state, not what was stamped on the request,
* so switching to Autopilot mid-session takes effect immediately.
*/
private _isSessionLiveAutoApproveLevel(chatSessionResource: URI): boolean {
const widget = this._chatWidgetService.getWidgetBySessionResource(chatSessionResource)
?? this._chatWidgetService.lastFocusedWidget;
return !!widget && isAutoApproveLevel(widget.input.currentModeInfo.permissionLevel);
}
/**
* True if the session is in an auto-approve level (Auto-Approve / Autopilot),
* via either the last request's stamped level or the live picker level.
*/
private _isSessionInAutoApproveLevel(chatSessionResource: URI | undefined): boolean {
if (!chatSessionResource) {
return false;
}
const model = this._chatService.getSession(chatSessionResource);
const request = model?.getRequests().at(-1);
return isAutoApproveLevel(request?.modeInfo?.permissionLevel) || this._isSessionLiveAutoApproveLevel(chatSessionResource);
}
/**
* True if the session's live permission picker level is Autopilot. Like
* {@link _isSessionLiveAutoApproveLevel}, but excludes plain Auto-Approve.
*/
private _isSessionLiveAutopilotLevel(chatSessionResource: URI): boolean {
const widget = this._chatWidgetService.getWidgetBySessionResource(chatSessionResource)
?? this._chatWidgetService.lastFocusedWidget;
return !!widget && isAutopilotLevel(widget.input.currentModeInfo.permissionLevel);
}
/**
* True if the session is at the Autopilot level (not plain Auto-Approve), via either the last
* request's stamped level or the live picker level.
*/
private _isSessionInAutopilotLevel(chatSessionResource: URI | undefined): boolean {
if (!chatSessionResource) {
return false;
}
const model = this._chatService.getSession(chatSessionResource);
const request = model?.getRequests().at(-1);
return isAutopilotLevel(request?.modeInfo?.permissionLevel) || this._isSessionLiveAutopilotLevel(chatSessionResource);
}
private getEligibleForAutoApprovalSpecialCase(toolData: IToolData): string | undefined {
if (toolData.id === 'vscode_fetchWebPage_internal') {
return 'fetch';
}
return undefined;
}
private isToolEligibleForAutoApproval(toolData: IToolData): boolean {
const fullReferenceName = this.getEligibleForAutoApprovalSpecialCase(toolData) ?? getToolFullReferenceName(toolData);
if (toolData.id === 'copilot_fetchWebPage') {
// Special case, this fetch will call an internal tool 'vscode_fetchWebPage_internal'
return true;
}
if (toolIdsThatCannotBeAutoApproved.has(toolData.id)) {
// Special case, this tool will always require user confirmation as there are multiple options,
// These aren't LM generated instead are generated by extension before agentic loop starts.
return false;
}
const eligibilityConfig = this._configurationService.getValue<Record<string, boolean>>(ChatConfiguration.EligibleForAutoApproval);
if (eligibilityConfig && typeof eligibilityConfig === 'object' && fullReferenceName) {
// Direct match
if (Object.prototype.hasOwnProperty.call(eligibilityConfig, fullReferenceName)) {
return eligibilityConfig[fullReferenceName];
}
// Back compat with legacy names
if (toolData.legacyToolReferenceFullNames) {
for (const legacyName of toolData.legacyToolReferenceFullNames) {
// Check if the full legacy name is in the config
if (Object.prototype.hasOwnProperty.call(eligibilityConfig, legacyName)) {
return eligibilityConfig[legacyName];
}
// Some tools may be both renamed and namespaced from a toolset, eg: xxx/yyy -> yyy
if (legacyName.includes('/')) {
const trimmedLegacyName = legacyName.split('/').pop();
if (trimmedLegacyName && Object.prototype.hasOwnProperty.call(eligibilityConfig, trimmedLegacyName)) {
return eligibilityConfig[trimmedLegacyName];
}
}
}
}
}
return true;
}
private async shouldAutoConfirm(toolId: string, runsInWorkspace: boolean | undefined, source: ToolDataSource, parameters: unknown, chatSessionResource: URI | undefined, chatRequestId: string | undefined, combination?: { label: string; key: string }, workingDirectory?: URI): Promise<ConfirmedReason | undefined> {
const tool = this._tools.get(toolId);
if (!tool) {
return undefined;
}
// Bypass confirmation under Auto-Approve / Autopilot, unless enterprise
// policy disables global auto-approve.
if (chatSessionResource && !this._isAutoApprovePolicyRestricted() && this._isSessionInAutoApproveLevel(chatSessionResource)) {
// CLI sessions still need their multi-option dialogs (e.g. uncommitted changes).
if (!(toolIdsThatCannotBeAutoApproved.has(tool.data.id) && getChatSessionType(chatSessionResource) !== localChatSessionType)) {
return { type: ToolConfirmKind.ConfirmationNotNeeded, reason: autoApproveAllReason };
}
}
if (!this.isToolEligibleForAutoApproval(tool.data)) {
return undefined;
}
const reason = this._confirmationService.getPreConfirmAction({ toolId, source, parameters, chatSessionResource, workingDirectory, combination });
if (reason) {
return reason;
}
const config = this._configurationService.inspect<boolean | Record<string, boolean>>(ChatConfiguration.GlobalAutoApprove);
// If we know the tool runs at a global level, only consider the global config.
// If we know the tool runs at a workspace level, use those specific settings when appropriate.
let value = config.value ?? config.defaultValue;
if (typeof runsInWorkspace === 'boolean') {
value = config.userLocalValue ?? config.applicationValue;
if (runsInWorkspace) {
value = config.workspaceValue ?? config.workspaceFolderValue ?? config.userRemoteValue ?? value;
}
}
const autoConfirm = value === true || (typeof value === 'object' && value.hasOwnProperty(toolId) && value[toolId] === true);
if (autoConfirm) {
if (await this._checkGlobalAutoApprove()) {
return { type: ToolConfirmKind.Setting, id: ChatConfiguration.GlobalAutoApprove };
}
}
return undefined;
}
private async shouldAutoConfirmPostExecution(toolId: string, runsInWorkspace: boolean | undefined, source: ToolDataSource, parameters: unknown, chatSessionResource: URI | undefined, chatRequestId: string | undefined, workingDirectory?: URI): Promise<ConfirmedReason | undefined> {
// Bypass post-execution confirmation under Auto-Approve / Autopilot,
// unless enterprise policy disables global auto-approve.
const sessionAutoApprove = chatSessionResource && !this._isAutoApprovePolicyRestricted() && this._isSessionInAutoApproveLevel(chatSessionResource);
if (sessionAutoApprove) {
if (!(toolIdsThatCannotBeAutoApproved.has(toolId) && getChatSessionType(chatSessionResource!) !== localChatSessionType)) {
return { type: ToolConfirmKind.ConfirmationNotNeeded, reason: autoApproveAllReason };
}
}
// Don't show the YOLO opt-in dialog under autopilot: this runs after the
// tool result is already back in the agent loop, so it can't block anything.
if (this._configurationService.getValue<boolean>(ChatConfiguration.GlobalAutoApprove) && !sessionAutoApprove && await this._checkGlobalAutoApprove()) {
return { type: ToolConfirmKind.Setting, id: ChatConfiguration.GlobalAutoApprove };
}
return this._confirmationService.getPostConfirmAction({ toolId, source, parameters, chatSessionResource, workingDirectory });
}
private async _checkGlobalAutoApprove(): Promise<boolean> {
const optedIn = this._storageService.getBoolean(AutoApproveStorageKeys.GlobalAutoApproveOptIn, StorageScope.APPLICATION, false);
if (optedIn) {
return true;
}
if (this._contextKeyService.getContextKeyValue(SkipAutoApproveConfirmationKey) === true) {
return true;
}
if (this._pendingGlobalAutoApproveCheck) {
return this._pendingGlobalAutoApproveCheck;
}
this._pendingGlobalAutoApproveCheck = this._doCheckGlobalAutoApprove();
try {
return await this._pendingGlobalAutoApproveCheck;
} finally {
this._pendingGlobalAutoApproveCheck = undefined;
}
}
private async _doCheckGlobalAutoApprove(): Promise<boolean> {
const store = new DisposableStore();
try {
// Dismiss the dialog automatically if another window stores the
// opt-in flag, avoiding duplicate approval prompts.
const cts = new CancellationTokenSource();
store.add(cts);
store.add(this._storageService.onDidChangeValue(StorageScope.APPLICATION, AutoApproveStorageKeys.GlobalAutoApproveOptIn, store)(() => {
if (this._storageService.getBoolean(AutoApproveStorageKeys.GlobalAutoApproveOptIn, StorageScope.APPLICATION, false)) {
cts.cancel();
}
}));
const promptResult = await this._dialogService.prompt({
type: Severity.Warning,
message: localize('autoApprove2.title', 'Enable global auto approve?'),
buttons: [
{
label: localize('autoApprove2.button.enable', 'Enable'),
run: () => true
},
{
label: localize('autoApprove2.button.disable', 'Disable'),
run: () => false
},
],
custom: {
icon: Codicon.warning,
markdownDetails: [{
markdown: new MarkdownString(globalAutoApproveDescription.value, { isTrusted: { enabledCommands: ['workbench.action.openSettings'] } }),
}],
},
token: cts.token,
});
// If cancelled by cross-window approval, treat as approved
if (cts.token.isCancellationRequested) {
return true;
}
if (promptResult.result !== true) {
await this._configurationService.updateValue(ChatConfiguration.GlobalAutoApprove, false);
return false;
}
this._storageService.store(AutoApproveStorageKeys.GlobalAutoApproveOptIn, true, StorageScope.APPLICATION, StorageTarget.USER);
return true;
} finally {
store.dispose();
}
}
private cleanupCallDisposables(requestId: string | undefined, store: DisposableStore): void {
if (requestId) {
const disposables = this._callsByRequestId.get(requestId);
if (disposables) {
const index = disposables.findIndex(d => d.store === store);
if (index > -1) {
disposables.splice(index, 1);
}
if (disposables.length === 0) {
this._callsByRequestId.delete(requestId);
}
}
}
store.dispose();
}
cancelToolCallsForRequest(requestId: string): void {
const calls = this._callsByRequestId.get(requestId);
if (calls) {
calls.forEach(call => call.store.dispose());
this._callsByRequestId.delete(requestId);
}
// Clean up any pending tool calls that belong to this request
for (const [toolCallId, invocation] of this._pendingToolCalls) {
if (invocation.chatRequestId === requestId) {
this._pendingToolCalls.delete(toolCallId);
}
}
}
private static readonly githubMCPServerAliases = ['github/github-mcp-server', 'io.github.github/github-mcp-server', 'github-mcp-server'];
private static readonly playwrightMCPServerAliases = ['microsoft/playwright-mcp', 'com.microsoft/playwright-mcp'];
private *getToolSetAliases(toolSet: ToolSet, fullReferenceName: string): Iterable<string> {
if (fullReferenceName !== toolSet.referenceName) {
yield toolSet.referenceName; // tool set name without '/*'
}
if (toolSet.legacyFullNames) {
yield* toolSet.legacyFullNames;
}
switch (toolSet.referenceName) {
case 'github':
for (const alias of LanguageModelToolsService.githubMCPServerAliases) {
yield alias + '/*';
}
break;
case 'playwright':
for (const alias of LanguageModelToolsService.playwrightMCPServerAliases) {
yield alias + '/*';
}
break;
case SpecedToolAliases.execute: // 'execute'
yield 'shell'; // legacy alias
break;
case SpecedToolAliases.agent: // 'agent'
yield VSCodeToolReference.runSubagent; // prefer the tool set over th old tool name
yield 'custom-agent'; // legacy alias
break;
}
}
private * getToolAliases(toolSet: IToolData, fullReferenceName: string): Iterable<string> {
const referenceName = toolSet.toolReferenceName ?? toolSet.displayName;
if (fullReferenceName !== referenceName && referenceName !== VSCodeToolReference.runSubagent) {
yield referenceName; // simple name, without toolset name
}
if (toolSet.legacyToolReferenceFullNames) {
for (const legacyName of toolSet.legacyToolReferenceFullNames) {
yield legacyName;
const lastSlashIndex = legacyName.lastIndexOf('/');
if (lastSlashIndex !== -1) {
yield legacyName.substring(lastSlashIndex + 1); // it was also known under the simple name
}
}
}
const slashIndex = fullReferenceName.lastIndexOf('/');
if (slashIndex !== -1) {
switch (fullReferenceName.substring(0, slashIndex)) {
case 'github':
for (const alias of LanguageModelToolsService.githubMCPServerAliases) {
yield alias + fullReferenceName.substring(slashIndex);
}
break;
case 'playwright':
for (const alias of LanguageModelToolsService.playwrightMCPServerAliases) {
yield alias + fullReferenceName.substring(slashIndex);
}
break;
}
}
}
/**
* Create a map that contains all tools and toolsets with their enablement state.
* @param fullReferenceNames A list of tool or toolset by their full reference names that are enabled.
* @returns A map of tool or toolset instances to their enablement state.
*/
toToolAndToolSetEnablementMap(fullReferenceNames: readonly string[], model: ILanguageModelChatMetadata | undefined): ToolAndToolSetEnablementMap {
const toolOrToolSetNames = new Set(fullReferenceNames);
const result = new Map<IToolSet | IToolData, boolean>();
for (const [tool, fullReferenceName] of this.toolsWithFullReferenceName.get()) {
if (isToolSet(tool)) {
const enabled = toolOrToolSetNames.has(fullReferenceName) || Iterable.some(this.getToolSetAliases(tool, fullReferenceName), name => toolOrToolSetNames.has(name));
const scoped = model ? new ToolSetForModel(tool, model) : tool;
result.set(scoped, enabled);
if (enabled) {
for (const memberTool of scoped.getTools()) {
result.set(memberTool, true);
}
}
} else {
if (!this.isToolEnabledForModel(tool, model)) {
continue;
}
if (!result.has(tool)) { // already set via an enabled toolset
const enabled = toolOrToolSetNames.has(fullReferenceName)
|| Iterable.some(this.getToolAliases(tool, fullReferenceName), name => toolOrToolSetNames.has(name))
|| !!tool.legacyToolReferenceFullNames?.some(toolFullName => {
// enable tool if just the legacy tool set name is present
const index = toolFullName.lastIndexOf('/');
return index !== -1 && toolOrToolSetNames.has(toolFullName.substring(0, index));
});
result.set(tool, enabled);
}
}
}
// also add all user tool sets (not part of the prompt referencable tools)
for (const toolSet of this._toolSets) {
if (toolSet.source.type === 'user') {
const enabled = Iterable.every(toolSet.getTools(), t => result.get(t) === true);
result.set(toolSet, enabled);
}
}
return ToolAndToolSetEnablementMap.fromMap(result);
}
toFullReferenceNames(map: ToolAndToolSetEnablementMap): string[] {
const result: string[] = [];
const toolsCoveredByEnabledToolSet = new Set<IToolData>();
// compare by id as toolset instances may be different (e.g. ToolSetForModel)
const enabledToolSetIds = new Set<string>();
const enabledToolIds = new Set<string>();
for (const [tool, enabled] of map) {
if (enabled) {
if (isToolSet(tool)) {
enabledToolSetIds.add(tool.id);
} else {
enabledToolIds.add(tool.id);
}
}
}
for (const [tool, fullReferenceName] of this.toolsWithFullReferenceName.get()) {
if (isToolSet(tool)) {
if (enabledToolSetIds.has(tool.id)) {
result.push(fullReferenceName);
for (const memberTool of tool.getTools()) {
toolsCoveredByEnabledToolSet.add(memberTool);
}
}
} else {
if (enabledToolIds.has(tool.id) && !toolsCoveredByEnabledToolSet.has(tool)) {
result.push(fullReferenceName);
}
}
}
return result;
}
toToolReferences(variableReferences: readonly IVariableReference[]): ChatRequestToolReferenceEntry[] {
const toolsOrToolSetByName = new Map<string, ToolSet | IToolData>();
for (const [tool, fullReferenceName] of this.toolsWithFullReferenceName.get()) {
toolsOrToolSetByName.set(fullReferenceName, tool);
}
const result: ChatRequestToolReferenceEntry[] = [];
for (const ref of variableReferences) {
const toolOrToolSet = toolsOrToolSetByName.get(ref.name);
if (toolOrToolSet) {
if (isToolSet(toolOrToolSet)) {
result.push(toToolSetVariableEntry(toolOrToolSet, ref.range));
} else {
result.push(toToolVariableEntry(toolOrToolSet, ref.range));
}
}
}
return result;
}
private readonly _toolSets = new ObservableSet<ToolSet>();
readonly toolSets: IObservable<Iterable<ToolSet>> = derived(this, reader => {
const allToolSets = Array.from(this._toolSets.observable.read(reader));
return allToolSets.filter(toolSet => this.isPermitted(toolSet, reader));
});
getToolSetsForModel(model: ILanguageModelChatMetadata | undefined, reader?: IReader): Iterable<IToolSet> {
if (!model) {
return this.toolSets.read(reader);
}
return Iterable.map(this.toolSets.read(reader), ts => new ToolSetForModel(ts, model, toolData => this.isToolEnabledForModel(toolData, model)));
}
getToolSet(id: string): ToolSet | undefined {
for (const toolSet of this._toolSets) {
if (toolSet.id === id) {
return toolSet;
}
}
return undefined;
}
getToolSetByName(name: string): ToolSet | undefined {
for (const toolSet of this._toolSets) {
if (toolSet.referenceName === name) {
return toolSet;
}
}
return undefined;
}
getSpecedToolSetName(referenceName: string): string {
if (LanguageModelToolsService.githubMCPServerAliases.includes(referenceName)) {
return 'github';
}
if (LanguageModelToolsService.playwrightMCPServerAliases.includes(referenceName)) {
return 'playwright';
}
return referenceName;
}
createToolSet(source: ToolDataSource, id: string, referenceName: string, options?: { icon?: ThemeIcon; description?: string; detail?: string; legacyFullNames?: string[]; deprecated?: boolean; hiddenInToolsPicker?: boolean }): ToolSet & IDisposable {
const that = this;
referenceName = this.getSpecedToolSetName(referenceName);
const result = new class extends ToolSet implements IDisposable {
dispose(): void {
if (that._toolSets.has(result)) {
this._tools.clear();
that._toolSets.delete(result);
}
}
}(id, referenceName, options?.icon ?? Codicon.tools, source, options?.description, options?.detail, options?.legacyFullNames, options?.deprecated, options?.hiddenInToolsPicker, this._contextKeyService);
this._toolSets.add(result);
return result;
}
private readonly allToolsIncludingDisableObs = observableFromEventOpts<readonly IToolData[], void>(
{ equalsFn: arrayEqualsC() },
this.onDidChangeTools,
() => Array.from(this.getAllToolsIncludingDisabled()),
);
private readonly toolsWithFullReferenceName = derived<[IToolData | ToolSet, string][]>(reader => {
const result: [IToolData | ToolSet, string][] = [];
const coveredByToolSets = new Set<IToolData>();
for (const toolSet of this.toolSets.read(reader)) {
if (toolSet.source.type !== 'user') {
result.push([toolSet, getToolSetFullReferenceName(toolSet)]);
for (const tool of toolSet.getTools()) {
result.push([tool, getToolFullReferenceName(tool, toolSet)]);
coveredByToolSets.add(tool);
}
}
}
for (const tool of this.allToolsIncludingDisableObs.read(reader)) {
// todo@connor4312/aeschil: this effectively hides model-specific tools
// for prompt referencing. Should we eventually enable this? (If so how?)
if (tool.when && !this._contextKeyService.contextMatchesRules(tool.when)) {
continue;
}
if (tool.canBeReferencedInPrompt && !coveredByToolSets.has(tool) && this.isPermitted(tool, reader)) {
result.push([tool, getToolFullReferenceName(tool)]);
}
}
return result;
});
* getFullReferenceNames(): Iterable<string> {
for (const [, fullReferenceName] of this.toolsWithFullReferenceName.get()) {
yield fullReferenceName;
}
}
getDeprecatedFullReferenceNames(): Map<string, Set<string>> {
const result = new Map<string, Set<string>>();
const knownToolSetNames = new Set<string>();
const add = (name: string, fullReferenceName: string) => {
if (name !== fullReferenceName) {
if (!result.has(name)) {
result.set(name, new Set<string>());
}
result.get(name)!.add(fullReferenceName);
}
};
for (const [tool, _] of this.toolsWithFullReferenceName.get()) {
if (isToolSet(tool)) {
knownToolSetNames.add(tool.referenceName);
if (tool.legacyFullNames) {
for (const legacyName of tool.legacyFullNames) {
knownToolSetNames.add(legacyName);
}
}
}
}
for (const [tool, fullReferenceName] of this.toolsWithFullReferenceName.get()) {
if (isToolSet(tool)) {
for (const alias of this.getToolSetAliases(tool, fullReferenceName)) {
add(alias, fullReferenceName);
}
} else {
for (const alias of this.getToolAliases(tool, fullReferenceName)) {
add(alias, fullReferenceName);
}
if (tool.legacyToolReferenceFullNames) {
// If the tool is in a toolset (fullReferenceName has a '/'), also add the
// namespaced form of legacy names (e.g. 'vscode/oldName' → 'vscode/newName')
const slashIndex = fullReferenceName.lastIndexOf('/');
const toolSetPrefix = slashIndex !== -1 ? fullReferenceName.substring(0, slashIndex + 1) : undefined;
for (const legacyName of tool.legacyToolReferenceFullNames) {
if (toolSetPrefix && !legacyName.includes('/')) {
add(toolSetPrefix + legacyName, fullReferenceName);
}
// for any 'orphaned' toolsets (toolsets that no longer exist and
// do not have an explicit legacy mapping), we should
// just point them to the list of tools directly
if (legacyName.includes('/')) {
const toolSetFullName = legacyName.substring(0, legacyName.lastIndexOf('/'));
if (!knownToolSetNames.has(toolSetFullName)) {
add(toolSetFullName, fullReferenceName);
}
}
}
}
}
}
return result;
}
getToolByFullReferenceName(fullReferenceName: string): IToolData | ToolSet | undefined {
for (const [tool, toolFullReferenceName] of this.toolsWithFullReferenceName.get()) {
if (fullReferenceName === toolFullReferenceName) {
return tool;
}
const aliases = isToolSet(tool) ? this.getToolSetAliases(tool, toolFullReferenceName) : this.getToolAliases(tool, toolFullReferenceName);
if (Iterable.some(aliases, alias => fullReferenceName === alias)) {
return tool;
}
}
return undefined;
}
getFullReferenceName(tool: IToolData | IToolSet, toolSet?: IToolSet): string {
for (const [item, toolFullReferenceName] of this.toolsWithFullReferenceName.get()) {
if (item === tool) {
return toolFullReferenceName;
}
}
if (isToolSet(tool)) {
return getToolSetFullReferenceName(tool);
}
return getToolFullReferenceName(tool, toolSet);
}
getFullReferenceNameMap(): Map<IToolData | IToolSet, string> {
const result = new Map<IToolData | IToolSet, string>();
for (const [item, toolFullReferenceName] of this.toolsWithFullReferenceName.get()) {
result.set(item, toolFullReferenceName);
}
return result;
}
}
function getToolFullReferenceName(tool: IToolData, toolSet?: IToolSet) {
const toolName = tool.toolReferenceName ?? tool.displayName;
if (toolSet) {
return `
{
.
}
/
{
}
`;
} else if (tool.source.type === 'extension') {
return `
{
.
.
.
.
toLowerCase
(
)
}
/
{
}
`;
}
return toolName;
}
function getToolSetFullReferenceName(toolSet: IToolSet) {
if (toolSet.source.type === 'mcp') {
return `
{
.
}
/*`;
}
return toolSet.referenceName;
}
type ToolApprovalEvent = LanguageModelToolTelemetryData & {
confirmKind: string;
requestId: string | undefined;
settingId: string | undefined;
lmServiceScope: string | undefined;
customButtonKind: string | undefined;
confirmationNotNeededReason: string | undefined;
sandboxWrapped: boolean | undefined;
requestUnsandboxedExecution: boolean | undefined;
};
type ToolApprovalClassification = LanguageModelToolTelemetryClassification & {
confirmKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'How the confirmation was resolved (userAction, setting, lmServicePerTool, confirmationNotNeeded, denied, skipped). Anything other than userAction implies auto-approval. "denied" and "skipped" mean the tool did not run; otherwise it ran (note: a custom Deny button click resolves as userAction since the tool still runs and the chosen label is passed to it; see customButtonKind to distinguish).' };
requestId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The ID of the chat request turn that this tool approval is associated with, if available.' };
settingId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When confirmKind is setting, the configuration id that auto-approved the tool.' };
lmServiceScope: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When confirmKind is lmServicePerTool, the scope (session/workspace/profile).' };
customButtonKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When the user clicked a custom button on the confirmation widget, whether the button represents approve or deny semantics. Undefined when no custom button was clicked.' };
confirmationNotNeededReason: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When confirmKind is confirmationNotNeeded, a stable identifier for why the tool did not require confirmation. Limited to a known allowlist (e.g. auto-approve-all, inlineChat); set to "other" for any other reason; undefined when no reason was supplied.' };
sandboxWrapped: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'For terminal tool calls, whether this specific invocation runs inside the agent terminal sandbox. Undefined for non-terminal tools.' };
requestUnsandboxedExecution: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'For terminal tool calls, whether the model requested to bypass the sandbox for this invocation. Undefined for non-terminal tools.' };
owner: 'chrmarti';
comment: 'Provides insight into how tool confirmations are resolved (user action vs. auto-approval).';
};