Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* Render one round of the assistant response's tool calls.
* One assistant response "turn" which contains multiple rounds of assistant message text, tool calls, and tool results.
*/
export
class
ChatToolCalls
extends
PromptElement<ChatToolCallsProps,void>
{
constructor
(
:
PromptElementProps
<
ChatToolCallsProps
>
,
IToolsService
private
readonly
:
IToolsService
,
IPromptEndpoint
private
readonly
:
IPromptEndpoint
,
IInstantiationService
private
readonly
:
IInstantiationService
)
{
super
(
)
;
}
async
render
(
:
void
,
:
PromptSizing
,
?
:
unknown
,
?
:
CancellationToken
)
:
Promise
<
PromptPiece
<
any
,
any
>
|
undefined
>
{
if
(
!
this
.
props
.
promptContext
.
tools
||
!
this
.
props
.
toolCallRounds
?.
)
{
return
;
}
// Create a child instantiation service with IBuildPromptContext registered
const
=
this
.
instantiationService
.
createChild
(
new
ServiceCollection
(
[
IBuildPromptContext
,
this
.
props
.
promptContext
]
)
)
;
// Shared budget to limit total image data across all tool results in this turn.
// Prevents 413 errors when many image-returning tools run in parallel.
const
:
SharedImageBudget
=
{
:
CAPI_IMAGE_BUDGET_BYTES
}
;
const
=
this
.
props
.
toolCallRounds
.
flatMap
(
(
,
)
=>
{
return
this
.
renderOneToolCallRound
(
,
,
this
.
props
.
toolCallRounds
!
.
length
,
,
,
)
;
}
)
;
if
(
!
.
length
)
{
return
;
}
const
KeepWith
=
useKeepWith
(
)
;
return
<>
<KeepWithpriority={1}flexGrow={1}>
{
}
</KeepWith>
</>
;
}
/**
* Render one round of tool calling: the assistant message text, its tool calls, and the results of those tool calls.
*/
private
renderOneToolCallRound
(
:
IToolCallRound
,
:
number
,
:
number
,
:
IInstantiationService
,
:
SharedImageBudget
,
?
:
CancellationToken
)
:
PromptElement
[
]
{
let
=
.
toolCalls
.
map
(
=>
(
{
...
,
:
this
.
toolsService
.
validateToolName
(
.
name
)
??
.
name
}
)
)
;
// A Responses marker retains every function call server-side. Close calls whose local
// results were lost so the next request can safely reuse previous_response_id.
const
=
this
.
props
.
isHistorical
&&
this
.
promptEndpoint
.
apiType
===
'responses'
&&
!
!
.
statefulMarker
;
if
(
this
.
props
.
isHistorical
)
{
=
.
filter
(
=>
.
id
&&
(
this
.
props
.
toolCallResults
?.
[
.
id
]
||
)
)
;
}
if
(
.
toolCalls
.
length
&&
!
.
length
)
{
return
[
]
;
}
const
:
Required
<
ToolCall
>
[
]
=
.
map
(
=>
(
{
:
'function'
,
function
:
{
:
.
name
,
:
.
arguments
}
,
:
.
id
!
,
:
useKeepWith
(
)
,
}
)
)
;
const
:
PromptElement
[
]
=
[
]
;
// Don't include this when rendering and triggering summarization
// Strip images from historical turns to avoid 413 errors
:
!
!
this
.
props
.
isHistorical
,
,
:
??
CancellationToken
.
None
,
}
)
}
</KeepWith>
,
)
;
}
// If a hook added context after this round, render it as a user message
if
(
.
hookContext
)
{
.
push
(
<UserMessage>
{
.
hookContext
}
</UserMessage>
)
;
}
return
;
}
}
/**
* Half the CAPI body-size limit (5 MB), used to cap image data so the rest
* of the prompt still fits. Shared by both the per-tool and cross-tool budgets.
*/
const
CAPI_IMAGE_BUDGET_BYTES
=
(
5
*
1024
*
1024
)
/
2
;
/**
* Shared mutable counter that limits the total image data rendered across
* all tool results within a turn, preventing 413 (request too large) errors
* when many image-returning tools (e.g. view_image) run in parallel.
*/
interface
SharedImageBudget
{
:
number
;
}
interface
ToolResultOpts
{
readonly
:
IToolCall
;
readonly
:
ChatParticipantToolToken
|
undefined
;
readonly
:
LanguageModelToolResult2
|
undefined
;
readonly
?
:
boolean
;
readonly
?
:
boolean
;
readonly
?
:
string
;
readonly
:
CopilotToolMode
;
readonly
:
boolean
;
readonly
:
boolean
;
readonly
?
:
number
;
readonly
:
string
|
undefined
;
readonly
?
:
boolean
;
readonly
?
:
SharedImageBudget
;
readonly
:
CancellationToken
;
}
const
=
'\nPlease check your input and try again.'
;
/**
* Creates a <ToolResult /> element. Eagerly starts the tool call if we know
* that the tool will not need/consume sizing information (e.g. MCP calls) and
* therefore don't need to wait for other elements to sequentially render.
*/
function
buildToolResultElement
(
:
ServicesAccessor
,
:
ToolResultOpts
)
{
const
:
IToolsService
=
.
get
(
IToolsService
)
;
const
:
ILogService
=
.
get
(
ILogService
)
;
const
:
ITelemetryService
=
.
get
(
ITelemetryService
)
;
const
:
IEndpointProvider
=
.
get
(
IEndpointProvider
)
;
const
:
IPromptEndpoint
=
.
get
(
IPromptEndpoint
)
;
const
:
IBuildPromptContext
=
.
get
(
IBuildPromptContext
)
;
const
=
.
get
(
ISessionTranscriptService
)
;
const
=
.
get
(
IChatHookService
)
;
const
=
.
get
(
IOTelService
)
;
const
=
.
get
(
IInstantiationService
)
;
const
=
.
getTool
(
.
toolCall
.
name
)
;
async
function
getToolResult
(
:
PromptSizing
)
{
const
:
LanguageModelToolTokenizationOptions
=
{
:
.
tokenBudget
,
countTokens
:
async
(
:
string
)
=>
.
countTokens
(
)
,
}
;
if
(
!
.
toolCallResult
&&
!
.
allowInvokingTool
)
{
throw
new
Error
(
`Missing tool call result for "${props.toolCall.id}" (${props.toolCall.name})`
)
;
}
const
:
PromptMetadata
[
]
=
[
]
;
let
=
false
;
let
=
.
toolCallResult
;
const
=
.
getCopilotTool
(
.
toolCall
.
name
as
ToolName
)
;
if
(
===
undefined
)
{
let
:
unknown
;
let
:
ToolValidationOutcome
=
ToolValidationOutcome
.
Unknown
;
if
(
.
validateInput
)
{
const
=
.
validateToolInput
(
.
toolCall
.
name
,
.
toolCall
.
arguments
)
;
if
(
'error'
in
)
{
=
ToolValidationOutcome
.
Invalid
;
.
push
(
new
ToolFailureEncountered
(
.
toolCall
.
id
)
)
;
=
textToolResult
(
.
error
+
)
;
}
else
{
=
ToolValidationOutcome
.
Valid
;
=
.
inputObj
;
}
}
else
{
=
JSON
.
parse
(
.
toolCall
.
arguments
)
;
}
let
:
ToolInvocationOutcome
=
===
undefined
?
ToolInvocationOutcome
.
Success
:
ToolInvocationOutcome
.
InvalidInput
;
if
(
===
undefined
)
{
try
{
if
(
.
tools
&&
!
.
tools
.
availableTools
.
find
(
=>
.
name
===
.
toolCall
.
name
)
)
{
=
ToolInvocationOutcome
.
DisabledByUser
;
throw
new
Error
(
`Tool ${props.toolCall.name} is currently disabled by the user, and cannot be called.`
)
;
}
if
(
?.
)
{
=
await
.
resolveInput
(
,
,
.
toolCallMode
)
;
}
// Execute preToolUse hook before invoking the tool
const
=
await
.
executePreToolUseHook
(
.
toolCall
.
name
,
,
.
toolCall
.
id
,
.
request
?.
,
.
conversation
?.
,
.
token
,
.
stream
)
;
// Apply updatedInput from hook (input modification takes effect before invocation)
if
(
?.
)
{
=
.
updatedInput
;
}
const
=
getSubAgentInvocationId
(
)
;
// Capture the active trace context (from the invoke_agent span) so that
// the execute_tool span is properly parented even when async context
// propagation doesn't carry the active span.
const
=
.
getActiveTraceContext
(
)
;
const
:
LanguageModelToolInvocationOptions
<
unknown
>
=
{
:
,
:
.
toolInvocationToken
,
,
:
.
requestId
,
,
// Split on `__vscode` so it's the chat stream id
// TODO @lramos15 - This is a gross hack
:
.
toolCall
.
id
.
split
(
'__vscode'
)
[
0
]
,
:
?
{
:
.
permissionDecision
,
:
.
permissionDecisionReason
,
:
.
updatedInput
,
}
:
undefined
,
}
;
// Attach trace context for span parenting (not in the VS Code API type)
(
as
{
?
:
{
:
string
;
:
string
}
}
)
.
parentTraceContext
=
;
const
=
.
conversation
?.
;
if
(
)
{
let
:
unknown
;
try
{
=
JSON
.
parse
(
.
toolCall
.
arguments
)
;
}
catch
{
=
.
toolCall
.
arguments
;
}
.
logToolExecutionStart
(
,
.
toolCall
.
id
,
.
toolCall
.
name
,
)
;
}
=
await
.
invokeToolWithEndpoint
(
.
toolCall
.
name
,
,
,
.
token
)
;
sendInvokedToolTelemetry
(
,
,
,
.
toolCall
.
name
,
,
{
:
.
conversation
?.
,
:
.
requestId
,
}
)
;
// Run hook context handling after tool execution
appendHookContext
(
,
,
,
,
,
)
;
if
(
)
{
.
logToolExecutionComplete
(
,
.
toolCall
.
id
,
true
)
;
}
}
catch
(
)
{
const
=
toolCallErrorToResult
(
)
;
=
.
result
;
=
.
isCancelled
??
false
;
if
(
.
isCancelled
)
{
=
ToolInvocationOutcome
.
Cancelled
;
}
else
{
=
===
ToolInvocationOutcome
.
DisabledByUser
?
:
ToolInvocationOutcome
.
Error
;
.
push
(
new
ToolFailureEncountered
(
.
toolCall
.
id
)
)
;
.
error
(
`Error from tool ${props.toolCall.name} with args ${props.toolCall.arguments}`
/* __GDPR__
"toolInvoke" : {
"owner": "donjayamanne",
"comment": "Details about invocation of tools",
"validateOutcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the tool input validation. valid, invalid and unknown" },
"invokeOutcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the tool Invokcation. invalidInput, disabledByUser, success, error, cancelled" },
"toolName": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The name of the tool being invoked." },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model that invoked the tool" }
}
*/
.
sendMSFTTelemetryEvent
(
'toolInvoke'
,
{
,
,
,
}
)
;
if
(
===
ToolName
.
EditNotebook
)
{
sendNotebookEditToolValidationTelemetry
(
,
,
.
toolCall
.
arguments
,
,
)
;
}
}
interface
IToolResultElementActualProps
{
call
(
:
PromptSizing
)
:
Promise
<
{
:
LanguageModelToolResult2
;
:
boolean
;
:
PromptMetadata
[
]
;
}
>
;
:
boolean
;
:
number
|
undefined
;
:
IToolCall
;
:
string
|
undefined
;
:
boolean
;
?
:
boolean
;
?
:
SharedImageBudget
;
}
function
buildImageUri
(
:
string
|
undefined
,
:
string
|
undefined
,
:
number
|
undefined
,
:
string
)
:
string
|
undefined
{
if
(
!
||
!
||
===
undefined
)
{
return
undefined
;
}
const
=
.
split
(
'__vscode'
)
[
0
]
;
return
buildToolImageResourceUri
(
,
,
,
getExtensionForMimeType
(
)
??
'.bin'
)
;
}
/**
* Replaces image data parts with text placeholders in tool results.
* Used for historical turns to prevent large base64 image data from
* accumulating and causing 413 (request too large) errors from the API.
*/
function
replaceImagesWithPlaceholders
(
:
LanguageModelToolResult2
[
'content'
]
,
:
string
|
undefined
,
:
string
|
undefined
,
)
:
LanguageModelToolResult2
[
'content'
]
{
if
(
!
.
some
(
=>
isImageDataPart
(
)
)
)
{
return
;
}
return
.
map
(
(
,
)
=>
{
if
(
!
isImageDataPart
(
)
)
{
return
;
}
const
=
buildImageUri
(
,
,
,
.
mimeType
)
;
const
=
?
` Image URI: ${uri}`
:
''
;
return
new
LanguageModelTextPart
(
`[Image was previously shown to you.${uriRef}]`
)
;
}
)
;
}
/**
* One tool call result, which either comes from the cache or from invoking the tool.
*/
// Override the token budget to Infinity for telemetry counting to avoid truncation,
// matching the prior behavior with modelMaxPromptTokens: Infinity
const
:
IChatEndpoint
=
{
...
,
:
.
tokenizer
,
:
Infinity
,
}
;
PromptRenderer
.
create
(
,
,
class
extends
PromptElement
{
render
(
)
{
return
<UserMessage>
<PrimitiveToolResult content=
{
.
content
}
/>
</UserMessage>
;
}
}
,
{
}
,
)
.
render
(
)
.
then
(
(
{
}
)
=>
{
/* __GDPR__
"agent.tool.responseLength" : {
"owner": "connor4312",
"comment": "Counts the number of tokens generated by tools",
"conversationId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Id for the current chat conversation." },
"requestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Id for the current chat request." },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model that invoked the tool." },
"toolName": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The name of the tool being invoked." },
"tokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "comment": "Number of tokens used.", "isMeasurement": true }
}
*/
.
sendMSFTTelemetryEvent
(
'agent.tool.responseLength'
,
{
...
,
:
.
model
,
}
,
{
}
)
;
}
)
;
}
enum
ToolValidationOutcome
{
Valid
=
'valid'
,
Invalid
=
'invalid'
,
Unknown
=
'unknown'
}
enum
ToolInvocationOutcome
{
InvalidInput
=
'invalidInput'
,
DisabledByUser
=
'disabledByUser'
,
Success
=
'success'
,
Error
=
'error'
,
Cancelled
=
'cancelled'
,
}
export
async
function
imageDataPartToTSX
(
:
LanguageModelDataPart
,
?
:
string
,
?
:
string
|
RequestMetadata
,
?
:
ILogService
,
?
:
IImageService
)
{
if
(
isImageDataPart
(
)
)
{
let
:
Uint8Array
=
.
data
;
let
=
.
mimeType
;
if
(
)
{
try
{
const
=
await
.
resizeImage
(
,
)
;
=
.
data
;
=
.
mimeType
;
}
catch
(
)
{
?.
warn
(
`Image resize failed, using original: ${error}`
)
;
}
}
const
=
Buffer
.
from
(
)
.
toString
(
'base64'
)
;
let
=
`data:${mimeType};base64,${base64}`
;
const
=
typeof
!==
'string'
&&
(
?.
===
RequestType
.
ChatCompletions
||
?.
===
RequestType
.
ChatResponses
||
?.
===
RequestType
.
ChatMessages
)
;
if
(
&&
&&
)
{
try
{
const
=
await
.
uploadChatImageAttachment
(
,
'tool-result-image'
,
??
'image/png'
,
)
;
if
(
)
{
=
.
toString
(
)
;
}
}
catch
(
)
{
if
(
)
{
.
warn
(
`Image upload failed, using base64 fallback: ${error}`
)
;
}
}
}
return
<Imagesrc={imageSource}mimeType={mimeType}/>
;
}
}
/**
* Appends hook context to a tool result after execution.
* Handles preToolUse additionalContext and executes the postToolUse hook,
* appending block messages and additionalContext as `<*-context>` tags.
*/
async
function
appendHookContext
(
:
LanguageModelToolResult2
,
:
IPreToolUseHookResult
|
undefined
,
:
IChatHookService
,
:
ToolResultOpts
,
:
unknown
,
:
IBuildPromptContext
,
)
:
Promise
<
void
>
{
// Append additional context from preToolUse hook
if
(
?.
)
{
for
(
const
of
.
additionalContext
)
{
.
content
.
push
(
new
LanguageModelTextPart
(
'\n<PreToolUse-context>\n'
+
+
'\n</PreToolUse-context>'
)
)
;
}
}
// Skip postToolUse hook if preToolUse denied the tool — no tool actually ran
if
(
?.
===
'deny'
)
{
return
;
}
// Skip postToolUse hook if the request was cancelled - the response stream is closed
if
(
.
token
.
isCancellationRequested
)
{
return
;
}
// Execute postToolUse hook after successful tool execution
const
=
await
.
executePostToolUseHook
(
.
toolCall
.
name
,
,
toolResultToText
(
)
,
.
toolCall
.
id
,
.
request
?.
,
.
conversation
?.
,
.
token
,
.
stream
)
;
if
(
?.
===
'block'
)
{
const
=
.
reason
??
'Hook blocked tool result'
;
const
=
`The PostToolUse hook blocked this tool result. Reason: ${blockReason}`
;
.
content
.
push
(
new
LanguageModelTextPart
(
'\n<PostToolUse-context>\n'
+
+
'\n</PostToolUse-context>'
)
)
;
}
if
(
?.
)
{
for
(
const
of
.
additionalContext
)
{
.
content
.
push
(
new
LanguageModelTextPart
(
'\n<PostToolUse-context>\n'
+
+
'\n</PostToolUse-context>'
)
)
;
}
}
}
function
toolResultToText
(
:
LanguageModelToolResult2
)
:
string
{
return
.
content
.
filter
(
(
)
:
is
LanguageModelTextPart
|
LanguageModelTextPart2
=>
instanceof
LanguageModelTextPart
||
instanceof
LanguageModelTextPart2
)
.
map
(
=>
.
value
)
.
join
(
'\n'
)
;
}
function
textToolResult
(
:
string
)
:
LanguageModelToolResult
{
return
new
LanguageModelToolResult
(
[
new
LanguageModelTextPart
(
)
]
)
;
}
export
function
toolCallErrorToResult
(
:
unknown
)
{
if
(
isCancellationError
(
)
)
{
return
{
:
textToolResult
(
'The user cancelled the tool call.'
)
,
:
true
}
;
}
else
{
const
=
instanceof
Error
?
.
message
:
String
(
)
;
return
{
:
textToolResult
(
`ERROR while calling tool: ${errorMessage}${toolErrorSuffix}`
)
}
;
}
}
export
class
ToolFailureEncountered
extends
PromptMetadata
{
constructor
(
public
:
string
)
{
super
(
)
;
}
}
export
class
ToolResultMetadata
extends
PromptMetadata
{
constructor
(
public
readonly
:
string
,
public
readonly
:
LanguageModelToolResult2
,
public
?
:
boolean
)
{
super
(
)
;
}
}
// Some MCP servers return a ton of resources as a 'download' action.
// Only include them all eagerly if we have a manageable number.
/**
* Some models do not yet support CAPI image uploads. For these cases,
* track the number of images bytes we're sending and truncate any images
* that would exceed that budget.
*/
private
=
CAPI_IMAGE_BUDGET_BYTES
;
constructor
(
:
T
,
IPromptEndpoint
protected
readonly
?
:
IPromptEndpoint
,
IAuthenticationService
private
readonly
?
:
IAuthenticationService
,
ILogService
private
readonly
?
:
ILogService
,
IImageService
private
readonly
?
:
IImageService
,
IConfigurationService
private
readonly
?
:
IConfigurationService
)
{
super
(
)
;
this
.
linkedResources
=
this
.
props
.
content
.
filter
(
(
)
:
is
LanguageModelDataPart
=>
instanceof
LanguageModelDataPart
&&
.
mimeType
===
McpLinkedResourceToolResult
.
mimeType
)
;
}
async
render
(
)
:
Promise
<
PromptPiece
|
undefined
>
{
return
(
<>
<IfEmptyalt='(empty)'>
{
await
Promise
.
all
(
this
.
props
.
content
.
filter
(
=>
this
.
hasAssistantAudience
(
)
)
.
map
(
async
=>
{
if
(
instanceof
LanguageModelTextPart
)
{
return
await
this
.
onText
(
.
value
)
;
}
else
if
(
instanceof
LanguageModelPromptTsxPart
)
{
return
await
this
.
onTSX
(
.
value
as
JSONTree
.
PromptElementJSON
)
;
}
else
if
(
isImageDataPart
(
)
)
{
return
await
this
.
onImage
(
,
this
.
props
.
content
.
indexOf
(
)
)
;
}
else
if
(
instanceof
LanguageModelDataPart
)
{
return
await
this
.
onData
(
)
;
}
}
)
)
}
{
this
.
linkedResources
.
length
>
0
&&
`\n\nHint: you can read the full contents of any ${this.linkedResources.length >DONT_INCLUDE_RESOURCE_CONTENT_IF_TOOL_HAS_MORE_THAN?'':'truncated '}resources by passing their URIs as the absolutePath to the ${ToolName.ReadFile}.\n`
}
</IfEmpty>
</>
)
;
}
private
hasAssistantAudience
(
:
LanguageModelTextPart2
|
LanguageModelPromptTsxPart
|
LanguageModelDataPart2
|
unknown
)
:
boolean
{
if
(
instanceof
LanguageModelPromptTsxPart
)
{
return
true
;
}
if
(
!
(
instanceof
LanguageModelDataPart2
||
instanceof
LanguageModelTextPart2
)
||
!
.
audience
)
{
return
true
;
}
return
.
audience
.
includes
(
LanguageModelPartAudience
.
Assistant
)
;
}
protected
async
onData
(
:
LanguageModelDataPart
)
{
if
(
.
mimeType
===
McpLinkedResourceToolResult
.
mimeType
)
{
return
this
.
onResourceLink
(
new
TextDecoder
(
)
.
decode
(
.
data
)
)
;
}
else
{
return
''
;
}
}
protected
async
onImage
(
:
LanguageModelDataPart
,
?
:
number
)
{
if
(
!
this
.
endpoint
?.
)
{
return
'[Image content is not available because vision is not supported by the current model.]'
;
}
const
=
this
.
configurationService
?
this
.
configurationService
.
getConfig
(
ConfigKey
.
EnableChatImageUpload
)
:
false
;
// Anthropic (from CAPI) currently does not support image uploads from tool calls.
const
=
&&
!
!
this
.
endpoint
&&
modelCanUseMcpResultImageURL
(
this
.
endpoint
)
;
// Enforce image budgets only when images will be inlined as base64.
// When uploads are available, the request body stays small (URL reference).
if
(
!
)
{
// Enforce shared cross-tool budget (prevents 413s when many tools return images)
const
=
this
.
props
.
sharedImageBudget
;
if
(
)
{
if
(
.
remaining
<
0
)
{
return
this
.
sharedBudgetPlaceholder
(
)
;
}
else
if
(
.
data
.
length
>
.
remaining
)
{
.
remaining
=
-
1
;
return
this
.
sharedBudgetPlaceholder
(
)
;
}
.
remaining
-=
.
data
.
length
;
}
// Enforce per-tool budget
if
(
this
.
imageSizeBudgetLeft
<
0
)
{
return
''
;
// already exceeded and messages about it
}
else
if
(
.
data
.
length
>
this
.
imageSizeBudgetLeft
)
{
this
.
imageSizeBudgetLeft
=
-
1
;
// just now exceeding
return
'Additional images are available, but there is no more space in the context. Try requesting a smaller amount of data, if possible.'
;
}
else
{
this
.
imageSizeBudgetLeft
-=
.
data
.
length
;
// bookkeep
}
}
// Only call getGitHubSession when uploads are potentially available
/**
* Number of tokens at which truncation will be triggered for string content.
*/
?
:
number
;
/**
* The tool call associated with this result.
*/
:
string
|
undefined
;
/**
* The session ID associated with this result.
*/
?
:
string
;
/**
* The name of the tool that produced this result.
*/
?
:
string
;
}
/**
* Inlined from prompt-tsx. In prompt-tsx it does `require('vscode)` for the instanceof checks which breaks in vitest
* and unfortunately I can't figure out how to work around that with the tools we have!
*/
export
class
ToolResult
extends
PrimitiveToolResult<IToolResultProps>
{
constructor
(
:
IToolResultProps
,
IPromptEndpoint
:
IPromptEndpoint
,
IAuthenticationService
:
IAuthenticationService
,
ILogService
private
readonly
:
ILogService
,
IImageService
:
IImageService
,
IConfigurationService
private
readonly
:
IConfigurationService
,
IExperimentationService
private
readonly
:
IExperimentationService
,
IChatDiskSessionResources
private
readonly
:
IChatDiskSessionResources
,
)
{
super
(
,
,
,
,
,
)
;
}
protected
async
onTSX
(
:
JSONTree
.
PromptElementJSON
)
:
Promise
<
any
>
{
if
(
this
.
props
.
truncate
)
{
return
<TokenLimitmax={this.props.truncate}>
{
await
super
.
onTSX
(
)
}
</TokenLimit>
;
}
return
super
.
onTSX
(
)
;
}
protected
async
onImage
(
:
LanguageModelDataPart
,
?
:
number
)
:
Promise
<
PromptPiece
|
undefined
>
{
const
=
await
super
.
onImage
(
,
)
;
if
(
!
||
===
undefined
||
!
this
.
props
.
toolCallId
||
!
this
.
props
.
sessionId
)
{
return
;
}
const
=
buildImageUri
(
this
.
props
.
sessionId
,
this
.
props
.
toolCallId
,
,
.
mimeType
)
;
return
<>
{
}
{
&&
`\n[Image URI: ${uri}]`
}
</>
;
}
protected
sharedBudgetPlaceholder
(
)
:
string
{
return
'[Image omitted — context image budget exceeded. Try viewing fewer images at once or reference this image by URI.]'
;
}
protected
async
onText
(
:
string
)
:
Promise
<
string
>
{
const
=
this
.
_configurationService
.
getExperimentBasedConfig
(
ConfigKey
.
Advanced
.
LargeToolResultsToDiskEnabled
,
this
.
_experimentationService
)
;
// Exempt the search and execution subagents and memory tool from disk caching as their results are often ignored if not written directly to the conversation
if
(
&&
this
.
diskSessionResources
&&
this
.
props
.
toolCallId
&&
this
.
props
.
sessionId
&&
this
.
props
.
toolName
!==
ToolName
.
SearchSubagent
&&
this
.
props
.
toolName
!==
ToolName
.
ExploreSubagent
&&
this
.
props
.
toolName
!==
ToolName
.
ExecutionSubagent
&&
this
.
props
.
toolName
!==
ToolName
.
Memory
)
{
const
=
this
.
_configurationService
.
getExperimentBasedConfig
(
ConfigKey
.
Advanced
.
LargeToolResultsToDiskThreshold
,
this
.
_experimentationService
)
;
if
(
.
length
>
)
{
try
{
const
=
this
.
props
.
sessionId
??
'unknown'
;
const
=
this
.
props
.
toolCallId
;
let
=
'content.txt'
;
let
:
string
|
undefined
;
try
{
const
=
JSON
.
parse
(
)
;
=
JSON
.
stringify
(
toJsonSchema
(
)
)
;
// re-stringify it as it's more friendly to line-based offsets in the read_file tool
=
JSON
.
stringify
(
,
null
,
2
)
;
=
'content.json'
;
}
catch
{
// ignored
}
const
=
await
this
.
diskSessionResources
.
ensure
(
,
,
{
[
]
:
,
'schema.json'
:
}
,
)
;
const
=
.
fsPath
;
const
=
URI
.
joinPath
(
,
)
;
const
=
?
URI
.
joinPath
(
,
'schema.json'
)
:
undefined
;
this
.
_logService
?.
debug
(
`[ToolResult] Large tool result (${content.length} bytes) written to disk: ${filePath}`
)
;
return
`Large tool result (${Math.round(content.length /1024)}KB) written to file. Use the ${ToolName.ReadFile} tool to access the content at: ${contentFileUri.fsPath}${schemaFileUri ?`\n\nData schema found at: ${schemaFileUri.fsPath}`:''}`
;
}
catch
(
)
{
this
.
_logService
?.
warn
(
`[ToolResult] Failed to write large tool result to disk: ${toErrorMessage(err)}`
)
;
// Fall through to normal truncation
}
}
}
// Standard truncation logic
const
=
this
.
props
.
truncate
;
if
(
!
||
.
length
<
)
{
// always >=1 character per token, early bail-out
return
;
}
const
=
await
this
.
endpoint
?.
acquireTokenizer
(
)
.
tokenLength
(
)
;
if
(
!
||
tokens< truncateAtTokens){return content;}const approxCharsPerToken = content.length / tokens;const removedMessage ='\n[Tool response was too long and was truncated.]\n';const targetChars = Math.round(approxCharsPerToken *(truncateAtTokens - removedMessage.length));const keepInFirstHalf = Math.round(targetChars *0.4);const keepInSecondHalf = targetChars - keepInFirstHalf;return content.slice(0, keepInFirstHalf)+ removedMessage + content.slice(-keepInSecondHalf);}protected override onResourceLink(data:string){// https://github.com/microsoft/vscode/blob/34e38b4a78a751d006b99acee1a95d76117fec7b/src/vs/workbench/contrib/mcp/common/mcpTypes.ts#L846let parsed:{
uri: UriComponents;
underlyingMimeType?:string;};try{
parsed =JSON.parse(data);}catch{returnnull;}return<McpLinkedResourceToolResult resourceUri={URI.revive(parsed.uri)} mimeType={parsed.underlyingMimeType} count={this.linkedResources.length}/>;}}exportinterface IToolCallResultWrapperProps extends BasePromptElementProps {
toolCallResults: IResultMetadata['toolCallResults'];}// Wrapper around ToolResult to allow rendering promptsexportclass ToolCallResultWrapper extends PromptElement<IToolCallResultWrapperProps>{asyncrender():Promise<PromptPiece |undefined>{return(<>{Object.entries(this.props.toolCallResults ??{}).map(([toolCallId, toolCallResult])=>
/* __GDPR__
"editNotebook.validation" : {
"owner": "donjayamanne",
"comment": "Validation failure for a Edit Notebook tool invocation",
"validationResult": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The result of the tool input validation. valid, invalid and unknown" },
"invokeOutcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The result of the tool Invocation. invalidInput, disabledByUser, success, error, cancelled" },
"editType": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The type of edit that was attempted. insert, delete, edit or unknown" },
"unknownProps": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "List of unknown properties in the input" },
"missingProps": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "List of missing properties in the input" },
"newCodeType": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The type of code, whether its string, string[], object, object[] or unknown" },
"cellId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The id of the cell, TOP, BOTTOM, cellid, empty or unknown" },
"explanation": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The explanation for the edit. provided, empty and unknown" },
"inputParsed": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Whether the input was parsed as JSON" },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model that invoked the tool" }
}
*/