Remove terminal tool and dependencies.
- We now solely use the shell tool. This deletes all content around the legacy terminal tool so we can focus on improving the new Shell tool. - Remove instances from sandboxing, tests, utilities etc.
This commit is contained in:
parent
dcb67c32a5
commit
cf91f72c5c
|
@ -5,94 +5,9 @@
|
|||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
findSafeSplitPoint,
|
||||
findLastSafeSplitPoint,
|
||||
} from './markdownUtilities.js';
|
||||
import { findLastSafeSplitPoint } from './markdownUtilities.js';
|
||||
|
||||
describe('markdownUtilities', () => {
|
||||
describe('findSafeSplitPoint', () => {
|
||||
it('should return content.length if content is shorter than idealMaxLength', () => {
|
||||
const content = 'short content';
|
||||
expect(findSafeSplitPoint(content, 100)).toBe(content.length);
|
||||
});
|
||||
|
||||
it('should split before a code block if idealMaxLength is inside it', () => {
|
||||
const content = 'text before ```code``` text after';
|
||||
expect(findSafeSplitPoint(content, 15)).toBe(12);
|
||||
});
|
||||
|
||||
it('should return 0 if idealMaxLength is inside a code block that starts at 0', () => {
|
||||
const content = '```code``` text after';
|
||||
expect(findSafeSplitPoint(content, 5)).toBe(0);
|
||||
});
|
||||
|
||||
it('should split at a double newline if possible', () => {
|
||||
const content = 'paragraph1\n\nparagraph2';
|
||||
expect(findSafeSplitPoint(content, 12)).toBe(22); // Updated expectation
|
||||
});
|
||||
|
||||
it('should split at a single newline if double newline is not available', () => {
|
||||
const content = 'line1\nline2';
|
||||
expect(findSafeSplitPoint(content, 7)).toBe(11); // Updated expectation
|
||||
});
|
||||
|
||||
it('should return content.length if no safe split point is found', () => {
|
||||
const content = 'longstringwithoutanysafesplitpoint';
|
||||
expect(findSafeSplitPoint(content, 10)).toBe(content.length);
|
||||
});
|
||||
|
||||
it('should handle content with multiple code blocks', () => {
|
||||
const content = 'text ```code1``` text ```code2``` text';
|
||||
expect(findSafeSplitPoint(content, 20)).toBe(38); // Updated expectation
|
||||
});
|
||||
|
||||
it('should prioritize splitting before a code block over a newline', () => {
|
||||
const content = 'text\nnewline ```code``` text';
|
||||
expect(findSafeSplitPoint(content, 15)).toBe(5); // Updated expectation
|
||||
});
|
||||
|
||||
// Known failure: Code has a bug
|
||||
it.fails(
|
||||
'should split after \n\n when idealMaxLength is not in a code block and a suitable \n\n exists after it',
|
||||
() => {
|
||||
const content = 'This is some text.\n\nThis is more text.';
|
||||
// idealMaxLength is 10, which is before the \n\n
|
||||
// The function should find the \n\n at index 20 and split after it (index 22)
|
||||
expect(findSafeSplitPoint(content, 10)).toBe(22);
|
||||
},
|
||||
);
|
||||
|
||||
it('should return content.length when idealMaxLength is not in a code block and no \n\n exists after it', () => {
|
||||
const content =
|
||||
'This is some text. This is more text and no double newline.';
|
||||
// idealMaxLength is 10
|
||||
// No \n\n after index 10
|
||||
expect(findSafeSplitPoint(content, 10)).toBe(content.length);
|
||||
});
|
||||
|
||||
it('should correctly split before a code block that idealMaxLength is inside, even if \n\n exists before it', () => {
|
||||
const content =
|
||||
'Paragraph before.\n\n```\nCode block content\n```\nParagraph after.';
|
||||
// idealMaxLength is 25, which is inside the code block
|
||||
// The split should be at index 19 (start of the code block)
|
||||
expect(findSafeSplitPoint(content, 25)).toBe(19);
|
||||
});
|
||||
|
||||
it('should split at the last \n before a code block if idealMaxLength is in the code block and no \n\n is found before it', () => {
|
||||
const content = 'Line before.\n```\nCode block\n```';
|
||||
// idealMaxLength is 15 (inside code block)
|
||||
// Split should be at 13 (after \n and before ```)
|
||||
expect(findSafeSplitPoint(content, 15)).toBe(13);
|
||||
});
|
||||
|
||||
it('should return 0 if idealMaxLength is in a code block starting at 0 and no prior newline exists', () => {
|
||||
const content =
|
||||
'```\nVery long code block that exceeds idealMaxLength\n```';
|
||||
expect(findSafeSplitPoint(content, 10)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findLastSafeSplitPoint', () => {
|
||||
it('should split at the last double newline if not in a code block', () => {
|
||||
const content = 'paragraph1\n\nparagraph2\n\nparagraph3';
|
||||
|
|
|
@ -90,101 +90,6 @@ const findEnclosingCodeBlockStart = (
|
|||
return -1;
|
||||
};
|
||||
|
||||
export const findSafeSplitPoint = (
|
||||
content: string,
|
||||
idealMaxLength: number = 500,
|
||||
): number => {
|
||||
if (content.length <= idealMaxLength) {
|
||||
return content.length;
|
||||
}
|
||||
|
||||
const enclosingBlockStartForIdealMax = findEnclosingCodeBlockStart(
|
||||
content,
|
||||
idealMaxLength,
|
||||
);
|
||||
|
||||
if (enclosingBlockStartForIdealMax !== -1) {
|
||||
// idealMaxLength is inside a code block. Try to split *before* this block.
|
||||
const textToSearchForNewline = content.substring(
|
||||
0,
|
||||
enclosingBlockStartForIdealMax,
|
||||
);
|
||||
|
||||
// Iteratively search for the last safe \n\n before enclosingBlockStartForIdealMax
|
||||
let currentSearchFromIndex = textToSearchForNewline.length;
|
||||
while (currentSearchFromIndex > 0) {
|
||||
// searchEndIndex refers to character count to search within
|
||||
const dnlIndex = textToSearchForNewline.lastIndexOf(
|
||||
'\n\n',
|
||||
currentSearchFromIndex - 1,
|
||||
); // fromIndex for lastIndexOf is 0-based
|
||||
if (dnlIndex === -1) break;
|
||||
|
||||
const potentialSplit = dnlIndex + 2;
|
||||
// The split must be strictly before the block idealMaxLength was in.
|
||||
// This is implicitly true if dnlIndex is found within textToSearchForNewline.
|
||||
if (!isIndexInsideCodeBlock(content, potentialSplit)) {
|
||||
// Condition: (potentialSplit > 0) OR (it's 0 AND the problematic block also started at 0)
|
||||
if (
|
||||
potentialSplit > 0 ||
|
||||
(enclosingBlockStartForIdealMax === 0 && potentialSplit === 0)
|
||||
) {
|
||||
return potentialSplit;
|
||||
}
|
||||
}
|
||||
currentSearchFromIndex = dnlIndex; // Continue search before the start of this found \n\n
|
||||
// (dnlIndex is start of \n\n, so next search is before it)
|
||||
}
|
||||
|
||||
// Iteratively search for the last safe \n
|
||||
currentSearchFromIndex = textToSearchForNewline.length;
|
||||
while (currentSearchFromIndex >= 0) {
|
||||
// Can be 0 if textToSearchForNewline has length 1 and it's \n
|
||||
const snlIndex = textToSearchForNewline.lastIndexOf(
|
||||
'\n',
|
||||
currentSearchFromIndex - 1,
|
||||
);
|
||||
if (snlIndex === -1) break;
|
||||
|
||||
const potentialSplit = snlIndex + 1;
|
||||
if (!isIndexInsideCodeBlock(content, potentialSplit)) {
|
||||
if (
|
||||
potentialSplit > 0 ||
|
||||
(enclosingBlockStartForIdealMax === 0 && potentialSplit === 0)
|
||||
) {
|
||||
return potentialSplit;
|
||||
}
|
||||
}
|
||||
currentSearchFromIndex = snlIndex;
|
||||
}
|
||||
|
||||
// Fallback: split right before this code block
|
||||
return enclosingBlockStartForIdealMax;
|
||||
}
|
||||
|
||||
// idealMaxLength is NOT inside a code block.
|
||||
// Search forwards from idealMaxLength for the next double newline (\n\n) not in a code block.
|
||||
let searchStartIndex = idealMaxLength;
|
||||
while (searchStartIndex < content.length) {
|
||||
const dnlIndex = content.indexOf('\n\n', searchStartIndex);
|
||||
if (dnlIndex === -1) {
|
||||
// No more double newlines found after idealMaxLength
|
||||
break;
|
||||
}
|
||||
|
||||
const potentialSplitPoint = dnlIndex + 2;
|
||||
if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
|
||||
return potentialSplitPoint;
|
||||
}
|
||||
|
||||
searchStartIndex = potentialSplitPoint; // Continue search after the found \n\n
|
||||
}
|
||||
|
||||
// If no safe double newline found after idealMaxLength, return content.length
|
||||
// to keep the entire content as one piece.
|
||||
return content.length;
|
||||
};
|
||||
|
||||
export const findLastSafeSplitPoint = (content: string) => {
|
||||
const enclosingBlockStart = findEnclosingCodeBlockStart(
|
||||
content,
|
||||
|
|
|
@ -332,11 +332,6 @@ export async function start_sandbox(sandbox: string) {
|
|||
args.push('--env', `GEMINI_CODE_MODEL=${process.env.GEMINI_CODE_MODEL}`);
|
||||
}
|
||||
|
||||
// copy TERMINAL_TOOL to optionally enable shell tool
|
||||
if (process.env.TERMINAL_TOOL) {
|
||||
args.push('--env', `TERMINAL_TOOL=${process.env.TERMINAL_TOOL}`);
|
||||
}
|
||||
|
||||
// copy TERM and COLORTERM to try to maintain terminal setup
|
||||
if (process.env.TERM) {
|
||||
args.push('--env', `TERM=${process.env.TERM}`);
|
||||
|
|
|
@ -14,7 +14,6 @@ import { ReadFileTool } from '../tools/read-file.js';
|
|||
import { GrepTool } from '../tools/grep.js';
|
||||
import { GlobTool } from '../tools/glob.js';
|
||||
import { EditTool } from '../tools/edit.js';
|
||||
import { TerminalTool } from '../tools/terminal.js';
|
||||
import { ShellTool } from '../tools/shell.js';
|
||||
import { WriteFileTool } from '../tools/write-file.js';
|
||||
import { WebFetchTool } from '../tools/web-fetch.js';
|
||||
|
@ -146,15 +145,9 @@ function createToolRegistry(config: Config): ToolRegistry {
|
|||
new WriteFileTool(targetDir),
|
||||
new WebFetchTool(), // Note: WebFetchTool takes no arguments
|
||||
new ReadManyFilesTool(targetDir),
|
||||
new ShellTool(config),
|
||||
];
|
||||
|
||||
// if TERMINAL_TOOL is set, revert to deprecated TerminalTool
|
||||
if (process.env.TERMINAL_TOOL) {
|
||||
tools.push(new TerminalTool(targetDir, config));
|
||||
} else {
|
||||
tools.push(new ShellTool(config));
|
||||
}
|
||||
|
||||
for (const tool of tools) {
|
||||
registry.registerTool(tool);
|
||||
}
|
||||
|
|
|
@ -30,6 +30,5 @@ export * from './tools/ls.js';
|
|||
export * from './tools/grep.js';
|
||||
export * from './tools/glob.js';
|
||||
export * from './tools/edit.js';
|
||||
export * from './tools/terminal.js';
|
||||
export * from './tools/write-file.js';
|
||||
export * from './tools/web-fetch.js';
|
||||
|
|
|
@ -1,911 +0,0 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import {
|
||||
spawn,
|
||||
SpawnOptions,
|
||||
ChildProcessWithoutNullStreams,
|
||||
} from 'child_process';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import crypto from 'crypto';
|
||||
import { promises as fs } from 'fs';
|
||||
import { SchemaValidator } from '../utils/schemaValidator.js';
|
||||
import { getErrorMessage, isNodeError } from '../utils/errors.js';
|
||||
import { Config } from '../config/config.js';
|
||||
import {
|
||||
BaseTool,
|
||||
ToolCallConfirmationDetails,
|
||||
ToolConfirmationOutcome,
|
||||
ToolExecuteConfirmationDetails,
|
||||
ToolResult,
|
||||
} from './tools.js';
|
||||
import { BackgroundTerminalAnalyzer } from '../utils/BackgroundTerminalAnalyzer.js';
|
||||
|
||||
export interface TerminalToolParams {
|
||||
command: string;
|
||||
description?: string;
|
||||
timeout?: number;
|
||||
runInBackground?: boolean;
|
||||
}
|
||||
|
||||
const MAX_OUTPUT_LENGTH = 10000;
|
||||
const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
const MAX_TIMEOUT_OVERRIDE_MS = 10 * 60 * 1000;
|
||||
const BACKGROUND_LAUNCH_TIMEOUT_MS = 15 * 1000;
|
||||
const BACKGROUND_POLL_TIMEOUT_MS = 30000;
|
||||
|
||||
interface QueuedCommand {
|
||||
params: TerminalToolParams;
|
||||
resolve: (result: ToolResult) => void;
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
export class TerminalTool extends BaseTool<TerminalToolParams, ToolResult> {
|
||||
static Name: string = 'execute_bash_command';
|
||||
private bashProcess: ChildProcessWithoutNullStreams | null = null;
|
||||
private currentCwd: string;
|
||||
private isExecuting: boolean = false;
|
||||
private commandQueue: QueuedCommand[] = [];
|
||||
private currentCommandCleanup: (() => void) | null = null;
|
||||
private shouldAlwaysExecuteCommands: Map<string, boolean> = new Map();
|
||||
private shellReady: Promise<void>;
|
||||
private resolveShellReady: (() => void) | undefined;
|
||||
private rejectShellReady: ((reason?: unknown) => void) | undefined;
|
||||
private readonly backgroundTerminalAnalyzer: BackgroundTerminalAnalyzer;
|
||||
|
||||
constructor(
|
||||
private readonly rootDirectory: string,
|
||||
private readonly config: Config,
|
||||
private readonly outputLimit: number = MAX_OUTPUT_LENGTH,
|
||||
) {
|
||||
const toolDisplayName = 'Terminal';
|
||||
const toolDescription = `Executes one or more bash commands sequentially in a secure and persistent interactive shell session. Can run commands in the foreground (waiting for completion) or background (returning after launch, with subsequent status polling).
|
||||
|
||||
Core Functionality:
|
||||
* Starts in project root: '${path.basename(rootDirectory)}'. Current Directory starts as: ${rootDirectory} (will update based on 'cd' commands).
|
||||
* Persistent State: Environment variables and the current working directory (\`pwd\`) persist between calls to this tool.
|
||||
* **Execution Modes:**
|
||||
* **Foreground (default):** Waits for the command to complete. Captures stdout, stderr, and exit code. Output is truncated if it exceeds ${outputLimit} characters.
|
||||
* **Background (\`runInBackground: true\`):** Appends \`&\` to the command and redirects its output to temporary files. Returns *after* the command is launched, providing the Process ID (PID) and launch status. Subsequently, the tool **polls** for the background process status for up to ${BACKGROUND_POLL_TIMEOUT_MS / 1000} seconds. Once the process finishes or polling times out, the tool reads the captured stdout/stderr from the temporary files, runs an internal LLM analysis on the output, cleans up the files, and returns the final status, captured output, and analysis.
|
||||
* Timeout: Optional timeout per 'execute' call (default: ${DEFAULT_TIMEOUT_MS / 60000} min, max override: ${MAX_TIMEOUT_OVERRIDE_MS / 60000} min for foreground). Background *launch* has a fixed shorter timeout (${BACKGROUND_LAUNCH_TIMEOUT_MS / 1000}s) for the launch attempt itself. Background *polling* has its own timeout (${BACKGROUND_POLL_TIMEOUT_MS / 1000}s). Timeout attempts SIGINT for foreground commands.
|
||||
|
||||
Usage Guidance & Restrictions:
|
||||
|
||||
1. **Directory/File Verification (IMPORTANT):**
|
||||
* BEFORE executing commands that create files or directories (e.g., \`mkdir foo/bar\`, \`touch new/file.txt\`, \`git clone ...\`), use the dedicated File System tool (e.g., 'list_directory') to verify the target parent directory exists and is the correct location.
|
||||
* Example: Before running \`mkdir foo/bar\`, first use the File System tool to check that \`foo\` exists in the current directory (\`${rootDirectory}\` initially, check current CWD if it changed).
|
||||
|
||||
2. **Use Specialized Tools (CRITICAL):**
|
||||
* Do NOT use this tool for filesystem searching (\`find\`, \`grep\`). Use the dedicated Search tool instead.
|
||||
* Do NOT use this tool for reading files (\`cat\`, \`head\`, \`tail\`, \`less\`, \`more\`). Use the dedicated File Reader tool instead.
|
||||
* Do NOT use this tool for listing files (\`ls\`). Use the dedicated File System tool ('list_directory') instead. Relying on this tool's output for directory structure is unreliable due to potential truncation and lack of structured data.
|
||||
|
||||
3. **Command Execution Notes:**
|
||||
* Chain multiple commands using shell operators like ';' or '&&'. Do NOT use newlines within the 'command' parameter string itself (newlines are fine inside quoted arguments).
|
||||
* The shell's current working directory is tracked internally. While \`cd\` is permitted if the user explicitly asks or it's necessary for a workflow, **strongly prefer** using absolute paths or paths relative to the *known* current working directory to avoid errors. Check the '(Executed in: ...)' part of the previous command's output for the CWD.
|
||||
* Good example (if CWD is /workspace/project): \`pytest tests/unit\` or \`ls /workspace/project/data\`
|
||||
* Less preferred: \`cd tests && pytest unit\` (only use if necessary or requested)
|
||||
|
||||
4. **Background Tasks (\`runInBackground: true\`):**
|
||||
* Use this for commands that are intended to run continuously (e.g., \`node server.js\`, \`npm start\`).
|
||||
* The tool initially returns success if the process *launches* successfully, along with its PID.
|
||||
* **Polling & Final Result:** The tool then monitors the process. The *final* result (delivered after polling completes or times out) will include:
|
||||
* The final status (completed or timed out).
|
||||
* The complete stdout and stderr captured in temporary files (truncated if necessary).
|
||||
* An LLM-generated analysis/summary of the output.
|
||||
* The initial exit code (usually 0) signifies successful *launching*; the final status indicates completion or timeout after polling.
|
||||
|
||||
Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`eslint .\`), test runners (\`pytest\`, \`jest\`), code formatters (\`prettier --write .\`), package managers (\`pip install\`), version control operations (\`git status\`, \`git diff\`), starting background servers/services (\`node server.js --runInBackground true\`), or other safe, standard command-line operations within the project workspace.`;
|
||||
const toolParameterSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
command: {
|
||||
description: `The exact bash command or sequence of commands (using ';' or '&&') to execute. Must adhere to usage guidelines. Example: 'npm install && npm run build'`,
|
||||
type: 'string',
|
||||
},
|
||||
description: {
|
||||
description: `Optional: A brief, user-centric explanation of what the command does and why it's being run. Used for logging and confirmation prompts. Example: 'Install project dependencies'`,
|
||||
type: 'string',
|
||||
},
|
||||
timeout: {
|
||||
description: `Optional execution time limit in milliseconds for FOREGROUND commands. Max ${MAX_TIMEOUT_OVERRIDE_MS}ms (${MAX_TIMEOUT_OVERRIDE_MS / 60000} min). Defaults to ${DEFAULT_TIMEOUT_MS}ms (${DEFAULT_TIMEOUT_MS / 60000} min) if not specified or invalid. Ignored if 'runInBackground' is true.`,
|
||||
type: 'number',
|
||||
},
|
||||
runInBackground: {
|
||||
description: `If true, execute the command in the background using '&'. Defaults to false. Use for servers or long tasks.`,
|
||||
type: 'boolean',
|
||||
},
|
||||
},
|
||||
required: ['command'],
|
||||
};
|
||||
super(
|
||||
TerminalTool.Name,
|
||||
toolDisplayName,
|
||||
toolDescription,
|
||||
toolParameterSchema,
|
||||
);
|
||||
this.rootDirectory = path.resolve(rootDirectory);
|
||||
this.currentCwd = this.rootDirectory;
|
||||
this.outputLimit = outputLimit;
|
||||
this.shellReady = new Promise((resolve, reject) => {
|
||||
this.resolveShellReady = resolve;
|
||||
this.rejectShellReady = reject;
|
||||
});
|
||||
this.backgroundTerminalAnalyzer = new BackgroundTerminalAnalyzer(config);
|
||||
this.initializeShell();
|
||||
}
|
||||
|
||||
private initializeShell() {
|
||||
if (this.bashProcess) {
|
||||
try {
|
||||
this.bashProcess.kill();
|
||||
} catch {
|
||||
/* Ignore */
|
||||
}
|
||||
}
|
||||
const spawnOptions: SpawnOptions = {
|
||||
cwd: this.rootDirectory,
|
||||
shell: true,
|
||||
env: { ...process.env },
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
};
|
||||
try {
|
||||
const bashPath = os.platform() === 'win32' ? 'bash.exe' : 'bash';
|
||||
this.bashProcess = spawn(
|
||||
bashPath,
|
||||
['-s'],
|
||||
spawnOptions,
|
||||
) as ChildProcessWithoutNullStreams;
|
||||
this.currentCwd = this.rootDirectory;
|
||||
this.bashProcess.on('error', (err) => {
|
||||
console.error('Persistent Bash Error:', err);
|
||||
this.rejectShellReady?.(err);
|
||||
this.bashProcess = null;
|
||||
this.isExecuting = false;
|
||||
this.clearQueue(
|
||||
new Error(`Persistent bash process failed to start: ${err.message}`),
|
||||
);
|
||||
});
|
||||
this.bashProcess.on('close', (code, signal) => {
|
||||
this.bashProcess = null;
|
||||
this.isExecuting = false;
|
||||
this.rejectShellReady?.(
|
||||
new Error(
|
||||
`Persistent bash process exited (code: ${code}, signal: ${signal})`,
|
||||
),
|
||||
);
|
||||
this.clearQueue(
|
||||
new Error(
|
||||
`Persistent bash process exited unexpectedly (code: ${code}, signal: ${signal}). State is lost. Queued commands cancelled.`,
|
||||
),
|
||||
);
|
||||
if (signal !== 'SIGINT') {
|
||||
this.shellReady = new Promise((resolve, reject) => {
|
||||
this.resolveShellReady = resolve;
|
||||
this.rejectShellReady = reject;
|
||||
});
|
||||
setTimeout(() => this.initializeShell(), 1000);
|
||||
}
|
||||
});
|
||||
setTimeout(() => {
|
||||
if (this.bashProcess && !this.bashProcess.killed) {
|
||||
this.resolveShellReady?.();
|
||||
} else if (!this.bashProcess) {
|
||||
// Error likely handled
|
||||
} else {
|
||||
this.rejectShellReady?.(
|
||||
new Error('Shell killed during initialization'),
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to spawn persistent bash:', error);
|
||||
this.rejectShellReady?.(error);
|
||||
this.bashProcess = null;
|
||||
this.clearQueue(
|
||||
new Error(`Failed to spawn persistent bash: ${getErrorMessage(error)}`),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
validateToolParams(params: TerminalToolParams): string | null {
|
||||
if (
|
||||
!SchemaValidator.validate(
|
||||
this.parameterSchema as Record<string, unknown>,
|
||||
params,
|
||||
)
|
||||
) {
|
||||
return `Parameters failed schema validation.`;
|
||||
}
|
||||
if (!params.command.trim()) {
|
||||
return 'Command cannot be empty.';
|
||||
}
|
||||
if (
|
||||
params.timeout !== undefined &&
|
||||
(typeof params.timeout !== 'number' || params.timeout <= 0)
|
||||
) {
|
||||
return 'Timeout must be a positive number of milliseconds.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
getDescription(params: TerminalToolParams): string {
|
||||
return params.description || params.command;
|
||||
}
|
||||
|
||||
async shouldConfirmExecute(
|
||||
params: TerminalToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
if (this.validateToolParams(params)) {
|
||||
return false; // skip confirmation, execute call will fail immediately
|
||||
}
|
||||
const rootCommand =
|
||||
params.command
|
||||
.trim()
|
||||
.split(/[\s;&&|]+/)[0]
|
||||
?.split(/[/\\]/)
|
||||
.pop() || 'unknown';
|
||||
if (this.shouldAlwaysExecuteCommands.get(rootCommand)) {
|
||||
return false;
|
||||
}
|
||||
const confirmationDetails: ToolExecuteConfirmationDetails = {
|
||||
title: 'Confirm Shell Command',
|
||||
command: params.command,
|
||||
rootCommand,
|
||||
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
||||
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
||||
this.shouldAlwaysExecuteCommands.set(rootCommand, true);
|
||||
}
|
||||
},
|
||||
};
|
||||
return confirmationDetails;
|
||||
}
|
||||
|
||||
async execute(
|
||||
params: TerminalToolParams,
|
||||
_signal: AbortSignal,
|
||||
): Promise<ToolResult> {
|
||||
const validationError = this.validateToolParams(params);
|
||||
if (validationError) {
|
||||
return {
|
||||
llmContent: `Command rejected: ${params.command}\nReason: ${validationError}`,
|
||||
returnDisplay: `Error: ${validationError}`,
|
||||
};
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const queuedItem: QueuedCommand = {
|
||||
params,
|
||||
resolve,
|
||||
reject: (error) =>
|
||||
resolve({
|
||||
llmContent: `Internal tool error for command: ${params.command}\nError: ${error.message}`,
|
||||
returnDisplay: `Internal Tool Error: ${error.message}`,
|
||||
}),
|
||||
};
|
||||
this.commandQueue.push(queuedItem);
|
||||
setImmediate(() => this.triggerQueueProcessing());
|
||||
});
|
||||
}
|
||||
|
||||
private async triggerQueueProcessing(): Promise<void> {
|
||||
if (this.isExecuting || this.commandQueue.length === 0) {
|
||||
return;
|
||||
}
|
||||
this.isExecuting = true;
|
||||
const { params, resolve, reject } = this.commandQueue.shift()!;
|
||||
try {
|
||||
await this.shellReady;
|
||||
if (!this.bashProcess || this.bashProcess.killed) {
|
||||
throw new Error(
|
||||
'Persistent bash process is not available or was killed.',
|
||||
);
|
||||
}
|
||||
const result = await this.executeCommandInShell(params);
|
||||
resolve(result);
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error executing command "${params.command}":`, error);
|
||||
if (error instanceof Error) {
|
||||
reject(error);
|
||||
} else {
|
||||
reject(new Error('Unknown error occurred: ' + JSON.stringify(error)));
|
||||
}
|
||||
} finally {
|
||||
this.isExecuting = false;
|
||||
setImmediate(() => this.triggerQueueProcessing());
|
||||
}
|
||||
}
|
||||
|
||||
private executeCommandInShell(
|
||||
params: TerminalToolParams,
|
||||
): Promise<ToolResult> {
|
||||
let tempStdoutPath: string | null = null;
|
||||
let tempStderrPath: string | null = null;
|
||||
let originalResolve: (value: ToolResult | PromiseLike<ToolResult>) => void;
|
||||
let originalReject: (reason?: unknown) => void;
|
||||
const promise = new Promise<ToolResult>((resolve, reject) => {
|
||||
originalResolve = resolve;
|
||||
originalReject = reject;
|
||||
if (!this.bashProcess) {
|
||||
return reject(
|
||||
new Error('Bash process is not running. Cannot execute command.'),
|
||||
);
|
||||
}
|
||||
const isBackgroundTask = params.runInBackground ?? false;
|
||||
const commandUUID = crypto.randomUUID();
|
||||
const startDelimiter = `::START_CMD_${commandUUID}::`;
|
||||
const endDelimiter = `::END_CMD_${commandUUID}::`;
|
||||
const exitCodeDelimiter = `::EXIT_CODE_${commandUUID}::`;
|
||||
const pidDelimiter = `::PID_${commandUUID}::`;
|
||||
if (isBackgroundTask) {
|
||||
try {
|
||||
const tempDir = os.tmpdir();
|
||||
tempStdoutPath = path.join(tempDir, `term_out_${commandUUID}.log`);
|
||||
tempStderrPath = path.join(tempDir, `term_err_${commandUUID}.log`);
|
||||
} catch (err: unknown) {
|
||||
return reject(
|
||||
new Error(
|
||||
`Failed to determine temporary directory: ${getErrorMessage(err)}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
let stdoutBuffer = '';
|
||||
let stderrBuffer = '';
|
||||
let commandOutputStarted = false;
|
||||
let exitCode: number | null = null;
|
||||
let backgroundPid: number | null = null;
|
||||
let receivedEndDelimiter = false;
|
||||
const effectiveTimeout = isBackgroundTask
|
||||
? BACKGROUND_LAUNCH_TIMEOUT_MS
|
||||
: Math.min(
|
||||
params.timeout ?? DEFAULT_TIMEOUT_MS,
|
||||
MAX_TIMEOUT_OVERRIDE_MS,
|
||||
);
|
||||
let onStdoutData: ((data: Buffer) => void) | null = null;
|
||||
let onStderrData: ((data: Buffer) => void) | null = null;
|
||||
let launchTimeoutId: NodeJS.Timeout | null = null;
|
||||
launchTimeoutId = setTimeout(() => {
|
||||
const timeoutMessage = isBackgroundTask
|
||||
? `Background command launch timed out after ${effectiveTimeout}ms.`
|
||||
: `Command timed out after ${effectiveTimeout}ms.`;
|
||||
if (!isBackgroundTask && this.bashProcess && !this.bashProcess.killed) {
|
||||
try {
|
||||
this.bashProcess.stdin.write('\x03');
|
||||
} catch (e: unknown) {
|
||||
console.error('Error writing SIGINT on timeout:', e);
|
||||
}
|
||||
}
|
||||
const listenersToClean = { onStdoutData, onStderrData };
|
||||
cleanupListeners(listenersToClean);
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) => {
|
||||
console.warn(
|
||||
`Error cleaning up temp files on timeout: ${err.message}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
originalResolve({
|
||||
llmContent: `Command execution failed: ${timeoutMessage}\nCommand: ${params.command}\nExecuted in: ${this.currentCwd}\n${isBackgroundTask ? 'Mode: Background Launch' : `Mode: Foreground\nTimeout Limit: ${effectiveTimeout}ms`}\nPartial Stdout (Launch):\n${this.truncateOutput(stdoutBuffer)}\nPartial Stderr (Launch):\n${this.truncateOutput(stderrBuffer)}\nNote: ${isBackgroundTask ? 'Launch failed or took too long.' : 'Attempted interrupt (SIGINT). Shell state might be unpredictable if command ignored interrupt.'}`,
|
||||
returnDisplay: `Timeout: ${timeoutMessage}`,
|
||||
});
|
||||
}, effectiveTimeout);
|
||||
const processDataChunk = (chunk: string, isStderr: boolean): boolean => {
|
||||
let dataToProcess = chunk;
|
||||
if (!commandOutputStarted) {
|
||||
const startIndex = dataToProcess.indexOf(startDelimiter);
|
||||
if (startIndex !== -1) {
|
||||
commandOutputStarted = true;
|
||||
dataToProcess = dataToProcess.substring(
|
||||
startIndex + startDelimiter.length,
|
||||
);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const pidIndex = dataToProcess.indexOf(pidDelimiter);
|
||||
if (pidIndex !== -1) {
|
||||
const pidMatch = dataToProcess
|
||||
.substring(pidIndex + pidDelimiter.length)
|
||||
.match(/^(\d+)/);
|
||||
if (pidMatch?.[1]) {
|
||||
backgroundPid = parseInt(pidMatch[1], 10);
|
||||
const pidEndIndex =
|
||||
pidIndex + pidDelimiter.length + pidMatch[1].length;
|
||||
const beforePid = dataToProcess.substring(0, pidIndex);
|
||||
if (isStderr) stderrBuffer += beforePid;
|
||||
else stdoutBuffer += beforePid;
|
||||
dataToProcess = dataToProcess.substring(pidEndIndex);
|
||||
} else {
|
||||
const beforePid = dataToProcess.substring(0, pidIndex);
|
||||
if (isStderr) stderrBuffer += beforePid;
|
||||
else stdoutBuffer += beforePid;
|
||||
dataToProcess = dataToProcess.substring(
|
||||
pidIndex + pidDelimiter.length,
|
||||
);
|
||||
}
|
||||
}
|
||||
const exitCodeIndex = dataToProcess.indexOf(exitCodeDelimiter);
|
||||
if (exitCodeIndex !== -1) {
|
||||
const exitCodeMatch = dataToProcess
|
||||
.substring(exitCodeIndex + exitCodeDelimiter.length)
|
||||
.match(/^(\d+)/);
|
||||
if (exitCodeMatch?.[1]) {
|
||||
exitCode = parseInt(exitCodeMatch[1], 10);
|
||||
const beforeExitCode = dataToProcess.substring(0, exitCodeIndex);
|
||||
if (isStderr) stderrBuffer += beforeExitCode;
|
||||
else stdoutBuffer += beforeExitCode;
|
||||
dataToProcess = dataToProcess.substring(
|
||||
exitCodeIndex +
|
||||
exitCodeDelimiter.length +
|
||||
exitCodeMatch[1].length,
|
||||
);
|
||||
} else {
|
||||
const beforeExitCode = dataToProcess.substring(0, exitCodeIndex);
|
||||
if (isStderr) stderrBuffer += beforeExitCode;
|
||||
else stdoutBuffer += beforeExitCode;
|
||||
dataToProcess = dataToProcess.substring(
|
||||
exitCodeIndex + exitCodeDelimiter.length,
|
||||
);
|
||||
}
|
||||
}
|
||||
const endDelimiterIndex = dataToProcess.indexOf(endDelimiter);
|
||||
if (endDelimiterIndex !== -1) {
|
||||
receivedEndDelimiter = true;
|
||||
const beforeEndDelimiter = dataToProcess.substring(
|
||||
0,
|
||||
endDelimiterIndex,
|
||||
);
|
||||
if (isStderr) stderrBuffer += beforeEndDelimiter;
|
||||
else stdoutBuffer += beforeEndDelimiter;
|
||||
const afterEndDelimiter = dataToProcess.substring(
|
||||
endDelimiterIndex + endDelimiter.length,
|
||||
);
|
||||
const exitCodeEchoMatch = afterEndDelimiter.match(/^(\d+)/);
|
||||
dataToProcess = exitCodeEchoMatch
|
||||
? afterEndDelimiter.substring(exitCodeEchoMatch[1].length)
|
||||
: afterEndDelimiter;
|
||||
}
|
||||
if (dataToProcess.length > 0) {
|
||||
if (isStderr) stderrBuffer += dataToProcess;
|
||||
else stdoutBuffer += dataToProcess;
|
||||
}
|
||||
if (receivedEndDelimiter && exitCode !== null) {
|
||||
setImmediate(cleanupAndResolve);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
onStdoutData = (data: Buffer) => processDataChunk(data.toString(), false);
|
||||
onStderrData = (data: Buffer) => processDataChunk(data.toString(), true);
|
||||
const cleanupListeners = (listeners?: {
|
||||
onStdoutData: ((data: Buffer) => void) | null;
|
||||
onStderrData: ((data: Buffer) => void) | null;
|
||||
}) => {
|
||||
if (launchTimeoutId) clearTimeout(launchTimeoutId);
|
||||
launchTimeoutId = null;
|
||||
const stdoutListener = listeners?.onStdoutData ?? onStdoutData;
|
||||
const stderrListener = listeners?.onStderrData ?? onStderrData;
|
||||
if (this.bashProcess && !this.bashProcess.killed) {
|
||||
if (stdoutListener)
|
||||
this.bashProcess.stdout.removeListener('data', stdoutListener);
|
||||
if (stderrListener)
|
||||
this.bashProcess.stderr.removeListener('data', stderrListener);
|
||||
}
|
||||
if (this.currentCommandCleanup === cleanupListeners) {
|
||||
this.currentCommandCleanup = null;
|
||||
}
|
||||
onStdoutData = null;
|
||||
onStderrData = null;
|
||||
};
|
||||
this.currentCommandCleanup = cleanupListeners;
|
||||
const cleanupAndResolve = async () => {
|
||||
if (
|
||||
!this.currentCommandCleanup ||
|
||||
this.currentCommandCleanup !== cleanupListeners
|
||||
) {
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch(
|
||||
(err) => {
|
||||
console.warn(
|
||||
`Error cleaning up temp files for superseded command: ${err.message}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const launchStdout = this.truncateOutput(stdoutBuffer);
|
||||
const launchStderr = this.truncateOutput(stderrBuffer);
|
||||
const listenersToClean = { onStdoutData, onStderrData };
|
||||
cleanupListeners(listenersToClean);
|
||||
if (exitCode === null) {
|
||||
console.error(
|
||||
`CRITICAL: Command "${params.command}" (background: ${isBackgroundTask}) finished delimiter processing but exitCode is null.`,
|
||||
);
|
||||
const errorMode = isBackgroundTask
|
||||
? 'Background Launch'
|
||||
: 'Foreground';
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
await this.cleanupTempFiles(tempStdoutPath, tempStderrPath);
|
||||
}
|
||||
originalResolve({
|
||||
llmContent: `Command: ${params.command}\nExecuted in: ${this.currentCwd}\nMode: ${errorMode}\nExit Code: -2 (Internal Error: Exit code not captured)\nStdout (during setup):\n${launchStdout}\nStderr (during setup):\n${launchStderr}`,
|
||||
returnDisplay:
|
||||
`Internal Error: Failed to capture command exit code.\n${launchStdout}\nStderr: ${launchStderr}`.trim(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
let cwdUpdateError = '';
|
||||
if (!isBackgroundTask) {
|
||||
const mightChangeCwd = params.command.trim().startsWith('cd ');
|
||||
if (exitCode === 0 || mightChangeCwd) {
|
||||
try {
|
||||
const latestCwd = await this.getCurrentShellCwd();
|
||||
if (this.currentCwd !== latestCwd) {
|
||||
this.currentCwd = latestCwd;
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (exitCode === 0) {
|
||||
cwdUpdateError = `\nWarning: Failed to verify/update current working directory after command: ${getErrorMessage(e)}`;
|
||||
console.error(
|
||||
'Failed to update CWD after successful command:',
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isBackgroundTask) {
|
||||
const launchSuccess = exitCode === 0;
|
||||
const pidString =
|
||||
backgroundPid !== null ? backgroundPid.toString() : 'Not Captured';
|
||||
if (
|
||||
launchSuccess &&
|
||||
backgroundPid !== null &&
|
||||
tempStdoutPath &&
|
||||
tempStderrPath
|
||||
) {
|
||||
this.inspectBackgroundProcess(
|
||||
backgroundPid,
|
||||
params.command,
|
||||
this.currentCwd,
|
||||
launchStdout,
|
||||
launchStderr,
|
||||
tempStdoutPath,
|
||||
tempStderrPath,
|
||||
originalResolve,
|
||||
);
|
||||
} else {
|
||||
const reason =
|
||||
backgroundPid === null
|
||||
? 'PID not captured'
|
||||
: `Launch failed (Exit Code: ${exitCode})`;
|
||||
const displayMessage = `Failed to launch process in background (${reason})`;
|
||||
console.error(
|
||||
`Background launch failed for command: ${params.command}. Reason: ${reason}`,
|
||||
);
|
||||
if (tempStdoutPath && tempStderrPath) {
|
||||
await this.cleanupTempFiles(tempStdoutPath, tempStderrPath);
|
||||
}
|
||||
originalResolve({
|
||||
llmContent: `Background Command Launch Failed: ${params.command}\nExecuted in: ${this.currentCwd}\nReason: ${reason}\nPID: ${pidString}\nExit Code (Launch): ${exitCode}\nStdout (During Launch):\n${launchStdout}\nStderr (During Launch):\n${launchStderr}`,
|
||||
returnDisplay: displayMessage,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let displayOutput = '';
|
||||
const stdoutTrimmed = launchStdout.trim();
|
||||
const stderrTrimmed = launchStderr.trim();
|
||||
if (stderrTrimmed) {
|
||||
displayOutput = stderrTrimmed;
|
||||
} else if (stdoutTrimmed) {
|
||||
displayOutput = stdoutTrimmed;
|
||||
}
|
||||
if (exitCode !== 0 && !displayOutput) {
|
||||
displayOutput = `Failed with exit code: ${exitCode}`;
|
||||
} else if (exitCode === 0 && !displayOutput) {
|
||||
displayOutput = `Success (no output)`;
|
||||
}
|
||||
originalResolve({
|
||||
llmContent: `Command: ${params.command}\nExecuted in: ${this.currentCwd}\nExit Code: ${exitCode}\nStdout:\n${launchStdout}\nStderr:\n${launchStderr}${cwdUpdateError}`,
|
||||
returnDisplay: displayOutput.trim() || `Exit Code: ${exitCode}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
if (!this.bashProcess || this.bashProcess.killed) {
|
||||
console.error(
|
||||
'Bash process lost or killed before listeners could be attached.',
|
||||
);
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) => {
|
||||
console.warn(
|
||||
`Error cleaning up temp files on attach failure: ${err.message}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
return originalReject(
|
||||
new Error(
|
||||
'Bash process lost or killed before listeners could be attached.',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (onStdoutData) this.bashProcess.stdout.on('data', onStdoutData);
|
||||
if (onStderrData) this.bashProcess.stderr.on('data', onStderrData);
|
||||
let commandToWrite: string;
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
commandToWrite = `echo "${startDelimiter}"; { { ${params.command} > "${tempStdoutPath}" 2> "${tempStderrPath}"; } & } 2>/dev/null; __LAST_PID=$!; echo "${pidDelimiter}$__LAST_PID" >&2; echo "${exitCodeDelimiter}$?" >&2; echo "${endDelimiter}$?" >&1\n`;
|
||||
} else if (!isBackgroundTask) {
|
||||
commandToWrite = `echo "${startDelimiter}"; ${params.command}; __EXIT_CODE=$?; echo "${exitCodeDelimiter}$__EXIT_CODE" >&2; echo "${endDelimiter}$__EXIT_CODE" >&1\n`;
|
||||
} else {
|
||||
return originalReject(
|
||||
new Error(
|
||||
'Internal setup error: Missing temporary file paths for background execution.',
|
||||
),
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (this.bashProcess?.stdin?.writable) {
|
||||
this.bashProcess.stdin.write(commandToWrite, (err) => {
|
||||
if (err) {
|
||||
console.error(
|
||||
`Error writing command "${params.command}" to bash stdin (callback):`,
|
||||
err,
|
||||
);
|
||||
const listenersToClean = { onStdoutData, onStderrData };
|
||||
cleanupListeners(listenersToClean);
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch(
|
||||
(e) => console.warn(`Cleanup failed: ${e.message}`),
|
||||
);
|
||||
}
|
||||
originalReject(
|
||||
new Error(
|
||||
`Shell stdin write error: ${err.message}. Command likely did not execute.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
'Shell stdin is not writable or process closed when attempting to write command.',
|
||||
);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
console.error(
|
||||
`Error writing command "${params.command}" to bash stdin (sync):`,
|
||||
e,
|
||||
);
|
||||
const listenersToClean = { onStdoutData, onStderrData };
|
||||
cleanupListeners(listenersToClean);
|
||||
if (isBackgroundTask && tempStdoutPath && tempStderrPath) {
|
||||
this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) =>
|
||||
console.warn(`Cleanup failed: ${err.message}`),
|
||||
);
|
||||
}
|
||||
originalReject(
|
||||
new Error(
|
||||
`Shell stdin write exception: ${getErrorMessage(e)}. Command likely did not execute.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async inspectBackgroundProcess(
|
||||
pid: number,
|
||||
command: string,
|
||||
cwd: string,
|
||||
initialStdout: string,
|
||||
initialStderr: string,
|
||||
tempStdoutPath: string,
|
||||
tempStderrPath: string,
|
||||
resolve: (value: ToolResult | PromiseLike<ToolResult>) => void,
|
||||
): Promise<void> {
|
||||
let finalStdout = '';
|
||||
let finalStderr = '';
|
||||
let llmAnalysis = '';
|
||||
let fileReadError = '';
|
||||
try {
|
||||
const { status, summary } = await this.backgroundTerminalAnalyzer.analyze(
|
||||
pid,
|
||||
tempStdoutPath,
|
||||
tempStderrPath,
|
||||
command,
|
||||
);
|
||||
if (status === 'Unknown') llmAnalysis = `LLM analysis failed: ${summary}`;
|
||||
else llmAnalysis = summary;
|
||||
} catch (llmerror: unknown) {
|
||||
console.error(
|
||||
`LLM analysis failed for PID ${pid} command "${command}":`,
|
||||
llmerror,
|
||||
);
|
||||
llmAnalysis = `LLM analysis failed: ${getErrorMessage(llmerror)}`;
|
||||
}
|
||||
try {
|
||||
finalStdout = await fs.readFile(tempStdoutPath, 'utf-8');
|
||||
finalStderr = await fs.readFile(tempStderrPath, 'utf-8');
|
||||
} catch (err: unknown) {
|
||||
console.error(`Error reading temp output files for PID ${pid}:`, err);
|
||||
fileReadError = `\nWarning: Failed to read temporary output files (${getErrorMessage(err)}). Final output may be incomplete.`;
|
||||
}
|
||||
await this.cleanupTempFiles(tempStdoutPath, tempStderrPath);
|
||||
const truncatedFinalStdout = this.truncateOutput(finalStdout);
|
||||
const truncatedFinalStderr = this.truncateOutput(finalStderr);
|
||||
resolve({
|
||||
llmContent: `Background Command: ${command}\nLaunched in: ${cwd}\nPID: ${pid}\n--- LLM Analysis ---\n${llmAnalysis}\n--- Final Stdout (from ${path.basename(tempStdoutPath)}) ---\n${truncatedFinalStdout}\n--- Final Stderr (from ${path.basename(tempStderrPath)}) ---\n${truncatedFinalStderr}\n--- Launch Stdout ---\n${initialStdout}\n--- Launch Stderr ---\n${initialStderr}${fileReadError}`,
|
||||
returnDisplay: `(PID: ${pid}): ${this.truncateOutput(llmAnalysis, 200)}`,
|
||||
});
|
||||
}
|
||||
|
||||
private async cleanupTempFiles(
|
||||
stdoutPath: string | null,
|
||||
stderrPath: string | null,
|
||||
): Promise<void> {
|
||||
const unlinkQuietly = async (filePath: string | null) => {
|
||||
if (!filePath) return;
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
} catch (err: unknown) {
|
||||
if (!isNodeError(err) || err.code !== 'ENOENT') {
|
||||
console.warn(
|
||||
`Failed to delete temporary file '${filePath}': ${getErrorMessage(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all([unlinkQuietly(stdoutPath), unlinkQuietly(stderrPath)]);
|
||||
}
|
||||
|
||||
private getCurrentShellCwd(): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (
|
||||
!this.bashProcess ||
|
||||
!this.bashProcess.stdin?.writable ||
|
||||
this.bashProcess.killed
|
||||
) {
|
||||
return reject(
|
||||
new Error(
|
||||
'Shell not running, stdin not writable, or killed for PWD check',
|
||||
),
|
||||
);
|
||||
}
|
||||
const pwdUuid = crypto.randomUUID();
|
||||
const pwdDelimiter = `::PWD_${pwdUuid}::`;
|
||||
let pwdOutput = '';
|
||||
let onPwdData: ((data: Buffer) => void) | null = null;
|
||||
let onPwdError: ((data: Buffer) => void) | null = null;
|
||||
let pwdTimeoutId: NodeJS.Timeout | null = null;
|
||||
let finished = false;
|
||||
const cleanupPwdListeners = (err?: Error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
if (pwdTimeoutId) clearTimeout(pwdTimeoutId);
|
||||
pwdTimeoutId = null;
|
||||
const stdoutListener = onPwdData;
|
||||
const stderrListener = onPwdError;
|
||||
onPwdData = null;
|
||||
onPwdError = null;
|
||||
if (this.bashProcess && !this.bashProcess.killed) {
|
||||
if (stdoutListener)
|
||||
this.bashProcess.stdout.removeListener('data', stdoutListener);
|
||||
if (stderrListener)
|
||||
this.bashProcess.stderr.removeListener('data', stderrListener);
|
||||
}
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(pwdOutput.trim());
|
||||
}
|
||||
};
|
||||
onPwdData = (data: Buffer) => {
|
||||
if (!onPwdData) return;
|
||||
const dataStr = data.toString();
|
||||
const delimiterIndex = dataStr.indexOf(pwdDelimiter);
|
||||
if (delimiterIndex !== -1) {
|
||||
pwdOutput += dataStr.substring(0, delimiterIndex);
|
||||
cleanupPwdListeners();
|
||||
} else {
|
||||
pwdOutput += dataStr;
|
||||
}
|
||||
};
|
||||
onPwdError = (data: Buffer) => {
|
||||
if (!onPwdError) return;
|
||||
const dataStr = data.toString();
|
||||
console.error(`Error during PWD check: ${dataStr}`);
|
||||
cleanupPwdListeners(
|
||||
new Error(
|
||||
`Stderr received during pwd check: ${this.truncateOutput(dataStr, 100)}`,
|
||||
),
|
||||
);
|
||||
};
|
||||
this.bashProcess.stdout.on('data', onPwdData);
|
||||
this.bashProcess.stderr.on('data', onPwdError);
|
||||
pwdTimeoutId = setTimeout(() => {
|
||||
cleanupPwdListeners(new Error('Timeout waiting for pwd response'));
|
||||
}, 5000);
|
||||
try {
|
||||
const pwdCommand = `printf "%s" "$PWD"; printf "${pwdDelimiter}";\n`;
|
||||
if (this.bashProcess?.stdin?.writable) {
|
||||
this.bashProcess.stdin.write(pwdCommand, (err) => {
|
||||
if (err) {
|
||||
console.error('Error writing pwd command (callback):', err);
|
||||
cleanupPwdListeners(
|
||||
new Error(`Failed to write pwd command: ${err.message}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw new Error('Shell stdin not writable for pwd command.');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
console.error('Exception writing pwd command:', e);
|
||||
cleanupPwdListeners(
|
||||
new Error(`Exception writing pwd command: ${getErrorMessage(e)}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private truncateOutput(output: string, limit?: number): string {
|
||||
const effectiveLimit = limit ?? this.outputLimit;
|
||||
if (output.length > effectiveLimit) {
|
||||
return (
|
||||
output.substring(0, effectiveLimit) +
|
||||
`\n... [Output truncated at ${effectiveLimit} characters]`
|
||||
);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private clearQueue(error: Error) {
|
||||
const queue = this.commandQueue;
|
||||
this.commandQueue = [];
|
||||
queue.forEach(({ resolve, params }) =>
|
||||
resolve({
|
||||
llmContent: `Command cancelled: ${params.command}\nReason: ${error.message}`,
|
||||
returnDisplay: `Command Cancelled: ${error.message}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.rejectShellReady?.(
|
||||
new Error('BashTool destroyed during initialization or operation.'),
|
||||
);
|
||||
this.rejectShellReady = undefined;
|
||||
this.resolveShellReady = undefined;
|
||||
this.clearQueue(new Error('BashTool is being destroyed.'));
|
||||
try {
|
||||
this.currentCommandCleanup?.();
|
||||
} catch (e) {
|
||||
console.warn('Error during current command cleanup:', e);
|
||||
}
|
||||
if (this.bashProcess) {
|
||||
const proc = this.bashProcess;
|
||||
const pid = proc.pid;
|
||||
this.bashProcess = null;
|
||||
proc.stdout?.removeAllListeners();
|
||||
proc.stderr?.removeAllListeners();
|
||||
proc.removeAllListeners('error');
|
||||
proc.removeAllListeners('close');
|
||||
proc.stdin?.end();
|
||||
try {
|
||||
proc.kill('SIGTERM');
|
||||
setTimeout(() => {
|
||||
if (!proc.killed) {
|
||||
proc.kill('SIGKILL');
|
||||
}
|
||||
}, 500);
|
||||
} catch (e: unknown) {
|
||||
console.warn(
|
||||
`Error trying to kill bash process PID: ${pid}: ${getErrorMessage(e)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,446 +0,0 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { SchemaUnion, Type } from '@google/genai';
|
||||
import { getErrorMessage, isNodeError } from '../utils/errors.js';
|
||||
import { GeminiClient } from '../core/client.js';
|
||||
import { Config } from '../config/config.js';
|
||||
import { promises as fs } from 'fs';
|
||||
import { exec as _exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
type AnalysisStatus =
|
||||
| 'Running'
|
||||
| 'SuccessReported'
|
||||
| 'ErrorReported'
|
||||
| 'Unknown'
|
||||
| 'AnalysisFailed';
|
||||
|
||||
const execAsync = promisify(_exec);
|
||||
|
||||
// Identifier for the background process (e.g., PID)
|
||||
// Using `unknown` allows more flexibility than `object` while still being type-safe
|
||||
export type ProcessHandle = number | string | unknown;
|
||||
|
||||
// Represents the structure expected from a successful LLM analysis call
|
||||
export interface AnalysisResult {
|
||||
summary: string;
|
||||
inferredStatus: 'Running' | 'SuccessReported' | 'ErrorReported' | 'Unknown';
|
||||
}
|
||||
|
||||
export interface AnalysisFailure {
|
||||
error: string;
|
||||
inferredStatus: 'AnalysisFailed';
|
||||
}
|
||||
|
||||
function isAnalysisFailure(
|
||||
result: AnalysisResult | AnalysisFailure,
|
||||
): result is AnalysisFailure {
|
||||
return (result as AnalysisFailure).inferredStatus === 'AnalysisFailed';
|
||||
}
|
||||
|
||||
export interface FinalAnalysisOutcome {
|
||||
status: string; // e.g., 'Completed_SuccessReported', 'TimedOut_Running', 'AnalysisFailed'
|
||||
summary: string; // Final summary or error message
|
||||
}
|
||||
|
||||
export class BackgroundTerminalAnalyzer {
|
||||
private geminiClient: GeminiClient | null = null;
|
||||
private readonly maxOutputAnalysisLength = 20000;
|
||||
private pollIntervalMs: number;
|
||||
private maxAttempts: number;
|
||||
private initialDelayMs: number;
|
||||
|
||||
constructor(
|
||||
config: Config,
|
||||
options: {
|
||||
pollIntervalMs?: number;
|
||||
maxAttempts?: number;
|
||||
initialDelayMs?: number;
|
||||
} = {},
|
||||
) {
|
||||
try {
|
||||
this.geminiClient = new GeminiClient(config);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Failed to initialize GeminiClient in BackgroundTerminalAnalyzer:',
|
||||
error,
|
||||
);
|
||||
// Set client to null so analyzeOutput handles it
|
||||
this.geminiClient = null;
|
||||
}
|
||||
this.pollIntervalMs = options.pollIntervalMs ?? 5000; // Default 5 seconds
|
||||
this.maxAttempts = options.maxAttempts ?? 6; // Default 6 attempts (approx 30s total)
|
||||
this.initialDelayMs = options.initialDelayMs ?? 500; // Default 0.5s initial delay
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls the output of a background process using an LLM
|
||||
* until a conclusive status is determined or timeout occurs.
|
||||
* @param pid The handle/identifier of the background process (typically PID number).
|
||||
* @param tempStdoutFilePath Path to the temporary file capturing stdout.
|
||||
* @param tempStderrFilePath Path to the temporary file capturing stderr.
|
||||
* @param command The command string that was executed (for context in prompts).
|
||||
* @returns A promise resolving to the final analysis outcome.
|
||||
*/
|
||||
async analyze(
|
||||
pid: ProcessHandle,
|
||||
tempStdoutFilePath: string,
|
||||
tempStderrFilePath: string,
|
||||
command: string,
|
||||
): Promise<FinalAnalysisOutcome> {
|
||||
// --- Validate PID ---
|
||||
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
|
||||
console.error(
|
||||
`BackgroundTerminalAnalyzer: Invalid or non-numeric PID provided (${pid}). Analysis cannot proceed.`,
|
||||
);
|
||||
return {
|
||||
status: 'AnalysisFailed',
|
||||
summary: 'Invalid PID provided for analysis.',
|
||||
};
|
||||
}
|
||||
|
||||
// --- Initial Delay ---
|
||||
// Wait briefly before the first check to allow the process to initialize
|
||||
// and potentially write initial output.
|
||||
await new Promise((resolve) => setTimeout(resolve, this.initialDelayMs));
|
||||
|
||||
let attempts = 0;
|
||||
let lastAnalysisResult: AnalysisResult | AnalysisFailure | null = null;
|
||||
|
||||
while (attempts < this.maxAttempts) {
|
||||
attempts++;
|
||||
let currentStdout = '';
|
||||
let currentStderr = '';
|
||||
|
||||
// --- Robust File Reading ---
|
||||
try {
|
||||
currentStdout = await fs.readFile(tempStdoutFilePath, 'utf-8');
|
||||
} catch (error: unknown) {
|
||||
// If file doesn't exist yet or isn't readable, treat as empty, but log warning
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
console.warn(
|
||||
`Attempt ${attempts}: Failed to read stdout file ${tempStdoutFilePath}: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
currentStderr = await fs.readFile(tempStderrFilePath, 'utf-8');
|
||||
} catch (error: unknown) {
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
console.warn(
|
||||
`Attempt ${attempts}: Failed to read stderr file ${tempStderrFilePath}: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Process Status Check ---
|
||||
let isRunning = false;
|
||||
try {
|
||||
// Check if process is running *before* the final analysis if it seems to have ended
|
||||
isRunning = await this.isProcessRunning(pid);
|
||||
if (!isRunning) {
|
||||
// Reread files one last time in case output was written just before exit
|
||||
try {
|
||||
currentStdout = await fs.readFile(tempStdoutFilePath, 'utf-8');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
currentStderr = await fs.readFile(tempStderrFilePath, 'utf-8');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
lastAnalysisResult = await this.performLlmAnalysis(
|
||||
currentStdout,
|
||||
currentStderr,
|
||||
command,
|
||||
pid,
|
||||
);
|
||||
|
||||
if (isAnalysisFailure(lastAnalysisResult)) {
|
||||
return {
|
||||
status: 'Completed_AnalysisFailed',
|
||||
summary: `Process ended. Final analysis failed: ${lastAnalysisResult.error}`,
|
||||
};
|
||||
}
|
||||
// Append ProcessEnded to the status determined by the final analysis
|
||||
return {
|
||||
status: 'Completed_' + lastAnalysisResult.inferredStatus,
|
||||
summary: `Process ended. Final analysis summary: ${lastAnalysisResult.summary}`,
|
||||
};
|
||||
}
|
||||
} catch (procCheckError: unknown) {
|
||||
// Log the error but allow polling to continue, as log analysis might still be useful
|
||||
console.warn(
|
||||
`Could not check process status for PID ${pid} on attempt ${attempts}: ${getErrorMessage(procCheckError)}`,
|
||||
);
|
||||
// Decide if you want to bail out here or continue analysis based on logs only
|
||||
// For now, we continue.
|
||||
}
|
||||
|
||||
// --- LLM Analysis ---
|
||||
lastAnalysisResult = await this.performLlmAnalysis(
|
||||
currentStdout,
|
||||
currentStderr,
|
||||
command,
|
||||
pid,
|
||||
);
|
||||
|
||||
if (isAnalysisFailure(lastAnalysisResult)) {
|
||||
console.error(
|
||||
`LLM Analysis failed for PID ${pid} on attempt ${attempts}:`,
|
||||
lastAnalysisResult.error,
|
||||
);
|
||||
// Stop polling on analysis failure, returning the specific failure status
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.error,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Exit Conditions ---
|
||||
if (
|
||||
lastAnalysisResult.inferredStatus === 'SuccessReported' ||
|
||||
lastAnalysisResult.inferredStatus === 'ErrorReported'
|
||||
) {
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.summary,
|
||||
};
|
||||
}
|
||||
|
||||
// Heuristic: If the process seems stable and 'Running' after several checks,
|
||||
// return that status without waiting for the full timeout. Adjust threshold as needed.
|
||||
const runningExitThreshold = Math.floor(this.maxAttempts / 3) + 1; // e.g., exit after attempt 4 if maxAttempts is 6
|
||||
if (
|
||||
attempts >= runningExitThreshold &&
|
||||
lastAnalysisResult.inferredStatus === 'Running'
|
||||
) {
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.summary,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Wait before next poll ---
|
||||
if (attempts < this.maxAttempts) {
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, this.pollIntervalMs),
|
||||
);
|
||||
}
|
||||
} // End while loop
|
||||
|
||||
// --- Timeout Condition ---
|
||||
console.warn(
|
||||
`Polling timed out for PID ${pid} after ${this.maxAttempts} attempts.`,
|
||||
);
|
||||
|
||||
// Determine final status based on the last successful analysis (if any)
|
||||
const finalStatus =
|
||||
lastAnalysisResult && !isAnalysisFailure(lastAnalysisResult)
|
||||
? `TimedOut_${lastAnalysisResult.inferredStatus}` // e.g., TimedOut_Running
|
||||
: 'TimedOut_AnalysisFailed'; // If last attempt failed or no analysis succeeded
|
||||
|
||||
const finalSummary =
|
||||
lastAnalysisResult && !isAnalysisFailure(lastAnalysisResult)
|
||||
? `Polling timed out after ${this.maxAttempts} attempts. Last known summary: ${lastAnalysisResult.summary}`
|
||||
: lastAnalysisResult && isAnalysisFailure(lastAnalysisResult)
|
||||
? `Polling timed out; last analysis attempt failed: ${lastAnalysisResult}`
|
||||
: `Polling timed out after ${this.maxAttempts} attempts without any successful analysis.`;
|
||||
|
||||
return { status: finalStatus, summary: finalSummary };
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the background process is still running using OS-specific methods.
|
||||
* @param pid Process handle/identifier (expects a number for standard checks).
|
||||
* @returns True if running, false otherwise.
|
||||
* @throws Error if the check itself fails critically (e.g., command not found, permissions).
|
||||
*/
|
||||
private async isProcessRunning(pid: ProcessHandle): Promise<boolean> {
|
||||
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
|
||||
console.warn(
|
||||
`isProcessRunning: Invalid PID provided (${pid}). Assuming not running.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
// Windows: Use tasklist command
|
||||
const command = `tasklist /FI "PID eq ${pid}" /NH`; // /NH for no header
|
||||
const { stdout } = await execAsync(command);
|
||||
// Check if the output contains the process information (it will have the image name if found)
|
||||
return stdout.toLowerCase().includes('.exe'); // A simple check, adjust if needed
|
||||
}
|
||||
// Linux/macOS/Unix-like: Use kill -0 signal
|
||||
// process.kill sends signal 0 to check existence without killing
|
||||
process.kill(pid, 0);
|
||||
return true; // If no error is thrown, process exists
|
||||
} catch (error: unknown) {
|
||||
if (isNodeError(error) && error.code === 'ESRCH') {
|
||||
// ESRCH: Standard error code for "No such process" on Unix-like systems
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
process.platform === 'win32' &&
|
||||
getErrorMessage(error).includes('No tasks are running')
|
||||
) {
|
||||
// tasklist specific error when PID doesn't exist
|
||||
return false;
|
||||
}
|
||||
// Other errors (e.g., EPERM - permission denied) mean we couldn't determine status.
|
||||
// Re-throwing might be appropriate depending on desired behavior.
|
||||
// Here, we log it and cautiously return true, assuming it *might* still be running.
|
||||
console.warn(
|
||||
`isProcessRunning(${pid}) encountered error: ${getErrorMessage(error)}. Assuming process might still exist.`,
|
||||
);
|
||||
// Or you could throw the error: throw new Error(`Failed to check process status for PID ${pid}: ${error.message}`);
|
||||
return true; // Cautious assumption
|
||||
}
|
||||
}
|
||||
|
||||
private async performLlmAnalysis(
|
||||
stdoutContent: string,
|
||||
stderrContent: string,
|
||||
command: string,
|
||||
pid: number,
|
||||
): Promise<AnalysisResult | AnalysisFailure> {
|
||||
if (!this.geminiClient) {
|
||||
return {
|
||||
error: '[Analysis unavailable: Gemini client not initialized]',
|
||||
inferredStatus: 'AnalysisFailed',
|
||||
};
|
||||
}
|
||||
|
||||
const truncatedStdout =
|
||||
stdoutContent.substring(0, this.maxOutputAnalysisLength) +
|
||||
(stdoutContent.length > this.maxOutputAnalysisLength
|
||||
? '... [truncated]'
|
||||
: '');
|
||||
const truncatedStderr =
|
||||
stderrContent.substring(0, this.maxOutputAnalysisLength) +
|
||||
(stderrContent.length > this.maxOutputAnalysisLength
|
||||
? '... [truncated]'
|
||||
: '');
|
||||
|
||||
const analysisPrompt = `**Analyze Background Process Logs**
|
||||
|
||||
**Context:** A command (\`${command}\`) was executed in the background. You are analyzing the standard output (stdout) and standard error (stderr) collected so far to understand its progress and outcome. This analysis will be used to inform a user about what the command did.
|
||||
|
||||
**Input:**
|
||||
* **Command:** \`${command}\`
|
||||
* **Stdout:**
|
||||
\`\`\`
|
||||
${truncatedStdout}
|
||||
\`\`\`
|
||||
* **Stderr:**
|
||||
\`\`\`
|
||||
${truncatedStderr}
|
||||
\`\`\`
|
||||
|
||||
**Task:**
|
||||
|
||||
Based *only* on the provided stdout and stderr:
|
||||
|
||||
1. **Interpret and Summarize:** Do *not* simply repeat the logs. Analyze the content and provide a concise summary describing the significant actions, results, progress, or errors reported by the command. If logs are empty, state that no output was captured. Summaries should be formatted as markdown. Focus on the most recent or conclusive information if logs are long.
|
||||
2. **Infer Current Status:** Based *only* on the log content, infer the likely status of the command's execution as reflected *in the logs*. Choose the most appropriate status from the options defined in the schema (\`Running\`, \`SuccessReported\`, \`ErrorReported\`, \`Unknown\`). For example:
|
||||
* If logs show ongoing activity or progress messages without clear completion or error signals, use \`Running\`.
|
||||
* If logs contain explicit messages indicating successful completion or the final expected output of a successful run, use \`SuccessReported\`.
|
||||
* If logs contain error messages, stack traces, or failure indications, use \`ErrorReported\`.
|
||||
* If the logs provide insufficient information to determine a clear status (e.g., empty logs, vague messages), use \`Unknown\`.
|
||||
* If dealing with a node server, the second the port has been shown the server is considered booted, use \`SuccessReported\`.
|
||||
* *Note: This status reflects the log content, not necessarily the absolute real-time state of the OS process.*
|
||||
3. **Format Output:** Return the results as a JSON object adhering strictly to the following schema:
|
||||
|
||||
\`\`\`json
|
||||
${JSON.stringify(
|
||||
{
|
||||
// Generate the schema JSON string for the prompt context
|
||||
type: 'object',
|
||||
properties: {
|
||||
summary: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Concise markdown summary (1-3 sentences) of log interpretation.',
|
||||
},
|
||||
inferredStatus: {
|
||||
type: 'string',
|
||||
enum: ['Running', 'SuccessReported', 'ErrorReported', 'Unknown'],
|
||||
description:
|
||||
'Status inferred from logs: Running, SuccessReported, ErrorReported, Unknown',
|
||||
},
|
||||
},
|
||||
required: ['summary', 'inferredStatus'],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
\`\`\`
|
||||
|
||||
**Instructions:**
|
||||
* The \`summary\` must be an interpretation of the logs, focusing on key outcomes or activities. Prioritize recent events if logs are extensive.
|
||||
* The \`inferredStatus\` should reflect the most likely state *deduced purely from the log text provided*. Ensure it is one of the specified enum values.`;
|
||||
|
||||
const schema: SchemaUnion = {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
summary: {
|
||||
type: Type.STRING,
|
||||
description:
|
||||
'Concise markdown summary (1-3 sentences) of log interpretation.',
|
||||
},
|
||||
inferredStatus: {
|
||||
type: Type.STRING,
|
||||
description:
|
||||
'Status inferred from logs: Running, SuccessReported, ErrorReported, Unknown',
|
||||
enum: ['Running', 'SuccessReported', 'ErrorReported', 'Unknown'],
|
||||
},
|
||||
},
|
||||
required: ['summary', 'inferredStatus'],
|
||||
};
|
||||
|
||||
try {
|
||||
const resultJson = await this.geminiClient.generateJson(
|
||||
[{ role: 'user', parts: [{ text: analysisPrompt }] }],
|
||||
schema,
|
||||
);
|
||||
|
||||
// Validate and construct the AnalysisResult object
|
||||
const summary =
|
||||
typeof resultJson?.summary === 'string'
|
||||
? resultJson.summary
|
||||
: '[Summary unavailable]';
|
||||
|
||||
// Define valid statuses using the AnalysisStatus type (ensure it's defined above)
|
||||
const validStatuses: Array<Exclude<AnalysisStatus, 'AnalysisFailed'>> = [
|
||||
'Running',
|
||||
'SuccessReported',
|
||||
'ErrorReported',
|
||||
'Unknown',
|
||||
];
|
||||
|
||||
const statusString = resultJson?.inferredStatus as string;
|
||||
const inferredStatus = validStatuses.includes(
|
||||
statusString as Exclude<AnalysisStatus, 'AnalysisFailed'>,
|
||||
)
|
||||
? (statusString as Exclude<AnalysisStatus, 'AnalysisFailed'>)
|
||||
: 'Unknown';
|
||||
|
||||
const analysisResult: AnalysisResult = { summary, inferredStatus };
|
||||
return analysisResult;
|
||||
} catch (error: unknown) {
|
||||
console.error(`LLM Analysis Request Failed for PID ${pid}:`, error);
|
||||
const analysisFailure: AnalysisFailure = {
|
||||
error: `[Analysis failed: ${getErrorMessage(error)}]`,
|
||||
inferredStatus: 'AnalysisFailed',
|
||||
};
|
||||
return analysisFailure;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue