-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Expand file tree
/
Copy pathshellBackgroundTools.ts
More file actions
306 lines (272 loc) · 8.63 KB
/
Copy pathshellBackgroundTools.ts
File metadata and controls
306 lines (272 loc) · 8.63 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
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'node:fs';
import { setTimeout as delay } from 'node:timers/promises';
import { ShellExecutionService } from '../services/shellExecutionService.js';
import {
BaseDeclarativeTool,
BaseToolInvocation,
Kind,
type ToolResult,
type ExecuteOptions,
} from './tools.js';
import { ToolErrorType } from './tool-error.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import { isNodeError } from '../utils/errors.js';
const MAX_BUFFER_LOAD_CAP_BYTES = 64 * 1024; // Safe 64KB buffer load Cap
const DEFAULT_TAIL_LINES_COUNT = 100;
// --- list_background_processes ---
class ListBackgroundProcessesInvocation extends BaseToolInvocation<
Record<string, never>,
ToolResult
> {
constructor(
private readonly context: AgentLoopContext,
params: Record<string, never>,
messageBus: MessageBus,
toolName?: string,
toolDisplayName?: string,
) {
super(params, messageBus, toolName, toolDisplayName);
}
getDescription(): string {
return 'Lists all active and recently completed background processes for the current session.';
}
async execute({ abortSignal: _signal }: ExecuteOptions): Promise<ToolResult> {
const processes = ShellExecutionService.listBackgroundProcesses(
this.context.config.getSessionId(),
);
if (processes.length === 0) {
return {
llmContent: 'No background processes found.',
returnDisplay: 'No background processes found.',
};
}
const lines = processes.map(
(p) =>
`- [PID ${p.pid}] ${p.status.toUpperCase()}: \`${p.command}\`${
p.exitCode !== undefined ? ` (Exit Code: ${p.exitCode})` : ''
}${p.signal ? ` (Signal: ${p.signal})` : ''}`,
);
const content = lines.join('\n');
return {
llmContent: content,
returnDisplay: content,
};
}
}
export class ListBackgroundProcessesTool extends BaseDeclarativeTool<
Record<string, never>,
ToolResult
> {
static readonly Name = 'list_background_processes';
constructor(
private readonly context: AgentLoopContext,
messageBus: MessageBus,
) {
super(
ListBackgroundProcessesTool.Name,
'List Background Processes',
'Lists all active and recently completed background shell processes orchestrating by the agent.',
Kind.Read,
{
type: 'object',
properties: {},
},
messageBus,
);
}
protected createInvocation(
params: Record<string, never>,
messageBus: MessageBus,
) {
return new ListBackgroundProcessesInvocation(
this.context,
params,
messageBus,
this.name,
);
}
}
// --- read_background_output ---
interface ReadBackgroundOutputParams {
pid: number;
lines?: number;
delay_ms?: number;
}
class ReadBackgroundOutputInvocation extends BaseToolInvocation<
ReadBackgroundOutputParams,
ToolResult
> {
constructor(
private readonly context: AgentLoopContext,
params: ReadBackgroundOutputParams,
messageBus: MessageBus,
toolName?: string,
toolDisplayName?: string,
) {
super(params, messageBus, toolName, toolDisplayName);
}
getDescription(): string {
return `Reading output for background process ${this.params.pid}`;
}
async execute({ abortSignal }: ExecuteOptions): Promise<ToolResult> {
const pid = this.params.pid;
if (this.params.delay_ms && this.params.delay_ms > 0) {
// Abort-aware delay: rejects with an AbortError when the user cancels,
// which the tool executor converts into a Cancelled result. Without
// this, cancellation would leave the scheduler blocked until the
// timer fires.
await delay(this.params.delay_ms, undefined, { signal: abortSignal });
}
// Verify process belongs to this session to prevent reading logs of processes from other sessions/users
const processes = ShellExecutionService.listBackgroundProcesses(
this.context.config.getSessionId(),
);
if (!processes.some((p) => p.pid === pid)) {
return {
llmContent: `Access denied. Background process ID ${pid} not found in this session's history.`,
returnDisplay: 'Access denied.',
error: {
message: `Background process history lookup failed for PID ${pid}`,
type: ToolErrorType.EXECUTION_FAILED,
},
};
}
const logPath = ShellExecutionService.getLogFilePath(pid);
try {
await fs.promises.access(logPath);
} catch {
return {
llmContent: `No output log found for process ID ${pid}. It might not have produced output or was cleaned up.`,
returnDisplay: `No log found for PID ${pid}`,
error: {
message: `Log file not found at ${logPath}`,
type: ToolErrorType.EXECUTION_FAILED,
},
};
}
try {
const fileHandle = await fs.promises.open(
logPath,
fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW,
);
let content = '';
let position = 0;
try {
const stats = await fileHandle.stat();
const readSize = Math.min(stats.size, MAX_BUFFER_LOAD_CAP_BYTES);
position = Math.max(0, stats.size - readSize);
const buffer = Buffer.alloc(readSize);
await fileHandle.read(buffer, 0, readSize, position);
content = buffer.toString('utf-8');
} finally {
await fileHandle.close();
}
if (!content) {
return {
llmContent: 'Log is empty.',
returnDisplay: 'Log is empty.',
};
}
const logLines = content.split('\n');
if (logLines.length > 0 && logLines[logLines.length - 1] === '') {
logLines.pop();
}
// Discard first line if we started reading from middle of file to avoid partial lines
if (position > 0 && logLines.length > 0) {
logLines.shift();
}
const requestedLinesCount = this.params.lines ?? DEFAULT_TAIL_LINES_COUNT;
const tailLines = logLines.slice(-requestedLinesCount);
const output = tailLines.join('\n');
const header =
requestedLinesCount < logLines.length
? `Showing last ${requestedLinesCount} of ${logLines.length} lines:\n`
: 'Full Log Output:\n';
const responseContent = header + output;
return {
llmContent: responseContent,
returnDisplay: responseContent,
};
} catch (error) {
if (isNodeError(error) && error.code === 'ELOOP') {
return {
llmContent:
'Symbolic link detected at predicted log path. Access is denied for security reasons.',
returnDisplay: `Symlink detected for PID ${pid}`,
error: {
message:
'Symbolic link detected at predicted log path. Access is denied for security reasons.',
type: ToolErrorType.EXECUTION_FAILED,
},
};
}
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
llmContent: `Error reading background log: ${errorMessage}`,
returnDisplay: 'Failed to read log.',
error: {
message: errorMessage,
type: ToolErrorType.EXECUTION_FAILED,
},
};
}
}
}
export class ReadBackgroundOutputTool extends BaseDeclarativeTool<
ReadBackgroundOutputParams,
ToolResult
> {
static readonly Name = 'read_background_output';
constructor(
private readonly context: AgentLoopContext,
messageBus: MessageBus,
) {
super(
ReadBackgroundOutputTool.Name,
'Read Background Output',
'Reads the output log of a background shell process. Support reading tail snapshot.',
Kind.Read,
{
type: 'object',
properties: {
pid: {
type: 'integer',
description:
'The process ID (PID) of the background process to inspect.',
},
lines: {
type: 'integer',
minimum: 1,
description:
'Optional. Number of lines to read from the end of the log. Defaults to 100.',
},
delay_ms: {
type: 'integer',
description:
'Optional. Delay in milliseconds to wait before reading the output. Useful to allow the process to start and generate initial output.',
},
},
required: ['pid'],
},
messageBus,
);
}
protected createInvocation(
params: ReadBackgroundOutputParams,
messageBus: MessageBus,
) {
return new ReadBackgroundOutputInvocation(
this.context,
params,
messageBus,
this.name,
);
}
}