|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | +import * as vscode from 'vscode' |
| 6 | +import { getLogger } from '../../shared/logger/logger' |
| 7 | +import { readDirectoryRecursively } from '../../shared/utilities/workspaceUtils' |
| 8 | +import fs from '../../shared/fs/fs' |
| 9 | + |
| 10 | +const maxToolResponseSize = 30720 // 30KB |
| 11 | + |
| 12 | +enum OutputKind { |
| 13 | + Text = 'text', |
| 14 | + Json = 'json', |
| 15 | +} |
| 16 | + |
| 17 | +export interface InvokeOutput { |
| 18 | + output: { |
| 19 | + kind: OutputKind |
| 20 | + content: string |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +export interface FsReadParams { |
| 25 | + path: string |
| 26 | + readRange?: number[] |
| 27 | +} |
| 28 | + |
| 29 | +export class FsRead { |
| 30 | + private readonly fsPath: string |
| 31 | + private readonly readRange?: number[] |
| 32 | + private readonly logger = getLogger('fsRead') |
| 33 | + |
| 34 | + constructor(params: FsReadParams) { |
| 35 | + this.fsPath = params.path |
| 36 | + this.readRange = params.readRange |
| 37 | + } |
| 38 | + |
| 39 | + public async invoke(): Promise<InvokeOutput> { |
| 40 | + try { |
| 41 | + const fileUri = vscode.Uri.file(this.fsPath) |
| 42 | + let exists: boolean |
| 43 | + try { |
| 44 | + exists = await fs.exists(fileUri) |
| 45 | + if (!exists) { |
| 46 | + throw new Error(`Path: "${this.fsPath}" does not exist or cannot be accessed.`) |
| 47 | + } |
| 48 | + } catch (err) { |
| 49 | + throw new Error(`Path: "${this.fsPath}" does not exist or cannot be accessed. (${err})`) |
| 50 | + } |
| 51 | + |
| 52 | + const isFile = await fs.existsFile(fileUri) |
| 53 | + const isDirectory = await fs.existsDir(fileUri) |
| 54 | + |
| 55 | + if (isFile) { |
| 56 | + const fileContents = await this.readFile(fileUri) |
| 57 | + this.logger.info(`Read file: ${this.fsPath}, size: ${fileContents.length}`) |
| 58 | + return this.handleFileRange(fileContents) |
| 59 | + } else if (isDirectory) { |
| 60 | + const maxDepth = this.getDirectoryDepth() ?? 0 |
| 61 | + const listing = await readDirectoryRecursively(fileUri, maxDepth) |
| 62 | + return this.createOutput(listing.join('\n')) |
| 63 | + } else { |
| 64 | + throw new Error(`"${this.fsPath}" is neither a standard file nor directory.`) |
| 65 | + } |
| 66 | + } catch (error: any) { |
| 67 | + this.logger.error(`Failed to read "${this.fsPath}": ${error.message || error}`) |
| 68 | + throw new Error(`[fs_read] Failed to read "${this.fsPath}": ${error.message || error}`) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private async readFile(fileUri: vscode.Uri): Promise<string> { |
| 73 | + this.logger.info(`Reading file: ${fileUri.fsPath}`) |
| 74 | + return await fs.readFileText(fileUri) |
| 75 | + } |
| 76 | + |
| 77 | + private handleFileRange(fullText: string): InvokeOutput { |
| 78 | + if (!this.readRange || this.readRange.length === 0) { |
| 79 | + this.logger.info('No range provided. returning entire file.') |
| 80 | + return this.createOutput(this.enforceMaxSize(fullText)) |
| 81 | + } |
| 82 | + |
| 83 | + const lines = fullText.split('\n') |
| 84 | + const [start, end] = this.parseLineRange(lines.length, this.readRange) |
| 85 | + if (start > end) { |
| 86 | + this.logger.error(`Invalid range: ${this.readRange.join('-')}`) |
| 87 | + return this.createOutput('') |
| 88 | + } |
| 89 | + |
| 90 | + this.logger.info(`Reading file: ${this.fsPath}, lines ${start + 1}-${end + 1}`) |
| 91 | + const slice = lines.slice(start, end + 1).join('\n') |
| 92 | + return this.createOutput(this.enforceMaxSize(slice)) |
| 93 | + } |
| 94 | + |
| 95 | + private parseLineRange(lineCount: number, range: number[]): [number, number] { |
| 96 | + const startIdx = range[0] |
| 97 | + let endIdx = range.length >= 2 ? range[1] : undefined |
| 98 | + |
| 99 | + if (endIdx === undefined) { |
| 100 | + endIdx = -1 |
| 101 | + } |
| 102 | + |
| 103 | + const convert = (i: number): number => { |
| 104 | + return i < 0 ? lineCount + i : i - 1 |
| 105 | + } |
| 106 | + |
| 107 | + const finalStart = Math.max(0, Math.min(lineCount - 1, convert(startIdx))) |
| 108 | + const finalEnd = Math.max(0, Math.min(lineCount - 1, convert(endIdx))) |
| 109 | + return [finalStart, finalEnd] |
| 110 | + } |
| 111 | + |
| 112 | + private getDirectoryDepth(): number | undefined { |
| 113 | + if (!this.readRange || this.readRange.length === 0) { |
| 114 | + return 0 |
| 115 | + } |
| 116 | + return this.readRange[0] |
| 117 | + } |
| 118 | + |
| 119 | + private enforceMaxSize(content: string): string { |
| 120 | + const byteCount = Buffer.byteLength(content, 'utf8') |
| 121 | + if (byteCount > maxToolResponseSize) { |
| 122 | + throw new Error( |
| 123 | + `This tool only supports reading ${maxToolResponseSize} bytes at a time. |
| 124 | + You tried to read ${byteCount} bytes. Try executing with fewer lines specified.` |
| 125 | + ) |
| 126 | + } |
| 127 | + return content |
| 128 | + } |
| 129 | + |
| 130 | + private createOutput(content: string): InvokeOutput { |
| 131 | + return { |
| 132 | + output: { |
| 133 | + kind: OutputKind.Text, |
| 134 | + content: content, |
| 135 | + }, |
| 136 | + } |
| 137 | + } |
| 138 | +} |
0 commit comments