forked from microsoft/vscode-copilot-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchSubagentTool.ts
More file actions
190 lines (161 loc) · 8.65 KB
/
Copy pathsearchSubagentTool.ts
File metadata and controls
190 lines (161 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as l10n from '@vscode/l10n';
import type * as vscode from 'vscode';
import { ChatFetchResponseType } from '../../../platform/chat/common/commonTypes';
import { ConfigKey, IConfigurationService } from '../../../platform/configuration/common/configurationService';
import { TextDocumentSnapshot } from '../../../platform/editing/common/textDocumentSnapshot';
import { CapturingToken } from '../../../platform/requestLogger/common/capturingToken';
import { IRequestLogger } from '../../../platform/requestLogger/node/requestLogger';
import { IExperimentationService } from '../../../platform/telemetry/common/nullExperimentationService';
import { IWorkspaceService } from '../../../platform/workspace/common/workspaceService';
import { ChatResponseStreamImpl } from '../../../util/common/chatResponseStreamImpl';
import { URI } from '../../../util/vs/base/common/uri';
import { generateUuid } from '../../../util/vs/base/common/uuid';
import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation';
import { ChatResponseNotebookEditPart, ChatResponseTextEditPart, ChatToolInvocationPart, ExtendedLanguageModelToolResult, LanguageModelTextPart, MarkdownString, Range } from '../../../vscodeTypes';
import { Conversation, Turn } from '../../prompt/common/conversation';
import { IBuildPromptContext } from '../../prompt/common/intents';
import { SearchSubagentToolCallingLoop } from '../../prompt/node/searchSubagentToolCallingLoop';
import { ToolName } from '../common/toolNames';
import { CopilotToolMode, ICopilotTool, ToolRegistry } from '../common/toolsRegistry';
export interface ISearchSubagentParams {
/** Natural language query describing what to search for */
query: string;
/** User-visible description shown while invoking */
description: string;
/** Detailed instructions regarding the search subagent's objective */
details: string;
}
class SearchSubagentTool implements ICopilotTool<ISearchSubagentParams> {
public static readonly toolName = ToolName.SearchSubagent;
private _inputContext: IBuildPromptContext | undefined;
constructor(
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IRequestLogger private readonly requestLogger: IRequestLogger,
@IWorkspaceService private readonly workspaceService: IWorkspaceService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExperimentationService private readonly experimentationService: IExperimentationService
) { }
async invoke(options: vscode.LanguageModelToolInvocationOptions<ISearchSubagentParams>, token: vscode.CancellationToken) {
const searchInstruction = [
`Find relevant code snippets for: ${options.input.query}`,
'',
'More detailed instructions: ',
`${options.input.details}`,
'',
].join('\n');
const request = this._inputContext!.request!;
const parentSessionId = this._inputContext?.conversation?.sessionId ?? generateUuid();
// Generate a stable session ID for this subagent invocation that will be used:
// 1. As subAgentInvocationId in the subagent's tool context
// 2. As subAgentInvocationId in toolMetadata for parent trajectory linking
// 3. As the session_id in the subagent's own trajectory
const subAgentInvocationId = generateUuid();
const toolCallLimit = this.configurationService.getExperimentBasedConfig(ConfigKey.Advanced.SearchSubagentToolCallLimit, this.experimentationService);
const loop = this.instantiationService.createInstance(SearchSubagentToolCallingLoop, {
toolCallLimit,
conversation: new Conversation(parentSessionId, [new Turn(generateUuid(), { type: 'user', message: searchInstruction })]),
request: request,
location: request.location,
promptText: options.input.query,
subAgentInvocationId: subAgentInvocationId,
});
const stream = this._inputContext?.stream && ChatResponseStreamImpl.filter(
this._inputContext.stream,
part => part instanceof ChatToolInvocationPart || part instanceof ChatResponseTextEditPart || part instanceof ChatResponseNotebookEditPart
);
// Create a new capturing token to group this search subagent and all its nested tool calls
// Similar to how DefaultIntentRequestHandler does it
// Pass the subAgentInvocationId so the trajectory uses this ID for explicit linking
const searchSubagentToken = new CapturingToken(
`Search: ${options.input.query.substring(0, 50)}${options.input.query.length > 50 ? '...' : ''}`,
'search',
false,
false,
subAgentInvocationId,
'search' // subAgentName for trajectory tracking
);
// Wrap the loop execution in captureInvocation with the new token
// All nested tool calls will now be logged under this same CapturingToken
const loopResult = await this.requestLogger.captureInvocation(searchSubagentToken, () => loop.run(stream, token));
// Build subagent trajectory metadata that will be logged via toolMetadata
// All nested tool calls are already logged by ToolCallingLoop.logToolResult()
const toolMetadata = {
query: options.input.query,
description: options.input.description,
// The subAgentInvocationId links this tool call to the subagent's trajectory
subAgentInvocationId: subAgentInvocationId,
agentName: 'search'
};
let subagentResponse = '';
if (loopResult.response.type === ChatFetchResponseType.Success) {
subagentResponse = loopResult.toolCallRounds.at(-1)?.response ?? loopResult.round.response ?? '';
} else {
subagentResponse = `The search subagent request failed with this message:\n${loopResult.response.type}: ${loopResult.response.reason}`;
}
// Parse and hydrate code snippets from <final_answer> tags
const hydratedResponse = await this.parseFinalAnswerAndHydrate(subagentResponse, token);
// toolMetadata will be automatically included in exportAllPromptLogsAsJsonCommand
const result = new ExtendedLanguageModelToolResult([new LanguageModelTextPart(hydratedResponse)]);
result.toolMetadata = toolMetadata;
result.toolResultMessage = new MarkdownString(l10n.t`Search complete: ${options.input.description}`);
return result;
}
/**
* Parse the path and line range subagent response and hydrate code snippets
* @param response The subagent response containing paths and line ranges
* @param token Cancellation token
* @returns The response with actual code snippets appended to file paths
*/
private async parseFinalAnswerAndHydrate(response: string, token: vscode.CancellationToken): Promise<string> {
const lines = response.split('\n');
// Parse file:line-line format
const fileRangePattern = /^(.+):(\d+)-(\d+)$/;
const processedLines: string[] = [];
for (const line of lines) {
const trimmedLine = line.trim();
const match = trimmedLine.match(fileRangePattern);
if (!match) {
// I decided to keep non-matching lines as-is, since non-SFTed models sometimes return added info
processedLines.push(line);
continue;
}
const [, filePath, startLineStr, endLineStr] = match;
const startLine = parseInt(startLineStr, 10);
const endLine = parseInt(endLineStr, 10);
try {
const uri = URI.file(filePath);
const document = await this.workspaceService.openTextDocument(uri);
const snapshot = TextDocumentSnapshot.create(document);
const clampedStartLine = Math.max(1, Math.min(startLine, snapshot.lineCount));
const clampedEndLine = Math.max(1, Math.min(endLine, snapshot.lineCount));
const range = new Range(
clampedStartLine - 1, 0,
clampedEndLine - 1, Number.MAX_SAFE_INTEGER
);
const code = snapshot.getText(range);
processedLines.push(`File: \`${filePath}\`, lines ${clampedStartLine}-${clampedEndLine}:\n\`\`\`\n${code}\n\`\`\``);
} catch (err) {
// If we can't read the file, keep the original line
processedLines.push(`${trimmedLine} (unable to read file: ${err})`);
}
if (token.isCancellationRequested) {
break;
}
}
return processedLines.join('\n');
}
prepareInvocation(options: vscode.LanguageModelToolInvocationPrepareOptions<ISearchSubagentParams>, _token: vscode.CancellationToken): vscode.ProviderResult<vscode.PreparedToolInvocation> {
return {
invocationMessage: options.input.description,
};
}
async resolveInput(input: ISearchSubagentParams, promptContext: IBuildPromptContext, _mode: CopilotToolMode): Promise<ISearchSubagentParams> {
this._inputContext = promptContext;
return input;
}
}
ToolRegistry.registerTool(SearchSubagentTool);