-
Notifications
You must be signed in to change notification settings - Fork 39.3k
Expand file tree
/
Copy pathcopilotShellTools.ts
More file actions
561 lines (497 loc) · 19.2 KB
/
copilotShellTools.ts
File metadata and controls
561 lines (497 loc) · 19.2 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { Tool, ToolResultObject } from '@github/copilot-sdk';
import { generateUuid } from '../../../../base/common/uuid.js';
import { URI } from '../../../../base/common/uri.js';
import { removeAnsiEscapeCodes } from '../../../../base/common/strings.js';
import * as platform from '../../../../base/common/platform.js';
import { DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js';
import { Emitter, Event } from '../../../../base/common/event.js';
import { ILogService } from '../../../log/common/log.js';
import { TerminalClaimKind, type ITerminalSessionClaim } from '../../common/state/protocol/state.js';
import { IAgentHostTerminalManager } from '../agentHostTerminalManager.js';
/**
* Maximum scrollback content (in bytes) returned to the model in tool results.
*/
const MAX_OUTPUT_BYTES = 80_000;
/**
* Default command timeout in milliseconds (120 seconds).
*/
const DEFAULT_TIMEOUT_MS = 120_000;
/**
* The sentinel prefix used to detect command completion in terminal output.
* The full sentinel format is: `<<<COPILOT_SENTINEL_<uuid>_EXIT_<code>>>`.
*/
const SENTINEL_PREFIX = '<<<COPILOT_SENTINEL_';
/**
* Tracks a single persistent shell instance backed by a managed PTY terminal.
*/
interface IManagedShell {
readonly id: string;
readonly terminalUri: string;
readonly shellType: ShellType;
}
export type ShellType = 'bash' | 'powershell';
function getShellExecutable(shellType: ShellType): string {
if (shellType === 'powershell') {
return 'powershell.exe';
}
return process.env['SHELL'] || '/bin/bash';
}
// ---------------------------------------------------------------------------
// ShellManager
// ---------------------------------------------------------------------------
/**
* Per-session manager for persistent shell instances. Each shell is backed by
* a {@link IAgentHostTerminalManager} terminal and participates in AHP terminal
* claim semantics.
*
* Created via {@link IInstantiationService} once per session and disposed when
* the session ends.
*/
export class ShellManager {
private readonly _shells = new Map<string, IManagedShell>();
private readonly _toolCallShells = new Map<string, string>();
private readonly _onDidAssociateTerminal = new Emitter<{ toolCallId: string; terminalUri: string; displayName: string }>();
readonly onDidAssociateTerminal: Event<{ toolCallId: string; terminalUri: string; displayName: string }> = this._onDidAssociateTerminal.event;
constructor(
private readonly _sessionUri: URI,
private readonly _workingDirectory: URI | undefined,
@IAgentHostTerminalManager private readonly _terminalManager: IAgentHostTerminalManager,
@ILogService private readonly _logService: ILogService,
) { }
async getOrCreateShell(
shellType: ShellType,
turnId: string,
toolCallId: string,
cwd?: string,
): Promise<IManagedShell> {
for (const shell of this._shells.values()) {
if (shell.shellType === shellType && this._terminalManager.hasTerminal(shell.terminalUri)) {
const exitCode = this._terminalManager.getExitCode(shell.terminalUri);
if (exitCode === undefined) {
this._trackToolCall(toolCallId, shell.id);
return shell;
}
this._shells.delete(shell.id);
}
}
const id = generateUuid();
const terminalUri = `agenthost-terminal://shell/${id}`;
const claim: ITerminalSessionClaim = {
kind: TerminalClaimKind.Session,
session: this._sessionUri.toString(),
turnId,
toolCallId,
};
const shellDisplayName = shellType === 'bash' ? 'Bash' : 'PowerShell';
await this._terminalManager.createTerminal({
terminal: terminalUri,
claim,
name: shellDisplayName,
cwd: cwd ?? this._workingDirectory?.fsPath,
}, { shell: getShellExecutable(shellType), preventShellHistory: true, nonInteractive: true });
const shell: IManagedShell = { id, terminalUri, shellType };
this._shells.set(id, shell);
this._trackToolCall(toolCallId, id);
this._logService.info(`[ShellManager] Created ${shellType} shell ${id} (terminal=${terminalUri})`);
return shell;
}
private _trackToolCall(toolCallId: string, shellId: string): void {
this._toolCallShells.set(toolCallId, shellId);
const shell = this._shells.get(shellId);
if (shell) {
const displayName = shell.shellType === 'bash' ? 'Bash' : 'PowerShell';
this._onDidAssociateTerminal.fire({ toolCallId, terminalUri: shell.terminalUri, displayName });
}
}
getTerminalUriForToolCall(toolCallId: string): string | undefined {
const shellId = this._toolCallShells.get(toolCallId);
if (!shellId) {
return undefined;
}
return this._shells.get(shellId)?.terminalUri;
}
getShell(id: string): IManagedShell | undefined {
return this._shells.get(id);
}
listShells(): IManagedShell[] {
const result: IManagedShell[] = [];
for (const shell of this._shells.values()) {
if (this._terminalManager.hasTerminal(shell.terminalUri)) {
result.push(shell);
}
}
return result;
}
shutdownShell(id: string): boolean {
const shell = this._shells.get(id);
if (!shell) {
return false;
}
this._terminalManager.disposeTerminal(shell.terminalUri);
this._shells.delete(id);
this._logService.info(`[ShellManager] Shut down shell ${id}`);
return true;
}
dispose(): void {
for (const shell of this._shells.values()) {
if (this._terminalManager.hasTerminal(shell.terminalUri)) {
this._terminalManager.disposeTerminal(shell.terminalUri);
}
}
this._shells.clear();
this._toolCallShells.clear();
}
}
// ---------------------------------------------------------------------------
// Sentinel helpers
// ---------------------------------------------------------------------------
function makeSentinelId(): string {
return generateUuid().replace(/-/g, '');
}
function buildSentinelCommand(sentinelId: string, shellType: ShellType): string {
if (shellType === 'powershell') {
return `Write-Output "${SENTINEL_PREFIX}${sentinelId}_EXIT_$LASTEXITCODE>>>"`;
}
return `echo "${SENTINEL_PREFIX}${sentinelId}_EXIT_$?>>>"`;
}
/**
* For POSIX shells (bash/zsh) that honor `HISTCONTROL=ignorespace` /
* `HIST_IGNORE_SPACE`, prepending a single space prevents the command from
* being recorded in shell history. The shell integration scripts opt these
* settings in via the `VSCODE_PREVENT_SHELL_HISTORY` env var (set when the
* terminal is created with `preventShellHistory: true`). PowerShell
* suppresses history through PSReadLine instead, so no prefix is needed.
*
* Exported for tests.
*/
export function prefixForHistorySuppression(shellType: ShellType): string {
return shellType === 'powershell' ? '' : ' ';
}
function parseSentinel(content: string, sentinelId: string): { found: boolean; exitCode: number; outputBeforeSentinel: string } {
const marker = `${SENTINEL_PREFIX}${sentinelId}_EXIT_`;
const idx = content.indexOf(marker);
if (idx === -1) {
return { found: false, exitCode: -1, outputBeforeSentinel: content };
}
const outputBeforeSentinel = content.substring(0, idx);
const afterMarker = content.substring(idx + marker.length);
const endIdx = afterMarker.indexOf('>>>');
const exitCodeStr = endIdx >= 0 ? afterMarker.substring(0, endIdx) : afterMarker.trim();
const exitCode = parseInt(exitCodeStr, 10);
return {
found: true,
exitCode: isNaN(exitCode) ? -1 : exitCode,
outputBeforeSentinel,
};
}
function prepareOutputForModel(rawOutput: string): string {
let text = removeAnsiEscapeCodes(rawOutput).trim();
if (text.length > MAX_OUTPUT_BYTES) {
text = text.substring(text.length - MAX_OUTPUT_BYTES);
}
return text;
}
// ---------------------------------------------------------------------------
// Tool implementations
// ---------------------------------------------------------------------------
function makeSuccessResult(text: string): ToolResultObject {
return { textResultForLlm: text, resultType: 'success' };
}
function makeFailureResult(text: string, error?: string): ToolResultObject {
return { textResultForLlm: text, resultType: 'failure', error };
}
async function executeCommandInShell(
shell: IManagedShell,
command: string,
timeoutMs: number,
terminalManager: IAgentHostTerminalManager,
logService: ILogService,
): Promise<ToolResultObject> {
if (terminalManager.supportsCommandDetection(shell.terminalUri)) {
return executeCommandWithShellIntegration(shell, command, timeoutMs, terminalManager, logService);
}
return executeCommandWithSentinel(shell, command, timeoutMs, terminalManager, logService);
}
/**
* Execute a command using shell integration (OSC 633) for completion detection.
* No sentinel echo is injected — the shell's own command-finished signal
* provides the exit code and cleanly delineated output.
*/
async function executeCommandWithShellIntegration(
shell: IManagedShell,
command: string,
timeoutMs: number,
terminalManager: IAgentHostTerminalManager,
logService: ILogService,
): Promise<ToolResultObject> {
const disposables = new DisposableStore();
terminalManager.writeInput(shell.terminalUri, `${prefixForHistorySuppression(shell.shellType)}${command}\r`);
return new Promise<ToolResultObject>(resolve => {
let resolved = false;
const finish = (result: ToolResultObject) => {
if (resolved) {
return;
}
resolved = true;
disposables.dispose();
resolve(result);
};
disposables.add(terminalManager.onCommandFinished(shell.terminalUri, event => {
const output = prepareOutputForModel(event.output);
const exitCode = event.exitCode ?? 0;
logService.info(`[ShellTool] Command completed (shell integration) with exit code ${exitCode}`);
if (exitCode === 0) {
finish(makeSuccessResult(`Exit code: ${exitCode}\n${output}`));
} else {
finish(makeFailureResult(`Exit code: ${exitCode}\n${output}`));
}
}));
disposables.add(terminalManager.onExit(shell.terminalUri, (exitCode: number) => {
logService.info(`[ShellTool] Shell exited unexpectedly with code ${exitCode}`);
const fullContent = terminalManager.getContent(shell.terminalUri) ?? '';
const output = prepareOutputForModel(fullContent);
finish(makeFailureResult(`Shell exited with code ${exitCode}\n${output}`));
}));
disposables.add(terminalManager.onClaimChanged(shell.terminalUri, (claim) => {
if (claim.kind === TerminalClaimKind.Session && !claim.toolCallId) {
logService.info(`[ShellTool] Continuing in background (claim narrowed)`);
finish(makeSuccessResult('The user chose to continue this command in the background. The terminal is still running.'));
}
}));
const timer = setTimeout(() => {
logService.warn(`[ShellTool] Command timed out after ${timeoutMs}ms`);
const fullContent = terminalManager.getContent(shell.terminalUri) ?? '';
const output = prepareOutputForModel(fullContent);
finish(makeFailureResult(
`Command timed out after ${Math.round(timeoutMs / 1000)}s. Partial output:\n${output}`,
'timeout',
));
}, timeoutMs);
disposables.add(toDisposable(() => clearTimeout(timer)));
});
}
/**
* Fallback: execute a command using a sentinel echo to detect completion.
* Used when shell integration is not available.
*/
async function executeCommandWithSentinel(
shell: IManagedShell,
command: string,
timeoutMs: number,
terminalManager: IAgentHostTerminalManager,
logService: ILogService,
): Promise<ToolResultObject> {
const sentinelId = makeSentinelId();
const sentinelCmd = buildSentinelCommand(sentinelId, shell.shellType);
const disposables = new DisposableStore();
const contentBefore = terminalManager.getContent(shell.terminalUri) ?? '';
const offsetBefore = contentBefore.length;
// PTY input uses \r for line endings — the PTY translates to \r\n
const input = `${prefixForHistorySuppression(shell.shellType)}${command}\r${sentinelCmd}\r`;
terminalManager.writeInput(shell.terminalUri, input);
return new Promise<ToolResultObject>(resolve => {
let resolved = false;
const finish = (result: ToolResultObject) => {
if (resolved) {
return;
}
resolved = true;
disposables.dispose();
resolve(result);
};
const checkForSentinel = () => {
const fullContent = terminalManager.getContent(shell.terminalUri) ?? '';
// Clamp offset: the terminal manager trims content when it exceeds
// 100k chars (slices to last 80k). If trimming happened after we
// captured offsetBefore, scan from the start of the current buffer.
const clampedOffset = Math.min(offsetBefore, fullContent.length);
const newContent = fullContent.substring(clampedOffset);
const parsed = parseSentinel(newContent, sentinelId);
if (parsed.found) {
const output = prepareOutputForModel(parsed.outputBeforeSentinel);
logService.info(`[ShellTool] Command completed with exit code ${parsed.exitCode}`);
if (parsed.exitCode === 0) {
finish(makeSuccessResult(`Exit code: ${parsed.exitCode}\n${output}`));
} else {
finish(makeFailureResult(`Exit code: ${parsed.exitCode}\n${output}`));
}
}
};
disposables.add(terminalManager.onData(shell.terminalUri, () => {
checkForSentinel();
}));
disposables.add(terminalManager.onExit(shell.terminalUri, (exitCode: number) => {
logService.info(`[ShellTool] Shell exited unexpectedly with code ${exitCode}`);
const fullContent = terminalManager.getContent(shell.terminalUri) ?? '';
const newContent = fullContent.substring(offsetBefore);
const output = prepareOutputForModel(newContent);
finish(makeFailureResult(`Shell exited with code ${exitCode}\n${output}`));
}));
disposables.add(terminalManager.onClaimChanged(shell.terminalUri, (claim) => {
if (claim.kind === TerminalClaimKind.Session && !claim.toolCallId) {
logService.info(`[ShellTool] Continuing in background (claim narrowed)`);
finish(makeSuccessResult('The user chose to continue this command in the background. The terminal is still running.'));
}
}));
const timer = setTimeout(() => {
logService.warn(`[ShellTool] Command timed out after ${timeoutMs}ms`);
const fullContent = terminalManager.getContent(shell.terminalUri) ?? '';
const newContent = fullContent.substring(offsetBefore);
const output = prepareOutputForModel(newContent);
finish(makeFailureResult(
`Command timed out after ${Math.round(timeoutMs / 1000)}s. Partial output:\n${output}`,
'timeout',
));
}, timeoutMs);
disposables.add(toDisposable(() => clearTimeout(timer)));
checkForSentinel();
});
}
// ---------------------------------------------------------------------------
// Public factory
// ---------------------------------------------------------------------------
interface IShellToolArgs {
command: string;
timeout?: number;
}
interface IWriteShellArgs {
command: string;
}
interface IReadShellArgs {
shell_id?: string;
}
interface IShutdownShellArgs {
shell_id?: string;
}
/**
* Creates the set of SDK {@link Tool} definitions that override the built-in
* Copilot CLI shell tools with PTY-backed implementations.
*
* Returns tools for the platform-appropriate shell (bash or powershell),
* including companion tools (read, write, shutdown, list).
*/
export function createShellTools(
shellManager: ShellManager,
terminalManager: IAgentHostTerminalManager,
logService: ILogService,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Tool<any>[] {
const shellType: ShellType = platform.isWindows ? 'powershell' : 'bash';
const primaryTool: Tool<IShellToolArgs> = {
name: shellType,
description: `Execute a command in a persistent ${shellType} shell. The shell is reused across calls.`,
parameters: {
type: 'object',
properties: {
command: { type: 'string', description: 'The command to execute' },
timeout: { type: 'number', description: 'Timeout in milliseconds (default 120000)' },
},
required: ['command'],
},
overridesBuiltInTool: true,
handler: async (args, invocation) => {
const shell = await shellManager.getOrCreateShell(
shellType,
invocation.toolCallId,
invocation.toolCallId,
);
const timeoutMs = args.timeout ?? DEFAULT_TIMEOUT_MS;
return executeCommandInShell(shell, args.command, timeoutMs, terminalManager, logService);
},
};
const readTool: Tool<IReadShellArgs> = {
name: `read_${shellType}`,
description: `Read the latest output from a running ${shellType} shell.`,
parameters: {
type: 'object',
properties: {
shell_id: { type: 'string', description: 'Shell ID to read from (optional; uses latest shell if omitted)' },
},
},
overridesBuiltInTool: true,
handler: (args) => {
const shells = shellManager.listShells();
const shell = args.shell_id
? shellManager.getShell(args.shell_id)
: shells[shells.length - 1];
if (!shell) {
return makeFailureResult('No active shell found.', 'no_shell');
}
const content = terminalManager.getContent(shell.terminalUri);
if (!content) {
return makeSuccessResult('(no output)');
}
return makeSuccessResult(prepareOutputForModel(content));
},
};
const writeTool: Tool<IWriteShellArgs> = {
name: `write_${shellType}`,
description: `Send input to a running ${shellType} shell (e.g. answering a prompt, sending Ctrl+C).`,
parameters: {
type: 'object',
properties: {
command: { type: 'string', description: 'Text to write to the shell stdin' },
},
required: ['command'],
},
overridesBuiltInTool: true,
handler: (args) => {
const shells = shellManager.listShells();
const shell = shells[shells.length - 1];
if (!shell) {
return makeFailureResult('No active shell found.', 'no_shell');
}
terminalManager.writeInput(shell.terminalUri, args.command);
return makeSuccessResult('Input sent to shell.');
},
};
const shutdownTool: Tool<IShutdownShellArgs> = {
name: shellType === 'bash' ? 'bash_shutdown' : `${shellType}_shutdown`,
description: `Stop a ${shellType} shell.`,
parameters: {
type: 'object',
properties: {
shell_id: { type: 'string', description: 'Shell ID to stop (optional; stops latest shell if omitted)' },
},
},
overridesBuiltInTool: true,
handler: (args) => {
if (args.shell_id) {
const success = shellManager.shutdownShell(args.shell_id);
return success
? makeSuccessResult('Shell stopped.')
: makeFailureResult('Shell not found.', 'not_found');
}
const shells = shellManager.listShells();
const shell = shells[shells.length - 1];
if (!shell) {
return makeFailureResult('No active shell to stop.', 'no_shell');
}
shellManager.shutdownShell(shell.id);
return makeSuccessResult('Shell stopped.');
},
};
const listTool: Tool<Record<string, never>> = {
name: `list_${shellType}`,
description: `List active ${shellType} shell instances.`,
parameters: { type: 'object', properties: {} },
overridesBuiltInTool: true,
handler: () => {
const shells = shellManager.listShells();
if (shells.length === 0) {
return makeSuccessResult('No active shells.');
}
const descriptions = shells.map(s => {
const exitCode = terminalManager.getExitCode(s.terminalUri);
const status = exitCode !== undefined ? `exited (${exitCode})` : 'running';
return `- ${s.id}: ${s.shellType} [${status}]`;
});
return makeSuccessResult(descriptions.join('\n'));
},
};
return [primaryTool, readTool, writeTool, shutdownTool, listTool];
}