ai-code-agents 0.1.0-beta.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -23
- package/dist/index.cjs +703 -635
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +289 -567
- package/dist/index.d.ts +289 -567
- package/dist/index.js +752 -639
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +27 -7
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/environments/docker-environment.ts","../src/util/escape-command-arg.ts","../src/util/validate-relative-path.ts","../src/environments/filesystem-environment-base.ts","../src/environments/command-line-environment-base.ts","../src/environments/unix-environment-base.ts","../src/environments/mock-filesystem-environment.ts","../src/environments/node-filesystem-environment.ts","../src/environments/unsafe-local-environment.ts","../src/tools/copy-file-tool.ts","../src/types.ts","../src/tools/tool-base.ts","../src/tools/environment-tool-base.ts","../src/tools/delete-file-tool.ts","../src/tools/edit-file-tool.ts","../src/tools/get-project-file-structure-tool.ts","../src/util/build-tree-from-files.ts","../src/tools/glob-tool.ts","../src/util/glob-to-reg-exp.ts","../src/tools/list-directory-tool.ts","../src/tools/move-file-tool.ts","../src/tools/read-file-tool.ts","../src/util/get-language-identifier-from-file-path.ts","../src/tools/read-many-files-tool.ts","../src/tools/run-command-tool.ts","../src/tools/write-file-tool.ts","../src/agent-creators.ts","../src/tools/submit-tool.ts","../src/instructions.ts","../src/tool-creators.ts","../src/util/get-step-log.ts","../src/environment-creators.ts"],"sourcesContent":["export * from './environments/docker-environment';\nexport * from './environments/mock-filesystem-environment';\nexport * from './environments/node-filesystem-environment';\nexport * from './environments/unsafe-local-environment';\n\nexport * from './tools/copy-file-tool';\nexport * from './tools/delete-file-tool';\nexport * from './tools/edit-file-tool';\nexport * from './tools/get-project-file-structure-tool';\nexport * from './tools/glob-tool';\nexport * from './tools/list-directory-tool';\nexport * from './tools/move-file-tool';\nexport * from './tools/read-file-tool';\nexport * from './tools/read-many-files-tool';\nexport * from './tools/run-command-tool';\nexport * from './tools/write-file-tool';\n\nexport * from './agent-creators';\nexport * from './environment-creators';\nexport * from './tool-creators';\nexport * from './types';\n","import { exec } from 'node:child_process';\nimport { escapeCommandArg } from '../util/escape-command-arg';\nimport { UnixEnvironmentBase } from './unix-environment-base';\n\nexport type DockerEnvironmentConfig = {\n containerId: string;\n directoryPath?: string;\n};\n\nexport const DockerEnvironmentName = 'docker';\n\n/**\n * A Docker-based execution environment that interacts with a specified Docker container.\n */\nexport class DockerEnvironment extends UnixEnvironmentBase<DockerEnvironmentConfig> {\n protected readonly _commandPrefix: string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: DockerEnvironmentConfig) {\n super(config);\n\n const { directoryPath } = this._envConfig;\n this._commandPrefix = directoryPath\n ? `cd ${escapeCommandArg(directoryPath)} && `\n : '';\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return DockerEnvironmentName;\n }\n\n /**\n * Executes a command in the environment and returns the exit code, stdout, and stderr.\n *\n * @param command - The command to execute.\n * @returns A promise that resolves to a tuple containing the exit code, stdout, and stderr.\n */\n protected async executeCommand(\n command: string,\n ): Promise<[number, string, string]> {\n return new Promise((resolve) => {\n exec(\n `docker exec ${this._envConfig.containerId} ${this._commandPrefix}${command}`,\n (error, stdout, stderr) => {\n const exitCode = error ? (error.code ?? 1) : 0;\n resolve([exitCode, stdout, stderr]);\n },\n );\n });\n }\n}\n","/**\n * Escapes a string to be used as a single command-line argument in a POSIX-compliant shell.\n *\n * The string is wrapped in single quotes, and any existing single quotes are\n * safely escaped. This prevents the shell from interpreting special\n * characters or expanding variables.\n *\n * @param arg - The argument string to escape.\n * @returns The escaped and quoted argument string.\n */\nexport function escapeCommandArg(arg: string): string {\n if ('' === arg) {\n return \"''\";\n }\n // 1. Replace all single quotes with '\\''\n // 2. Wrap the entire string in single quotes.\n // e.g., \"it's a test\" -> \"'it'\\\\''s a test'\"\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","import * as path from 'node:path';\n\n/**\n * Validates that the given path is a relative path and does not contain path traversal.\n *\n * @param filePath - The file path to validate.\n */\nexport function validateRelativePath(filePath: string): void {\n if (path.isAbsolute(filePath)) {\n throw new Error('Absolute paths are not allowed.');\n }\n if (filePath.startsWith('~')) {\n throw new Error('Paths starting with \"~\" are not allowed.');\n }\n if (filePath.includes('\\0')) {\n throw new Error('Paths must not contain null bytes.');\n }\n\n const normalizedPath = path.normalize(filePath);\n if (normalizedPath.startsWith('..')) {\n throw new Error('Path traversal is not allowed.');\n }\n}\n","import { validateRelativePath } from '../util/validate-relative-path';\nimport type {\n FilesystemEnvironmentInterface,\n ReadFileResult,\n WriteFileResult,\n DeleteFileResult,\n MoveFileResult,\n CopyFileResult,\n} from '../types';\n\n/**\n * Base class for a filesystem-based execution environment.\n */\nexport abstract class FilesystemEnvironmentBase<EnvironmentConfig>\n implements FilesystemEnvironmentInterface\n{\n protected _envConfig: EnvironmentConfig;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: EnvironmentConfig) {\n this._envConfig = config;\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n abstract get name(): string;\n\n /**\n * Reads the content of a file at the specified path.\n *\n * @param path - The path to the file to read, relative to the project directory.\n * @returns A promise that resolves to a ReadFileResult.\n */\n async readFile(path: string): Promise<ReadFileResult> {\n validateRelativePath(path);\n\n if (!(await this.fileExists(path))) {\n throw new Error(`File not found: ${path}`);\n }\n\n const content = await this.readFileContent(path);\n\n return {\n path,\n content,\n };\n }\n\n /**\n * Writes content to a file at the specified path.\n *\n * If a file is already present at the path, it will be overwritten.\n *\n * @param path - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n * @returns A promise that resolves to a WriteFileResult.\n */\n async writeFile(path: string, content: string): Promise<WriteFileResult> {\n validateRelativePath(path);\n\n await this.writeFileContent(path, content);\n\n return {\n path,\n message: 'File written successfully.',\n };\n }\n\n /**\n * Deletes a file at the specified path.\n *\n * @param path - The path to the file to delete, relative to the project directory.\n * @returns A promise that resolves to a DeleteFileResult.\n */\n async deleteFile(path: string): Promise<DeleteFileResult> {\n validateRelativePath(path);\n\n if (!(await this.fileExists(path))) {\n return {\n path,\n message: 'File was already deleted.',\n };\n }\n\n await this.deleteFileContent(path);\n\n return {\n path,\n message: 'File deleted successfully.',\n };\n }\n\n /**\n * Moves a file from a source path to a destination path.\n *\n * If a file is already present at the destination path, it will be overwritten.\n *\n * @param sourcePath - The path to the file to move.\n * @param destinationPath - The path to move the file to.\n * @returns A promise that resolves to a MoveFileResult.\n */\n async moveFile(\n sourcePath: string,\n destinationPath: string,\n ): Promise<MoveFileResult> {\n validateRelativePath(sourcePath);\n validateRelativePath(destinationPath);\n\n if (!(await this.fileExists(sourcePath))) {\n throw new Error(`File not found: ${sourcePath}`);\n }\n\n await this.moveFileContent(sourcePath, destinationPath);\n\n return {\n sourcePath,\n destinationPath,\n message: 'File moved successfully.',\n };\n }\n\n /**\n * Copies a file from a source path to a destination path.\n *\n * If a file is already present at the destination path, it will be overwritten.\n *\n * @param sourcePath - The path to the file to copy.\n * @param destinationPath - The path to copy the file to.\n * @returns A promise that resolves to a CopyFileResult.\n */\n async copyFile(\n sourcePath: string,\n destinationPath: string,\n ): Promise<CopyFileResult> {\n validateRelativePath(sourcePath);\n validateRelativePath(destinationPath);\n\n if (!(await this.fileExists(sourcePath))) {\n throw new Error(`File not found: ${sourcePath}`);\n }\n\n await this.copyFileContent(sourcePath, destinationPath);\n\n return {\n sourcePath,\n destinationPath,\n message: 'File copied successfully.',\n };\n }\n\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected abstract fileExists(relativePath: string): Promise<boolean>;\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected abstract readFileContent(relativePath: string): Promise<string>;\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected abstract writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void>;\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected abstract deleteFileContent(relativePath: string): Promise<void>;\n\n /**\n * Moves the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally moves the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to move, relative to the project directory.\n * @param relativeDestinationPath - The path to move the file to, relative to the project directory.\n */\n protected async moveFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const content = await this.readFileContent(relativeSourcePath);\n this.writeFileContent(relativeDestinationPath, content);\n this.deleteFileContent(relativeSourcePath);\n }\n\n /**\n * Copies the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally copies the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to copy, relative to the project directory.\n * @param relativeDestinationPath - The path to copy the file to, relative to the project directory.\n */\n protected async copyFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const content = await this.readFileContent(relativeSourcePath);\n this.writeFileContent(relativeDestinationPath, content);\n }\n}\n","import type {\n CommandLineEnvironmentInterface,\n RunCommandResult,\n} from '../types';\nimport { FilesystemEnvironmentBase } from './filesystem-environment-base';\n\n/**\n * Base class for a command-line based execution environment.\n */\nexport abstract class CommandLineEnvironmentBase<EnvironmentConfig>\n extends FilesystemEnvironmentBase<EnvironmentConfig>\n implements CommandLineEnvironmentInterface\n{\n /**\n * Runs a CLI command in environment.\n *\n * @param command - The command to run.\n * @returns A promise that resolves to a RunCommandResult.\n */\n async runCommand(command: string): Promise<RunCommandResult> {\n const [exitCode, stdout, stderr] = await this.executeCommand(command);\n return {\n command,\n exitCode,\n stdout,\n stderr,\n };\n }\n\n /**\n * Executes a command in the environment and returns the exit code, stdout, and stderr.\n *\n * @param command - The command to execute.\n * @returns A promise that resolves to a tuple containing the exit code, stdout, and stderr.\n */\n protected abstract executeCommand(\n command: string,\n ): Promise<[number, string, string]>;\n}\n","import { escapeCommandArg } from '../util/escape-command-arg';\nimport { CommandLineEnvironmentBase } from './command-line-environment-base';\n\n/**\n * Base class for a Unix-like command line execution environment.\n */\nexport abstract class UnixEnvironmentBase<\n EnvironmentConfig,\n> extends CommandLineEnvironmentBase<EnvironmentConfig> {\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected async fileExists(relativePath: string): Promise<boolean> {\n const command = `if [ -e ${escapeCommandArg(relativePath)} ]; then echo \"yes\"; else echo \"no\"; fi`;\n const { exitCode, stdout } = await this.runCommand(command);\n return exitCode === 0 && stdout.trim() === 'yes';\n }\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected async readFileContent(relativePath: string): Promise<string> {\n const command = `cat ${escapeCommandArg(relativePath)}`;\n const { exitCode, stdout } = await this.runCommand(command);\n return exitCode === 0 ? stdout : '';\n }\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected async writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void> {\n const command = `sh -c \"echo ${escapeCommandArg(\n content,\n )} > ${escapeCommandArg(relativePath)}\"`;\n const { exitCode, stderr } = await this.runCommand(command);\n if (exitCode !== 0) {\n throw new Error(`Failed to write file: ${stderr || 'Unknown error'}`);\n }\n }\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected async deleteFileContent(relativePath: string): Promise<void> {\n const command = `rm ${escapeCommandArg(relativePath)}`;\n const { exitCode, stderr } = await this.runCommand(command);\n if (exitCode !== 0) {\n throw new Error(`Failed to delete file: ${stderr || 'Unknown error'}`);\n }\n }\n\n /**\n * Moves the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally moves the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to move, relative to the project directory.\n * @param relativeDestinationPath - The path to move the file to, relative to the project directory.\n */\n protected override async moveFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const command = `mv ${escapeCommandArg(relativeSourcePath)} ${escapeCommandArg(\n relativeDestinationPath,\n )}`;\n const { exitCode, stderr } = await this.runCommand(command);\n if (exitCode !== 0) {\n throw new Error(`Failed to move file: ${stderr || 'Unknown error'}`);\n }\n }\n\n /**\n * Copies the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally copies the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to copy, relative to the project directory.\n * @param relativeDestinationPath - The path to copy the file to, relative to the project directory.\n */\n protected override async copyFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const command = `cp ${escapeCommandArg(relativeSourcePath)} ${escapeCommandArg(\n relativeDestinationPath,\n )}`;\n const result = await this.runCommand(command);\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to copy file: ${result.stderr || 'Unknown error'}`,\n );\n }\n }\n}\n","import path from 'node:path';\nimport { FilesystemEnvironmentBase } from './filesystem-environment-base';\n\nexport type MockFilesystemEnvironmentConfig = {\n initialFiles?: Map<string, string>;\n directoryPath?: string;\n};\n\nexport const MockFilesystemEnvironmentName = 'mock-filesystem';\n\n/**\n * An in-memory execution environment that simulates a filesystem.\n *\n * This environment is useful for testing purposes where you want to control the\n * filesystem state without interacting with the actual disk.\n */\nexport class MockFilesystemEnvironment extends FilesystemEnvironmentBase<MockFilesystemEnvironmentConfig> {\n protected readonly files: Map<string, string>;\n protected readonly _preparePath: (filePath: string) => string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: MockFilesystemEnvironmentConfig = {}) {\n super(config);\n\n const { initialFiles, directoryPath } = this._envConfig;\n this.files = initialFiles ?? new Map<string, string>();\n this._preparePath = directoryPath\n ? (filePath: string) => path.join(directoryPath, filePath)\n : (filePath: string) => filePath;\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return MockFilesystemEnvironmentName;\n }\n\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected async fileExists(relativePath: string): Promise<boolean> {\n return this.files.has(this._preparePath(relativePath));\n }\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected async readFileContent(relativePath: string): Promise<string> {\n return this.files.get(this._preparePath(relativePath)) ?? '';\n }\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected async writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void> {\n this.files.set(this._preparePath(relativePath), content);\n }\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected async deleteFileContent(relativePath: string): Promise<void> {\n this.files.delete(this._preparePath(relativePath));\n }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { FilesystemEnvironmentBase } from './filesystem-environment-base';\n\nexport type NodeFilesystemEnvironmentConfig = {\n directoryPath: string;\n};\n\nexport const NodeFilesystemEnvironmentName = 'node-filesystem';\n\n/**\n * A Node.js filesystem-based execution environment.\n *\n * This environment uses Node.js fs/promises APIs to provide filesystem operations\n * within a specified directory path. All relative file paths are resolved relative\n * to the configured directoryPath.\n */\nexport class NodeFilesystemEnvironment extends FilesystemEnvironmentBase<NodeFilesystemEnvironmentConfig> {\n /**\n * Constructs a new NodeFilesystemEnvironment instance.\n *\n * @param config - Environment configuration including the mandatory directoryPath.\n */\n constructor(config: NodeFilesystemEnvironmentConfig) {\n if (!config.directoryPath) {\n throw new Error('The directory path must be provided');\n }\n\n super(config);\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return NodeFilesystemEnvironmentName;\n }\n\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected async fileExists(relativePath: string): Promise<boolean> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n\n try {\n await fs.stat(absolutePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected async readFileContent(relativePath: string): Promise<string> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n return fs.readFile(absolutePath, 'utf-8');\n }\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected async writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n await fs.writeFile(absolutePath, content, 'utf-8');\n }\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected async deleteFileContent(relativePath: string): Promise<void> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n await fs.rm(absolutePath);\n }\n\n /**\n * Moves the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally moves the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to move, relative to the project directory.\n * @param relativeDestinationPath - The path to move the file to, relative to the project directory.\n */\n protected override async moveFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const sourcePath = path.join(\n this._envConfig.directoryPath,\n relativeSourcePath,\n );\n const destinationPath = path.join(\n this._envConfig.directoryPath,\n relativeDestinationPath,\n );\n await fs.rename(sourcePath, destinationPath);\n }\n}\n","import { exec } from 'node:child_process';\nimport { escapeCommandArg } from '../util/escape-command-arg';\nimport { UnixEnvironmentBase } from './unix-environment-base';\n\nexport type UnsafeLocalEnvironmentConfig = {\n directoryPath: string;\n};\n\nexport const UnsafeLocalEnvironmentName = 'unsafe-local';\n\n/**\n * A local command line execution environment in a specific directory, without any safety mechanisms.\n *\n * WARNING: This environment is unsafe because it allows unrestricted access to\n * the local file system and command line. It should only be used in controlled\n * environments where security is not a concern.\n */\nexport class UnsafeLocalEnvironment extends UnixEnvironmentBase<UnsafeLocalEnvironmentConfig> {\n protected readonly _commandPrefix: string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: UnsafeLocalEnvironmentConfig) {\n const { directoryPath } = config;\n if (!directoryPath) {\n throw new Error('The directory path must be provided');\n }\n if (!directoryPath.startsWith('/')) {\n throw new Error('The directory path must be absolute (start with \"/\")');\n }\n\n super(config);\n\n this._commandPrefix = `cd ${escapeCommandArg(directoryPath)} && `;\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return UnsafeLocalEnvironmentName;\n }\n\n /**\n * Executes a command in the environment and returns the exit code, stdout, and stderr.\n *\n * @param command - The command to execute.\n * @returns A promise that resolves to a tuple containing the exit code, stdout, and stderr.\n */\n protected async executeCommand(\n command: string,\n ): Promise<[number, string, string]> {\n return new Promise((resolve) => {\n exec(`${this._commandPrefix}${command}`, (error, stdout, stderr) => {\n const exitCode = error ? (error.code ?? 1) : 0;\n resolve([exitCode, stdout, stderr]);\n });\n });\n }\n}\n","import { z } from 'zod';\nimport {\n CopyFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const CopyFileToolName = 'copy_file';\n\nexport type CopyFileToolConfig = ToolConfig;\n\nexport const CopyFileToolInput = z.object({\n sourcePath: z.string().meta({\n description:\n 'The path to the file to copy, relative to the project directory.',\n }),\n destinationPath: z.string().meta({\n description:\n 'The path to the destination where the file should be copied, relative to the project directory. If the file already exists, it will be overwritten.',\n }),\n});\n\nexport type CopyFileToolInput = z.infer<typeof CopyFileToolInput>;\n\nexport const CopyFileToolOutput = CopyFileResult;\n\nexport type CopyFileToolOutput = z.infer<typeof CopyFileToolOutput>;\n\n/**\n * Class for the CopyFile tool.\n */\nexport class CopyFileTool extends EnvironmentToolBase<\n CopyFileToolConfig,\n CopyFileToolInput,\n CopyFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n CopyFileToolInput,\n CopyFileToolOutput\n > {\n return {\n name: CopyFileToolName,\n description: 'Copies a file from a source path to a destination path.',\n inputSchema: CopyFileToolInput,\n outputSchema: CopyFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: CopyFileToolInput,\n ): Promise<CopyFileToolOutput> {\n return env.copyFile(input.sourcePath, input.destinationPath);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: CopyFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `File \\`${output.sourcePath}\\` copied successfully to \\`${output.destinationPath}\\`.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<CopyFileToolInput, CopyFileToolOutput>> {\n return [\n {\n input: {\n sourcePath: 'src/index.ts',\n destinationPath: 'index.ts',\n },\n output: 'File `src/index.ts` copied successfully to `index.ts`.',\n },\n ];\n }\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport type { ToolCallOptions } from 'ai';\nimport * as z from 'zod';\n\nexport const ReadFileResult = z.object({\n path: z.string().meta({\n description: 'The path to the file that was read.',\n }),\n content: z.string().meta({\n description: 'The content of the file that was read.',\n }),\n});\n\nexport type ReadFileResult = z.infer<typeof ReadFileResult>;\n\nexport const WriteFileResult = z.object({\n path: z.string().meta({\n description: 'The path to the file that was written.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the write operation.',\n }),\n});\n\nexport type WriteFileResult = z.infer<typeof WriteFileResult>;\n\nexport const DeleteFileResult = z.object({\n path: z.string().meta({\n description: 'The path to the file that was deleted.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the delete operation.',\n }),\n});\n\nexport type DeleteFileResult = z.infer<typeof DeleteFileResult>;\n\nexport const MoveFileResult = z.object({\n sourcePath: z.string().meta({\n description: 'The original path of the file that was moved.',\n }),\n destinationPath: z.string().meta({\n description: 'The new path of the file that was moved to.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the move operation.',\n }),\n});\n\nexport type MoveFileResult = z.infer<typeof MoveFileResult>;\n\nexport const CopyFileResult = z.object({\n sourcePath: z.string().meta({\n description: 'The original path of the file that was copied.',\n }),\n destinationPath: z.string().meta({\n description: 'The new path of the file that was copied to.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the copy operation.',\n }),\n});\n\nexport type CopyFileResult = z.infer<typeof CopyFileResult>;\n\nexport const RunCommandResult = z.object({\n command: z.string().meta({\n description: 'The command that was executed.',\n }),\n exitCode: z.number().meta({\n description: 'The exit code of the command.',\n }),\n stdout: z.string().meta({\n description: 'The standard output of the command.',\n }),\n stderr: z.string().meta({\n description: 'The standard error output of the command.',\n }),\n});\n\nexport type RunCommandResult = z.infer<typeof RunCommandResult>;\n\nexport interface FilesystemEnvironmentInterface {\n get name(): string;\n readFile(path: string): Promise<ReadFileResult>;\n writeFile(path: string, content: string): Promise<WriteFileResult>;\n deleteFile(path: string): Promise<DeleteFileResult>;\n moveFile(\n sourcePath: string,\n destinationPath: string,\n ): Promise<MoveFileResult>;\n copyFile(\n sourcePath: string,\n destinationPath: string,\n ): Promise<CopyFileResult>;\n}\n\nexport interface CommandLineEnvironmentInterface\n extends FilesystemEnvironmentInterface {\n runCommand(command: string): Promise<RunCommandResult>;\n}\n\nexport type Environment =\n | FilesystemEnvironmentInterface\n | CommandLineEnvironmentInterface;\n\n// These types must be compatible with or subtypes of the LanguageModelV3ToolResultOutput type from '@ai-sdk/provider'.\ntype ModelTextResult = { type: 'text'; value: string };\ntype ModelTextPart = { type: 'text'; text: string };\ntype ModelMediaPart = { type: 'media'; data: string; mediaType: string };\nexport type ModelFormattedToolResult =\n | ModelTextResult\n | {\n type: 'content';\n value: Array<ModelTextPart | ModelMediaPart>;\n };\n\nexport type ToolExample<ToolInputType, ToolOutputType> = {\n input: ToolInputType;\n output: ToolOutputType | string;\n};\n\n// This interface must be compatible with the Tool interface from 'ai'.\nexport interface ToolInterface<ToolInputType, ToolOutputType> {\n get name(): string;\n get description(): string;\n get inputSchema(): FlexibleSchema<ToolInputType>;\n get outputSchema(): FlexibleSchema<ToolOutputType>;\n execute(\n input: ToolInputType,\n options: ToolCallOptions,\n ): Promise<ToolOutputType>;\n toModelOutput(output: ToolOutputType): ModelFormattedToolResult;\n get examples(): Array<ToolExample<ToolInputType, ToolOutputType>>;\n get needsApproval(): boolean;\n}\n\nexport interface EnvironmentToolInterface<\n ToolInputType,\n ToolOutputType,\n EnvironmentType,\n> extends ToolInterface<ToolInputType, ToolOutputType> {\n get environment(): EnvironmentType;\n}\n\n// Optional constructor parameter for tools.\nexport type ToolConfig = {\n name?: string;\n description?: string;\n needsApproval?: boolean;\n};\n","import type { ToolCallOptions } from 'ai';\nimport type {\n ToolInterface,\n ToolConfig as ToolBaseConfig,\n ToolExample,\n ModelFormattedToolResult,\n} from '../types';\n\ntype FlexibleInputSchema<T> = ToolInterface<T, unknown>['inputSchema'];\ntype FlexibleOutputSchema<T> = ToolInterface<unknown, T>['outputSchema'];\n\nexport type ToolMetadata<ToolInputType, ToolOutputType> = {\n name: string;\n description: string;\n inputSchema: FlexibleInputSchema<ToolInputType>;\n outputSchema: FlexibleOutputSchema<ToolOutputType>;\n needsApproval: boolean;\n};\n\n/**\n * Base class for a tool.\n */\nexport abstract class ToolBase<\n ToolConfig extends ToolBaseConfig,\n ToolInputType,\n ToolOutputType,\n> implements ToolInterface<ToolInputType, ToolOutputType>\n{\n readonly _toolConfig!: ToolConfig;\n protected readonly _name: string;\n protected readonly _description: string;\n protected readonly _inputSchema: FlexibleInputSchema<ToolInputType>;\n protected readonly _outputSchema: FlexibleOutputSchema<ToolOutputType>;\n protected readonly _needsApproval: boolean;\n\n /**\n * Constructs a new tool instance.\n *\n * @param toolConfig - Optional tool config, can be used to override some defaults.\n */\n constructor(toolConfig?: ToolConfig) {\n const {\n name: defaultName,\n description: defaultDescription,\n inputSchema,\n outputSchema,\n needsApproval: defaultNeedsApproval,\n } = this.getMetadata();\n\n this._name = toolConfig?.name || defaultName;\n this._description = toolConfig?.description || defaultDescription;\n this._inputSchema = inputSchema;\n this._outputSchema = outputSchema;\n this._needsApproval =\n toolConfig?.needsApproval !== undefined\n ? toolConfig.needsApproval\n : defaultNeedsApproval;\n }\n\n /**\n * Gets the tool name.\n *\n * @returns The tool name.\n */\n get name(): string {\n return this._name;\n }\n\n /**\n * Gets the tool description.\n *\n * @returns The tool description.\n */\n get description(): string {\n return this._description;\n }\n\n /**\n * Gets the input schema for the tool.\n *\n * @returns The input schema.\n */\n get inputSchema(): FlexibleInputSchema<ToolInputType> {\n return this._inputSchema;\n }\n\n /**\n * Gets the input schema for the tool.\n *\n * @returns The input schema.\n */\n get outputSchema(): FlexibleInputSchema<ToolOutputType> {\n return this._outputSchema;\n }\n\n /**\n * Gets whether the tool needs approval before use.\n *\n * @returns True if the tool needs approval, false otherwise.\n */\n get needsApproval(): boolean {\n return this._needsApproval;\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n abstract get examples(): Array<ToolExample<ToolInputType, ToolOutputType>>;\n\n /**\n * Executes the tool with the given input.\n *\n * @param input - The input for the tool.\n * @param options - Options from the tool call.\n * @returns A promise that resolves to the tool execution result.\n */\n abstract execute(\n input: ToolInputType,\n options: ToolCallOptions,\n ): Promise<ToolOutputType>;\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n abstract toModelOutput(output: ToolOutputType): ModelFormattedToolResult;\n\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected abstract getMetadata(): ToolMetadata<ToolInputType, ToolOutputType>;\n}\n","import type { ToolCallOptions } from 'ai';\nimport type {\n EnvironmentToolInterface,\n ToolConfig as ToolBaseConfig,\n} from '../types';\nimport { ToolBase, type ToolMetadata } from './tool-base';\n\nexport type EnvironmentToolMetadata<ToolInputType, ToolOutputType> =\n ToolMetadata<ToolInputType, ToolOutputType>;\n\n/**\n * Base class for an execution environment tool.\n */\nexport abstract class EnvironmentToolBase<\n ToolConfig extends ToolBaseConfig,\n ToolInputType,\n ToolOutputType,\n EnvironmentType,\n >\n extends ToolBase<ToolConfig, ToolInputType, ToolOutputType>\n implements\n EnvironmentToolInterface<ToolInputType, ToolOutputType, EnvironmentType>\n{\n protected readonly _environment: EnvironmentType;\n\n /**\n * Constructs a new `EnvironmentToolBase` instance.\n *\n * @param environment - The execution environment to apply the tool in.\n * @param toolConfig - Optional tool config, can be used to override some defaults.\n */\n constructor(environment: EnvironmentType, toolConfig?: ToolConfig) {\n super(toolConfig);\n\n this._environment = environment;\n }\n\n /**\n * Gets the current execution environment for the tool.\n *\n * @returns The current execution environment.\n */\n get environment(): EnvironmentType {\n return this._environment;\n }\n\n /**\n * Executes the tool with the given input.\n *\n * @param input - The input for the tool.\n * @param _options - Options from the tool call.\n * @returns A promise that resolves to the tool execution result.\n */\n override execute(\n input: ToolInputType,\n _options: ToolCallOptions,\n ): Promise<ToolOutputType> {\n return this.executeForEnvironment(this._environment, input);\n }\n\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected abstract override getMetadata(): EnvironmentToolMetadata<\n ToolInputType,\n ToolOutputType\n >;\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected abstract executeForEnvironment(\n env: EnvironmentType,\n input: ToolInputType,\n ): Promise<ToolOutputType>;\n}\n","import { z } from 'zod';\nimport {\n DeleteFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const DeleteFileToolName = 'delete_file';\n\nexport type DeleteFileToolConfig = ToolConfig;\n\nexport const DeleteFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to delete, relative to the project directory.',\n }),\n});\n\nexport type DeleteFileToolInput = z.infer<typeof DeleteFileToolInput>;\n\nexport const DeleteFileToolOutput = DeleteFileResult;\n\nexport type DeleteFileToolOutput = z.infer<typeof DeleteFileToolOutput>;\n\n/**\n * Class for the DeleteFile tool.\n */\nexport class DeleteFileTool extends EnvironmentToolBase<\n DeleteFileToolConfig,\n DeleteFileToolInput,\n DeleteFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n DeleteFileToolInput,\n DeleteFileToolOutput\n > {\n return {\n name: DeleteFileToolName,\n description: 'Deletes the file at the specified path.',\n inputSchema: DeleteFileToolInput,\n outputSchema: DeleteFileToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: DeleteFileToolInput,\n ): Promise<DeleteFileToolOutput> {\n return env.deleteFile(input.path);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: DeleteFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `File \\`${output.path}\\` deleted successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<DeleteFileToolInput, DeleteFileToolOutput>\n > {\n return [\n {\n input: {\n path: 'src/components/Chart.tsx',\n },\n output: 'File `src/components/Chart.tsx` deleted successfully.',\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const EditFileToolName = 'edit_file';\n\nexport type EditFileToolConfig = ToolConfig;\n\nexport const EditFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to edit, relative to the project directory.',\n }),\n oldString: z.string().meta({\n description: 'The exact string to replace in the file.',\n }),\n newString: z.string().meta({\n description: 'The string to replace the old string with.',\n }),\n replaceAll: z.boolean().optional().meta({\n description:\n 'Whether to replace all occurrences of the old string. Defaults to false.',\n }),\n});\n\nexport type EditFileToolInput = z.infer<typeof EditFileToolInput>;\n\nexport const EditFileToolOutput = z.object({\n path: z.string().meta({\n description: 'The path to the file that was edited.',\n }),\n oldString: z.string().meta({\n description: 'The old string that was replaced.',\n }),\n newString: z.string().meta({\n description: 'The new string that replaced the old string.',\n }),\n replacements: z.number().meta({\n description: 'The number of replacements made.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the edit operation.',\n }),\n});\n\nexport type EditFileToolOutput = z.infer<typeof EditFileToolOutput>;\n\n/**\n * Escapes special regex characters in a string for literal matching.\n *\n * @param string - The string to escape.\n * @returns The escaped string.\n */\nfunction escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Class for the EditFile tool.\n */\nexport class EditFileTool extends EnvironmentToolBase<\n EditFileToolConfig,\n EditFileToolInput,\n EditFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n EditFileToolInput,\n EditFileToolOutput\n > {\n return {\n name: EditFileToolName,\n description: 'Edits a file by replacing strings.',\n inputSchema: EditFileToolInput,\n outputSchema: EditFileToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: EditFileToolInput,\n ): Promise<EditFileToolOutput> {\n const { path, oldString, newString, replaceAll = false } = input;\n\n const readResult = await env.readFile(path);\n let content = readResult.content;\n let replacements = 0;\n\n if (replaceAll) {\n const escapedOldString = escapeRegExp(oldString);\n const regex = new RegExp(escapedOldString, 'g');\n const matches = content.match(regex);\n replacements = matches ? matches.length : 0;\n content = content.replace(regex, newString);\n } else {\n const index = content.indexOf(oldString);\n if (index !== -1) {\n content =\n content.substring(0, index) +\n newString +\n content.substring(index + oldString.length);\n replacements = 1;\n }\n }\n\n await env.writeFile(path, content);\n\n const message =\n replacements > 0\n ? `Successfully made ${replacements} replacement(s) in file.`\n : 'No replacements made - old string not found.';\n\n return {\n path,\n oldString,\n newString,\n replacements,\n message,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: EditFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `Edited file \\`${output.path}\\` with ${output.replacements} replacement(s).`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<EditFileToolInput, EditFileToolOutput>> {\n return [\n {\n input: {\n path: 'src/example.ts',\n oldString: 'console.log(\"hello\");',\n newString: 'console.log(\"world\");',\n replaceAll: false,\n },\n output: {\n path: 'src/example.ts',\n oldString: 'console.log(\"hello\");',\n newString: 'console.log(\"world\");',\n replacements: 1,\n message: 'Successfully made 1 replacement(s) in file.',\n },\n },\n {\n input: {\n path: 'src/example.ts',\n oldString: 'var',\n newString: 'let',\n replaceAll: true,\n },\n output: {\n path: 'src/example.ts',\n oldString: 'var',\n newString: 'let',\n replacements: 3,\n message: 'Successfully made 3 replacement(s) in file.',\n },\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport { escapeCommandArg } from '../util/escape-command-arg';\nimport { buildTreeFromFiles } from '../util/build-tree-from-files';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const GetProjectFileStructureToolName = 'get_project_file_structure';\n\nexport type GetProjectFileStructureToolConfig = ToolConfig;\n\nexport const GetProjectFileStructureToolInput = z.object({\n path: z.string().optional().meta({\n description:\n 'Root path to list files from, relative to the project directory. Defaults to \".\".',\n }),\n excludeGitIgnored: z.boolean().optional().meta({\n description: 'Whether to exclude files ignored by Git. Defaults to true.',\n }),\n});\n\nexport type GetProjectFileStructureToolInput = z.infer<\n typeof GetProjectFileStructureToolInput\n>;\n\nexport const GetProjectFileStructureToolOutput = z.object({\n files: z.array(z.string()).meta({\n description: 'List of all file paths found, relative to the root path.',\n }),\n excludeGitIgnored: z.boolean().meta({\n description: 'Whether files ignored by Git were excluded.',\n }),\n});\n\nexport type GetProjectFileStructureToolOutput = z.infer<\n typeof GetProjectFileStructureToolOutput\n>;\n\n/**\n * Class for the GetProjectFileStructure tool.\n */\nexport class GetProjectFileStructureTool extends EnvironmentToolBase<\n GetProjectFileStructureToolConfig,\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput\n > {\n return {\n name: GetProjectFileStructureToolName,\n description:\n 'Recursively lists all files in the project directory and formats them as a tree structure.',\n inputSchema: GetProjectFileStructureToolInput,\n outputSchema: GetProjectFileStructureToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: GetProjectFileStructureToolInput,\n ): Promise<GetProjectFileStructureToolOutput> {\n const { path = '.', excludeGitIgnored = true } = input;\n const escapedPath = escapeCommandArg(path);\n\n // The `find` command needs to be executed from the project root to ensure\n // paths are relative to the project root.\n let command = `find ${escapedPath} -type f`;\n\n // Exclude .gitignore patterns if requested.\n if (excludeGitIgnored) {\n let gitIgnoredPaths: string[] = [];\n try {\n const { content: gitignoreContent } = await env.readFile('.gitignore');\n gitIgnoredPaths = gitignoreContent\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#')); // Ignore empty lines and comments.\n } catch (_error) {\n // Ignore errors, e.g. if .gitignore does not exist.\n }\n\n for (const gitIgnoredPath of gitIgnoredPaths) {\n // If the path doesn't end in a slash, it could be a file or a directory. Otherwise, it's a directory.\n if (!gitIgnoredPath.endsWith('/')) {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}/*`);\n command += ` -not -name ${escapeCommandArg(gitIgnoredPath)} -not -path ${escapedPath}`;\n } else {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}*`);\n command += ` -not -path ${escapedPath}`;\n }\n }\n }\n\n command += ' | sort';\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to get project file structure with command \"${command}\": ${stderr}`,\n );\n }\n\n const files = stdout\n .split('\\n')\n .map((path) => path.trim())\n .filter(Boolean); // Filter out empty strings.\n\n const trimInitialDotSlash = (path: string) =>\n path.startsWith('./') ? path.slice(2) : path;\n\n return {\n files: files.map(trimInitialDotSlash),\n excludeGitIgnored,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n output: GetProjectFileStructureToolOutput,\n ): ModelFormattedToolResult {\n const tree = buildTreeFromFiles(output.files);\n\n if (!tree) {\n return {\n type: 'text',\n value: 'No files found.',\n };\n }\n\n return {\n type: 'text',\n value: tree,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput\n >\n > {\n return [\n {\n input: {},\n output: `├── **src/**\n│ ├── **components/**\n│ │ ├── **Button.js**\n│ │ └── **Header.js**\n│ └── **index.js**\n├── **tests/**\n│ └── **test_runner.py**\n├── .gitignore\n├── README.md\n└── package.json`,\n },\n ];\n }\n}\n","interface TreeNode {\n [key: string]: TreeNode;\n}\n\n/**\n * Renders the tree structure as a string.\n *\n * @param node - The current tree node to render.\n * @param prefix - The prefix string for indentation.\n * @returns The rendered tree string.\n */\nfunction renderTree(node: TreeNode, prefix = ''): string {\n const entries = Object.keys(node).sort();\n let result = '';\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n const isLast = i === entries.length - 1;\n const connector = isLast ? '└── ' : '├── ';\n const nextPrefix = prefix + (isLast ? ' ' : '│ ');\n\n result += prefix + connector + '**' + entry + '**' + '\\n';\n\n if (Object.keys(node[entry]).length > 0) {\n result += renderTree(node[entry], nextPrefix);\n }\n }\n\n return result;\n}\n\n/**\n * Builds a tree-like string representation from a list of file paths.\n *\n * @param files - Array of file paths relative to the root.\n * @returns A string representing the file structure as a tree.\n */\nexport function buildTreeFromFiles(files: string[]): string {\n if (files.length === 0) {\n return '';\n }\n\n // Sort files to ensure consistent ordering\n const sortedFiles = [...files].sort();\n\n // Build a tree structure\n const tree: TreeNode = {};\n\n for (const file of sortedFiles) {\n const parts = file.split('/');\n let current = tree;\n for (const part of parts) {\n if (!current[part]) {\n current[part] = {};\n }\n current = current[part];\n }\n }\n\n return renderTree(tree).trim();\n}\n","import { z } from 'zod';\nimport {\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport { escapeCommandArg } from '../util/escape-command-arg';\nimport { globToRegExp } from '../util/glob-to-reg-exp';\nimport { validateRelativePath } from '../util/validate-relative-path';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const GlobToolName = 'glob';\n\nexport type GlobToolConfig = ToolConfig;\n\nexport const GlobToolInput = z.object({\n searchPattern: z.string().meta({\n description:\n 'The glob pattern to search for, relative to the search path / project directory (e.g. \"**/*.ts\", \"docs/*.md\").',\n }),\n searchPath: z.string().optional().meta({\n description:\n 'The path to search within, relative to the project directory. Defaults to the project directory.',\n }),\n excludeGitIgnored: z.boolean().optional().meta({\n description: 'Whether to exclude files ignored by Git. Defaults to true.',\n }),\n});\n\nexport type GlobToolInput = z.infer<typeof GlobToolInput>;\n\nexport const GlobToolOutput = z.object({\n searchPattern: z.string().meta({\n description: 'The glob pattern that was searched for.',\n }),\n searchPath: z.string().meta({\n description: 'The path that was searched within.',\n }),\n excludeGitIgnored: z.boolean().meta({\n description: 'Whether files ignored by Git were excluded.',\n }),\n matchingPaths: z.array(z.string()).meta({\n description:\n 'The list of file paths that matched the glob search, relative to the project directory.',\n }),\n});\n\nexport type GlobToolOutput = z.infer<typeof GlobToolOutput>;\n\n/**\n * Class for the Glob tool.\n */\nexport class GlobTool extends EnvironmentToolBase<\n GlobToolConfig,\n GlobToolInput,\n GlobToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n GlobToolInput,\n GlobToolOutput\n > {\n return {\n name: GlobToolName,\n description:\n 'Runs a glob search to find matching file paths in the project.',\n inputSchema: GlobToolInput,\n outputSchema: GlobToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: GlobToolInput,\n ): Promise<GlobToolOutput> {\n const { searchPattern, searchPath = '', excludeGitIgnored = true } = input;\n\n if (searchPattern.startsWith('/')) {\n throw new Error(\n 'The search pattern must not start with a forward slash.',\n );\n }\n\n if (searchPath) {\n validateRelativePath(searchPath);\n }\n\n const untrailingslashedSearchPath =\n searchPath === '' ? '.' : searchPath.replace(/\\/+$/, '');\n\n const escapedSearchPath = escapeCommandArg(untrailingslashedSearchPath);\n\n // The `find` command needs to be executed from the project root to ensure\n // paths are relative to the project root.\n let command = `find ${escapedSearchPath} -type f`;\n\n // Exclude .gitignore patterns if requested.\n if (excludeGitIgnored) {\n let gitIgnoredPaths: string[] = [];\n try {\n const { content: gitignoreContent } = await env.readFile('.gitignore');\n gitIgnoredPaths = gitignoreContent\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#')); // Ignore empty lines and comments.\n } catch (_error) {\n // Ignore errors, e.g. if .gitignore does not exist.\n }\n\n for (const gitIgnoredPath of gitIgnoredPaths) {\n // If the path doesn't end in a slash, it could be a file or a directory. Otherwise, it's a directory.\n if (!gitIgnoredPath.endsWith('/')) {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}/*`);\n command += ` -not -name ${escapeCommandArg(gitIgnoredPath)} -not -path ${escapedPath}`;\n } else {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}*`);\n command += ` -not -path ${escapedPath}`;\n }\n }\n }\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to glob files with command \"${command}\": ${stderr}`,\n );\n }\n\n const matchingPaths = stdout\n .split('\\n')\n .map((path) => path.trim())\n .filter(Boolean); // Filter out empty strings.\n\n const trimInitialDotSlash = (path: string) =>\n path.startsWith('./') ? path.slice(2) : path;\n\n if (searchPattern !== '' && searchPattern !== '**') {\n const combinedPattern = `${untrailingslashedSearchPath}/${searchPattern}`;\n\n const regExp = globToRegExp(combinedPattern);\n const filteredMatchingPaths = matchingPaths.filter((path) =>\n regExp.test(path),\n );\n\n return {\n searchPattern,\n searchPath,\n excludeGitIgnored,\n matchingPaths: filteredMatchingPaths.map(trimInitialDotSlash),\n };\n }\n\n return {\n searchPattern,\n searchPath,\n excludeGitIgnored,\n matchingPaths: matchingPaths.map(trimInitialDotSlash),\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: GlobToolOutput): ModelFormattedToolResult {\n if (output.matchingPaths.length === 0) {\n return {\n type: 'text',\n value: 'No matching files found.',\n };\n }\n\n const bulletPoints = output.matchingPaths\n .map((path) => `- \\`${path}\\``)\n .join('\\n');\n\n return {\n type: 'text',\n value: `Matching files:\n${bulletPoints}\n`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<GlobToolInput, GlobToolOutput>> {\n return [\n {\n input: {\n searchPattern: 'src/**/*.tsx',\n },\n output: `Matching files:\n- \\`src/app/page.tsx\\`\n- \\`src/components/chart.tsx\\`\n- \\`src/components/footer.tsx\\`\n- \\`src/components/header.tsx\\`\n`,\n },\n {\n input: {\n searchPattern: '*',\n searchPath: 'packages/my-project',\n },\n output: `Matching files:\n- \\`packages/my-project/package.json\\`\n- \\`packages/my-project/README.md\\`\n- \\`packages/my-project/tsconfig.json\\`\n- \\`packages/my-project/vitest.config.ts\\`\n`,\n },\n ];\n }\n}\n","/**\n * Converts a glob pattern to a regular expression.\n *\n * This is a best-effort implementation and may not cover all edge cases of\n * glob patterns. It supports `*`, `**`, and `?`.\n *\n * @param glob - The glob pattern to convert.\n * @returns A regular expression that matches the glob pattern.\n */\nexport function globToRegExp(glob: string): RegExp {\n let reStr = '';\n for (let i = 0; i < glob.length; i++) {\n const char = glob[i];\n switch (char) {\n case '*':\n if (glob[i + 1] === '*') {\n // Handle '**/' pattern\n if (glob[i + 2] === '/') {\n reStr += '(?:.*\\\\/)?';\n i += 2; // Consume '**/'\n } else {\n reStr += '.*';\n i++; // Consume the second '*'\n }\n } else {\n reStr += '[^/]*';\n }\n break;\n case '?':\n reStr += '[^/]';\n break;\n // Escape characters with special meaning in regex.\n case '.':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '+':\n case '^':\n case '$':\n case '|':\n case '\\\\':\n reStr += `\\\\${char}`;\n break;\n default:\n reStr += char;\n }\n }\n return new RegExp(`^${reStr}$`);\n}\n","import { z } from 'zod';\nimport {\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport { escapeCommandArg } from '../util/escape-command-arg';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const ListDirectoryToolName = 'list_directory';\n\nexport type ListDirectoryToolConfig = ToolConfig;\n\nexport const ListDirectoryToolInput = z.object({\n path: z.string().meta({\n description:\n 'The directory path to list, relative to the project directory.',\n }),\n});\n\nexport type ListDirectoryToolInput = z.infer<typeof ListDirectoryToolInput>;\n\nexport const ListDirectoryToolOutput = z.object({\n path: z.string().meta({\n description: 'The directory path that was listed.',\n }),\n files: z.array(z.string()).meta({\n description: 'List of files in the directory.',\n }),\n directories: z.array(z.string()).meta({\n description: 'List of subdirectories in the directory.',\n }),\n});\n\nexport type ListDirectoryToolOutput = z.infer<typeof ListDirectoryToolOutput>;\n\n/**\n * Class for the ListDirectory tool.\n */\nexport class ListDirectoryTool extends EnvironmentToolBase<\n ListDirectoryToolConfig,\n ListDirectoryToolInput,\n ListDirectoryToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ListDirectoryToolInput,\n ListDirectoryToolOutput\n > {\n return {\n name: ListDirectoryToolName,\n description:\n 'Lists all files and directories in the specified directory, differentiating between files and directories. Non-recursive.',\n inputSchema: ListDirectoryToolInput,\n outputSchema: ListDirectoryToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: ListDirectoryToolInput,\n ): Promise<ListDirectoryToolOutput> {\n const escapedPath = escapeCommandArg(input.path);\n const command = `ls -la ${escapedPath}`;\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to list directory \"${input.path}\" with command \"${command}\": ${stderr}`,\n );\n }\n\n const lines = stdout.split('\\n').filter((line) => line.trim() !== '');\n const files: string[] = [];\n const directories: string[] = [];\n\n // Skip the first line (total) and process each entry\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n // ls -la format: permissions links owner group size month day time name\n // First character indicates type: d=directory, -=file, l=symlink, etc.\n const typeChar = line.charAt(0);\n const parts = line.split(/\\s+/);\n const name = parts[parts.length - 1];\n\n // Skip . and .. entries\n if (name === '.' || name === '..') continue;\n\n if (typeChar === 'd') {\n directories.push(name);\n } else if (typeChar === '-') {\n files.push(name);\n }\n // Ignore other types (symlinks, etc.) for now\n }\n\n return {\n path: input.path,\n files,\n directories,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: ListDirectoryToolOutput): ModelFormattedToolResult {\n const formatEntries = (entries: string[], type: string) => {\n if (entries.length === 0) {\n return `No ${type} found.`;\n }\n const bulletPoints = entries.map((name) => `- \\`${name}\\``).join('\\n');\n return `${type.charAt(0).toUpperCase() + type.slice(1)}:\\n${bulletPoints}`;\n };\n\n const filesSection = formatEntries(output.files, 'files');\n const directoriesSection = formatEntries(output.directories, 'directories');\n\n return {\n type: 'text',\n value: `Directory listing for \\`${output.path}\\`:\\n\\n${filesSection}\\n\\n${directoriesSection}`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<ListDirectoryToolInput, ListDirectoryToolOutput>\n > {\n return [\n {\n input: {\n path: 'src',\n },\n output: `Directory listing for \\`src\\`:\n\nFiles:\n- \\`index.ts\\`\n- \\`utils.ts\\`\n\nDirectories:\n- \\`components\\`\n- \\`hooks\\``,\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n MoveFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const MoveFileToolName = 'move_file';\n\nexport type MoveFileToolConfig = ToolConfig;\n\nexport const MoveFileToolInput = z.object({\n sourcePath: z.string().meta({\n description:\n 'The path to the file to move, relative to the project directory.',\n }),\n destinationPath: z.string().meta({\n description:\n 'The path to the destination where the file should be moved, relative to the project directory. If the file already exists, it will be overwritten.',\n }),\n});\n\nexport type MoveFileToolInput = z.infer<typeof MoveFileToolInput>;\n\nexport const MoveFileToolOutput = MoveFileResult;\n\nexport type MoveFileToolOutput = z.infer<typeof MoveFileToolOutput>;\n\n/**\n * Class for the MoveFile tool.\n */\nexport class MoveFileTool extends EnvironmentToolBase<\n MoveFileToolConfig,\n MoveFileToolInput,\n MoveFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n MoveFileToolInput,\n MoveFileToolOutput\n > {\n return {\n name: MoveFileToolName,\n description: 'Moves a file from a source path to a destination path.',\n inputSchema: MoveFileToolInput,\n outputSchema: MoveFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: MoveFileToolInput,\n ): Promise<MoveFileToolOutput> {\n return env.moveFile(input.sourcePath, input.destinationPath);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: MoveFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `File \\`${output.sourcePath}\\` moved successfully to \\`${output.destinationPath}\\`.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<MoveFileToolInput, MoveFileToolOutput>> {\n return [\n {\n input: {\n sourcePath: 'src/lib/types.ts',\n destinationPath: 'lib/index.ts',\n },\n output: 'File `src/lib/types.ts` moved successfully to `lib/index.ts`.',\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n ReadFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport { getLanguageIdentifierFromFilePath } from '../util/get-language-identifier-from-file-path';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const ReadFileToolName = 'read_file';\n\nexport type ReadFileToolConfig = ToolConfig;\n\nexport const ReadFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to read, relative to the project directory.',\n }),\n});\n\nexport type ReadFileToolInput = z.infer<typeof ReadFileToolInput>;\n\nexport const ReadFileToolOutput = ReadFileResult;\n\nexport type ReadFileToolOutput = z.infer<typeof ReadFileToolOutput>;\n\nconst formatModelResponse = (output: ReadFileToolOutput) => {\n const language = getLanguageIdentifierFromFilePath(output.path);\n return `File: \\`${output.path}\\`\nContent:\n\\`\\`\\`${language}\n${output.content}\n\\`\\`\\`\n`;\n};\n\n/**\n * Class for the ReadFile tool.\n */\nexport class ReadFileTool extends EnvironmentToolBase<\n ReadFileToolConfig,\n ReadFileToolInput,\n ReadFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ReadFileToolInput,\n ReadFileToolOutput\n > {\n return {\n name: ReadFileToolName,\n description: 'Reads the content of a file at the specified path.',\n inputSchema: ReadFileToolInput,\n outputSchema: ReadFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: ReadFileToolInput,\n ): Promise<ReadFileToolOutput> {\n return env.readFile(input.path);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: ReadFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: formatModelResponse(output),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<ReadFileToolInput, ReadFileToolOutput>> {\n const exampleContent = `import clsx from 'clsx';\n\ntype LoaderProps = {\n className?: string;\n};\n\nexport function Loader(props: LoaderProps) {\n const { className } = props;\n\n return (\n <div className={clsx('loader', className)}>\n Loading…\n </div>\n );\n}\n`;\n\n return [\n {\n input: {\n path: 'src/components/Loader.tsx',\n },\n output: formatModelResponse({\n path: 'src/components/Loader.tsx',\n content: exampleContent,\n }),\n },\n ];\n }\n}\n","/**\n * External dependencies\n */\nimport path from 'node:path';\n\nexport type ProgrammingLanguage = {\n identifier: string;\n name: string;\n fileExtensions: string[];\n};\n\nconst jsLanguage: ProgrammingLanguage = {\n identifier: 'javascript',\n name: 'JavaScript',\n fileExtensions: ['js', 'jsx'],\n};\n\nconst tsLanguage: ProgrammingLanguage = {\n identifier: 'typescript',\n name: 'TypeScript',\n fileExtensions: ['ts', 'tsx'],\n};\n\nconst ymlLanguage: ProgrammingLanguage = {\n identifier: 'yaml',\n name: 'YAML',\n fileExtensions: ['yml', 'yaml'],\n};\n\n/**\n * Language detection by file extension.\n */\nconst EXTENSION_TO_LANGUAGE: Record<string, ProgrammingLanguage> = {\n ts: tsLanguage,\n tsx: tsLanguage,\n js: jsLanguage,\n jsx: jsLanguage,\n py: {\n identifier: 'python',\n name: 'Python',\n fileExtensions: ['py'],\n },\n java: {\n identifier: 'java',\n name: 'Java',\n fileExtensions: ['java'],\n },\n c: {\n identifier: 'c',\n name: 'C',\n fileExtensions: ['c'],\n },\n cpp: {\n identifier: 'cpp',\n name: 'C++',\n fileExtensions: ['cpp'],\n },\n cs: {\n identifier: 'chsarp',\n name: 'C#',\n fileExtensions: ['cs'],\n },\n go: {\n identifier: 'go',\n name: 'Go',\n fileExtensions: ['go'],\n },\n rs: {\n identifier: 'rust',\n name: 'Rust',\n fileExtensions: ['rs'],\n },\n php: {\n identifier: 'php',\n name: 'PHP',\n fileExtensions: ['php'],\n },\n rb: {\n identifier: 'ruby',\n name: 'Ruby',\n fileExtensions: ['rb'],\n },\n swift: {\n identifier: 'swift',\n name: 'Swift',\n fileExtensions: ['swift'],\n },\n kt: {\n identifier: 'kotlin',\n name: 'Kotlin',\n fileExtensions: ['kt'],\n },\n scala: {\n identifier: 'scala',\n name: 'Scala',\n fileExtensions: ['scala'],\n },\n html: {\n identifier: 'html',\n name: 'HTML',\n fileExtensions: ['html'],\n },\n css: {\n identifier: 'css',\n name: 'CSS',\n fileExtensions: ['css'],\n },\n sass: {\n identifier: 'sass',\n name: 'Sass',\n fileExtensions: ['sass'],\n },\n scss: {\n identifier: 'scss',\n name: 'SCSS',\n fileExtensions: ['scss'],\n },\n less: {\n identifier: 'less',\n name: 'Less',\n fileExtensions: ['less'],\n },\n json: {\n identifier: 'json',\n name: 'JSON',\n fileExtensions: ['json'],\n },\n md: {\n identifier: 'markdown',\n name: 'Markdown',\n fileExtensions: ['md'],\n },\n toml: {\n identifier: 'toml',\n name: 'TOML',\n fileExtensions: ['toml'],\n },\n yml: ymlLanguage,\n yaml: ymlLanguage,\n xml: {\n identifier: 'xml',\n name: 'XML',\n fileExtensions: ['xml'],\n },\n sql: {\n identifier: 'sql',\n name: 'SQL',\n fileExtensions: ['sql'],\n },\n graphql: {\n identifier: 'graphql',\n name: 'GraphQL',\n fileExtensions: ['graphql'],\n },\n sh: {\n identifier: 'bash',\n name: 'Shell',\n fileExtensions: ['sh'],\n },\n ps1: {\n identifier: 'bash',\n name: 'PowerShell',\n fileExtensions: ['ps1'],\n },\n};\n\n/**\n * Returns programming language information for a file path.\n *\n * @param filePath - File path.\n * @returns Programming language information, or null if none could be identified.\n */\nfunction getLanguageFromFilePath(\n filePath: string,\n): ProgrammingLanguage | undefined {\n const extension = path.extname(filePath).slice(1).toLowerCase() || '';\n return EXTENSION_TO_LANGUAGE[extension];\n}\n\n/**\n * Returns the programming language identifier for a file path.\n *\n * @param filePath - File path.\n * @returns Programming language identifier, or empty string if none could be identified.\n */\nexport function getLanguageIdentifierFromFilePath(filePath: string): string {\n const language = getLanguageFromFilePath(filePath);\n return language ? language.identifier : '';\n}\n","import { z } from 'zod';\nimport {\n ReadFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport { getLanguageIdentifierFromFilePath } from '../util/get-language-identifier-from-file-path';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const ReadManyFilesToolName = 'read_many_files';\n\nexport type ReadManyFilesToolConfig = ToolConfig;\n\nexport const ReadManyFilesToolInput = z.object({\n paths: z.array(z.string()).meta({\n description:\n 'The paths to the files to read, relative to the project directory.',\n }),\n});\n\nexport type ReadManyFilesToolInput = z.infer<typeof ReadManyFilesToolInput>;\n\nexport const ReadManyFilesToolOutput = z.record(z.string(), ReadFileResult);\n\nexport type ReadManyFilesToolOutput = z.infer<typeof ReadManyFilesToolOutput>;\n\nconst formatModelResponse = (output: ReadManyFilesToolOutput[string]) => {\n const language = getLanguageIdentifierFromFilePath(output.path);\n return `File: \\`${output.path}\\`\nContent:\n\\`\\`\\`${language}\n${output.content}\n\\`\\`\\`\n`;\n};\n\n/**\n * Class for the ReadManyFiles tool.\n */\nexport class ReadManyFilesTool extends EnvironmentToolBase<\n ReadManyFilesToolConfig,\n ReadManyFilesToolInput,\n ReadManyFilesToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ReadManyFilesToolInput,\n ReadManyFilesToolOutput\n > {\n return {\n name: ReadManyFilesToolName,\n description: 'Reads the contents of the files at the specified paths.',\n inputSchema: ReadManyFilesToolInput,\n outputSchema: ReadManyFilesToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: ReadManyFilesToolInput,\n ): Promise<ReadManyFilesToolOutput> {\n const results: ReadFileResult[] = await Promise.all(\n input.paths.map((path) => env.readFile(path)),\n );\n\n return results.reduce((acc, result) => {\n acc[result.path] = result;\n return acc;\n }, {} as ReadManyFilesToolOutput);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: ReadManyFilesToolOutput): ModelFormattedToolResult {\n const fileContentResponses = Object.values(output).map((fileResult) =>\n formatModelResponse(fileResult),\n );\n\n return {\n type: 'text',\n value: fileContentResponses.join('\\n'),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<ReadManyFilesToolInput, ReadManyFilesToolOutput>\n > {\n const exampleContent1 = `import clsx from 'clsx';\n\ntype LoaderProps = {\n className?: string;\n};\n\nexport function Loader(props: LoaderProps) {\n const { className } = props;\n\n return (\n <div className={clsx('loader', className)}>\n Loading…\n </div>\n );\n}\n`;\n const exampleContent2 = `export function snakeCaseToCamelCase(snakeCase: string): string {\n return snakeCase.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n`;\n\n return [\n {\n input: {\n paths: [\n 'src/components/Loader.tsx',\n 'src/util/snake-case-to-camel-case.ts',\n ],\n },\n output:\n formatModelResponse({\n path: 'src/components/Loader.tsx',\n content: exampleContent1,\n }) +\n '\\n' +\n formatModelResponse({\n path: 'src/util/snake-case-to-camel-case.ts',\n content: exampleContent2,\n }),\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n RunCommandResult,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const RunCommandToolName = 'run_command';\n\nexport type RunCommandToolConfig = ToolConfig;\n\nexport const RunCommandToolInput = z.object({\n command: z\n .string()\n .meta({ description: 'The CLI command to run, including all arguments.' }),\n});\n\nexport type RunCommandToolInput = z.infer<typeof RunCommandToolInput>;\n\nexport const RunCommandToolOutput = RunCommandResult;\n\nexport type RunCommandToolOutput = z.infer<typeof RunCommandToolOutput>;\n\n/**\n * Formats the command result into a model-friendly response string.\n *\n * @param output - The command result output.\n * @returns The formatted string for model consumption.\n */\nfunction formatCommandResultToModelResponse(output: RunCommandResult) {\n const stdout = !output.stdout.trim()\n ? '(none)'\n : `\n\\`\\`\\`\n${output.stdout}\n\\`\\`\\``;\n const stderr = !output.stderr.trim()\n ? '(none)'\n : `\n\\`\\`\\`\n${output.stderr}\n\\`\\`\\``;\n\n return `Command: \\`${output.command}\\`\nExit Code: ${output.exitCode}\nOutput (stdout): ${stdout}\nError Output (stderr): ${stderr}\n`;\n}\n\n/**\n * Class for the RunCommand tool.\n *\n * WARNING: This tool can be dangerous if misused. It allows executing arbitrary commands in the environment.\n * Only allow using this tool in sandboxed environments where the potential risks are understood and mitigated.\n */\nexport class RunCommandTool extends EnvironmentToolBase<\n RunCommandToolConfig,\n RunCommandToolInput,\n RunCommandToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n RunCommandToolInput,\n RunCommandToolOutput\n > {\n return {\n name: RunCommandToolName,\n description: 'Runs the specific CLI command.',\n inputSchema: RunCommandToolInput,\n outputSchema: RunCommandToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: RunCommandToolInput,\n ): Promise<RunCommandToolOutput> {\n return env.runCommand(input.command);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: RunCommandToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: formatCommandResultToModelResponse(output),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<RunCommandToolInput, RunCommandToolOutput>\n > {\n const exampleGitOutput = `diff --git a/src/util/string-utils.ts b/src/util/string-utils.ts\nindex 1836072..b13adef 100644\n--- a/src/util/string-utils.ts\n+++ b/src/util/string-utils.ts\n@@ -1,3 +1,7 @@\n export function snakeCaseToCamelCase(str: string): string {\n return str.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase());\n }\n+\n+export function camelCaseToSnakeCase(str: string): string {\n+ return str.replace(/([A-Z])/g, (match) => \\`_\\${match.toLowerCase()}\\`);\n+}\n`;\n\n const exampleNpmOutput = `\nadded 1 package, and changed 1 package in 2s\n\n156 packages are looking for funding\n run \\`npm fund\\` for details`;\n\n const exampleMkdirError = `mkdir: src/lib: No such file or directory\n`;\n\n return [\n {\n input: {\n command: 'git --no-pager diff',\n },\n output: formatCommandResultToModelResponse({\n command: 'git --no-pager diff',\n exitCode: 0,\n stdout: exampleGitOutput,\n stderr: '',\n }),\n },\n {\n input: {\n command: 'npm install zod',\n },\n output: formatCommandResultToModelResponse({\n command: 'npm install zod',\n exitCode: 0,\n stdout: exampleNpmOutput,\n stderr: '',\n }),\n },\n {\n input: {\n command: 'mkdir src/lib/api',\n },\n output: formatCommandResultToModelResponse({\n command: 'mkdir src/lib/api',\n exitCode: 1,\n stdout: '',\n stderr: exampleMkdirError,\n }),\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n WriteFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelFormattedToolResult,\n} from '../types';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n} from './environment-tool-base';\n\nexport const WriteFileToolName = 'write_file';\n\nexport type WriteFileToolConfig = ToolConfig;\n\nexport const WriteFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to write, relative to the project directory.',\n }),\n content: z.string().meta({\n description:\n 'The content to write to the file. If the file already exists, the content will replace existing content.',\n }),\n});\n\nexport type WriteFileToolInput = z.infer<typeof WriteFileToolInput>;\n\nexport const WriteFileToolOutput = WriteFileResult;\n\nexport type WriteFileToolOutput = z.infer<typeof WriteFileToolOutput>;\n\n/**\n * Class for the WriteFile tool.\n */\nexport class WriteFileTool extends EnvironmentToolBase<\n WriteFileToolConfig,\n WriteFileToolInput,\n WriteFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n WriteFileToolInput,\n WriteFileToolOutput\n > {\n return {\n name: WriteFileToolName,\n description: 'Writes content to a file at the specified path.',\n inputSchema: WriteFileToolInput,\n outputSchema: WriteFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: WriteFileToolInput,\n ): Promise<WriteFileToolOutput> {\n return env.writeFile(input.path, input.content);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param output - The output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(output: WriteFileToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `File \\`${output.path}\\` written successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<WriteFileToolInput, WriteFileToolOutput>> {\n const exampleContent = `export function snakeCaseToCamelCase(snakeCase: string): string {\n return snakeCase.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n`;\n\n return [\n {\n input: {\n path: 'src/util/snake-case-to-camel-case.ts',\n content: exampleContent,\n },\n output:\n 'File `src/util/snake-case-to-camel-case.ts` written successfully.',\n },\n ];\n }\n}\n","import type { Tool } from '@ai-sdk/provider-utils';\nimport {\n Experimental_Agent as Agent,\n type Experimental_AgentSettings as AgentSettings,\n stepCountIs,\n hasToolCall,\n} from 'ai';\nimport { getAdditionalInstructions } from './instructions';\nimport {\n createToolsForEnvironment,\n createToolsForNamedEnvironment,\n type ToolsDefinition,\n} from './tool-creators';\nimport type { Environment } from './types';\nimport { SubmitTool, SubmitToolName } from './tools/submit-tool';\nimport { getStepLog } from './util/get-step-log';\n\nexport type CodeAgentCreatorConfig = AgentSettings<Record<string, Tool>> & {\n maxSteps: number;\n allowSubmit?: boolean;\n logStep?: (stepLog: string, stepIndex: number) => void;\n omitAdditionalInstructions?: boolean;\n} & (\n | {\n environment: Environment;\n environmentToolsDefinition: ToolsDefinition;\n }\n | {\n environments: Record<string, Environment>;\n environmentToolsDefinition: Record<string, ToolsDefinition>;\n }\n | Record<string, never>\n );\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype FirstFunctionArgument<T> = T extends (arg1: infer U, ...args: any[]) => any\n ? U\n : never;\n\n/**\n * Creates an AI code agent configured to operate on one or more specified execution environments with tools.\n *\n * @param agentConfig - Configuration options for the code agent, including environments, tools definition, and agent settings.\n * @returns An instance of Agent configured with the specified environment tools and settings.\n */\nexport function createCodeAgent(\n agentConfig: CodeAgentCreatorConfig,\n): Agent<Record<string, Tool>> {\n const {\n maxSteps,\n allowSubmit,\n logStep,\n omitAdditionalInstructions,\n tools: originalTools,\n stopWhen: originalStopWhen,\n prepareStep: originalPrepareStep,\n system: originalSystemInstruction,\n ...remainingConfig\n } = agentConfig;\n\n let agentSettings: AgentSettings<Record<string, Tool>>;\n let environmentTools:\n | ReturnType<typeof createToolsForEnvironment>\n | undefined;\n if ('environments' in remainingConfig) {\n const { environments, environmentToolsDefinition, ...agentSettingsInput } =\n remainingConfig;\n agentSettings = { ...agentSettingsInput };\n\n environmentTools = {};\n for (const [environmentName, environment] of Object.entries(environments)) {\n if (!(environmentName in environmentToolsDefinition)) {\n throw new Error(\n `No tools definition provided for environment \"${environmentName}\". Please provide a tools definition for each environment.`,\n );\n }\n const environmentTools = createToolsForNamedEnvironment(\n environmentName,\n environment,\n environmentToolsDefinition[environmentName],\n );\n for (const [toolName, tool] of Object.entries(environmentTools)) {\n if (toolName in environmentTools) {\n throw new Error(\n `Tool name conflict: The tool name \"${toolName}\" from environment \"${environmentName}\" is already used by another environment's tools.`,\n );\n }\n environmentTools[toolName] = tool;\n }\n }\n } else if ('environment' in remainingConfig) {\n const { environment, environmentToolsDefinition, ...agentSettingsInput } =\n remainingConfig;\n agentSettings = { ...agentSettingsInput };\n\n environmentTools = createToolsForEnvironment(\n environment,\n environmentToolsDefinition,\n );\n } else {\n agentSettings = { ...remainingConfig };\n }\n\n const tools =\n environmentTools && originalTools\n ? mergeTools(environmentTools, originalTools)\n : originalTools || environmentTools || {};\n\n if (allowSubmit) {\n if (SubmitToolName in tools) {\n throw new Error(\n `Tool name conflict: The Submit tool name \"${SubmitToolName}\" is already used by another tool.`,\n );\n }\n tools[SubmitToolName] = new SubmitTool();\n }\n\n if (Object.keys(tools).length > 0) {\n agentSettings.tools = tools;\n }\n\n let stepCount = 0;\n const prepareStep = logStep\n ? (prepareStepInput: FirstFunctionArgument<typeof originalPrepareStep>) => {\n const { steps } = prepareStepInput;\n if (steps.length > 0) {\n stepCount += 1;\n const stepLog = getStepLog(steps[steps.length - 1]);\n logStep(`=== Step ${stepCount} ===\\n${stepLog}`, stepCount - 1);\n }\n if (originalPrepareStep) {\n return originalPrepareStep(prepareStepInput);\n }\n return undefined;\n }\n : originalPrepareStep;\n\n const stopWhenCondition = allowSubmit\n ? [stepCountIs(maxSteps), hasToolCall(SubmitToolName)]\n : stepCountIs(maxSteps);\n const stopWhen = originalStopWhen\n ? mergeStopWhen(originalStopWhen, stopWhenCondition)\n : stopWhenCondition;\n\n const system = !omitAdditionalInstructions\n ? mergeSystemInstructions(\n originalSystemInstruction,\n getAdditionalInstructions({ maxSteps, allowSubmit, tools }),\n )\n : originalSystemInstruction;\n\n return new Agent({\n ...agentSettings,\n system,\n prepareStep,\n stopWhen,\n });\n}\n\n/**\n * Merges two sets of tools into one, ensuring no name conflicts.\n *\n * @param baseTools - The base set of tools.\n * @param additionalTools - Additional tools to merge into the base set.\n * @returns A new record containing all tools from both sets.\n */\nfunction mergeTools(\n baseTools: Record<string, Tool>,\n additionalTools: Exclude<\n AgentSettings<Record<string, Tool>>['tools'],\n undefined\n >,\n): Record<string, Tool> {\n const tools = { ...baseTools };\n for (const [toolName, tool] of Object.entries(additionalTools)) {\n if (toolName in tools) {\n throw new Error(\n `Tool name conflict: The additional tool name \"${toolName}\" is already used by the code environment tools.`,\n );\n }\n tools[toolName] = tool;\n }\n return tools;\n}\n\n/**\n * Merges two stopWhen conditions into one.\n *\n * @param baseStopWhen - The base stopWhen condition.\n * @param additionalStopWhen - The additional stopWhen condition to merge.\n * @returns A combined stopWhen condition.\n */\nfunction mergeStopWhen(\n baseStopWhen: Exclude<\n AgentSettings<Record<string, Tool>>['stopWhen'],\n undefined\n >,\n additionalStopWhen: Exclude<\n AgentSettings<Record<string, Tool>>['stopWhen'],\n undefined\n >,\n): Exclude<AgentSettings<Record<string, Tool>>['stopWhen'], undefined> {\n if (Array.isArray(baseStopWhen)) {\n if (Array.isArray(additionalStopWhen)) {\n return [...baseStopWhen, ...additionalStopWhen];\n }\n\n return [...baseStopWhen, additionalStopWhen];\n }\n\n if (Array.isArray(additionalStopWhen)) {\n return [baseStopWhen, ...additionalStopWhen];\n }\n\n return [baseStopWhen, additionalStopWhen];\n}\n\n/**\n * Merges the base system instructions with additional instructions.\n *\n * If no base system instructions are provided, only the additional instructions are returned.\n *\n * @param baseSystem - The base system instructions, or undefined if none.\n * @param additionalInstructions - The additional instructions to append.\n * @returns The merged system instructions.\n */\nfunction mergeSystemInstructions(\n baseSystem: string | undefined,\n additionalInstructions: string,\n): string {\n if (baseSystem) {\n return `${baseSystem.trimEnd()}\\n\\n${additionalInstructions}`;\n }\n return additionalInstructions;\n}\n","import type { ToolCallOptions } from 'ai';\nimport { z } from 'zod';\nimport type {\n ToolConfig,\n ToolExample,\n ModelFormattedToolResult,\n} from '../types';\nimport { ToolBase, type ToolMetadata } from './tool-base';\n\nexport const SubmitToolName = 'submit';\n\nexport type SubmitToolConfig = ToolConfig;\n\nexport const SubmitToolInput = z.object({});\n\nexport type SubmitToolInput = z.infer<typeof SubmitToolInput>;\n\nexport const SubmitToolOutput = z.object({});\n\nexport type SubmitToolOutput = z.infer<typeof SubmitToolOutput>;\n\n/**\n * Class for the Submit tool.\n */\nexport class SubmitTool extends ToolBase<\n SubmitToolConfig,\n SubmitToolInput,\n SubmitToolOutput\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): ToolMetadata<SubmitToolInput, SubmitToolOutput> {\n return {\n name: SubmitToolName,\n description: 'Submits the current task, indicating that it is completed.',\n inputSchema: SubmitToolInput,\n outputSchema: SubmitToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool with the given input.\n *\n * @param _ - The input for the tool. Unused.\n * @param __ - Options from the tool call. Unused.\n * @returns A promise that resolves to the tool execution result.\n */\n async execute(\n _: SubmitToolInput,\n __: ToolCallOptions,\n ): Promise<SubmitToolOutput> {\n return {};\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param _ - The output from the tool execution. Unused.\n * @returns The formatted tool result.\n */\n toModelOutput(_: SubmitToolOutput): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `Task submitted successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<SubmitToolInput, SubmitToolOutput>> {\n return [];\n }\n}\n","import type { Tool } from '@ai-sdk/provider-utils';\nimport type { ToolExample } from './types';\nimport { SubmitToolName } from './tools/submit-tool';\n\ntype AdditionalInstructionsConfig = {\n maxSteps: number;\n allowSubmit?: boolean;\n tools: Record<string, Tool>;\n};\n\n/**\n * Generates additional instructions for the AI model based on the provided configuration.\n *\n * @param config - Configuration object containing maxSteps and tools.\n * @returns A string containing the additional instructions, to append to the system prompt.\n */\nexport function getAdditionalInstructions(\n config: AdditionalInstructionsConfig,\n) {\n const { maxSteps, allowSubmit, tools } = config;\n\n const exampleSections: string[] = [];\n for (const [toolName, tool] of Object.entries(tools)) {\n if (\n 'examples' in tool &&\n Array.isArray(tool.examples) &&\n tool.examples.length > 0\n ) {\n let toolSection = `### Tool: \\`${toolName}\\`\\n\\n`;\n for (const example of tool.examples) {\n toolSection += formatExampleForInstructions(toolName, example);\n }\n exampleSections.push(toolSection.trim());\n }\n }\n\n const workflowGuidelines: string[] = [\n /*\n * If there are examples, the tool information is already mentioned in a separate Tool Examples section.\n * Therefore the line below is only relevant if there are no examples.\n */\n ...(!exampleSections.length\n ? [\n 'You have access to several tools to assist you in completing your task.',\n ]\n : []),\n 'You must issue tool calls to complete your task. Do not engage with the user directly.',\n ...(allowSubmit\n ? [\n `Once you think you have completed your task, call the \\`${SubmitToolName}\\` tool to submit your results.`,\n ]\n : []),\n `You have a maximum of ${maxSteps} steps to complete your task.`,\n ];\n\n const importantWorkflowGuidelines = `## Important Workflow Guidelines\n\n${workflowGuidelines.map((line) => `- ${line}`).join('\\n')}\n\nRemember, you don't get to ask the user any clarifying questions, just use the tools available to complete your task. You're on your own now.\n`;\n\n if (exampleSections.length) {\n return (\n `## Tool Examples\n\nYou have access to several tools to assist you in completing your task. Here are some examples of how to use them:\n\n${exampleSections.join('\\n\\n')}\n\n` + importantWorkflowGuidelines\n );\n }\n\n return importantWorkflowGuidelines;\n}\n\n/**\n * Formats a tool example for inclusion in the model instructions.\n *\n * @param toolName - The name of the tool.\n * @param example - The tool example to format.\n * @returns The formatted tool example string.\n */\nexport function formatExampleForInstructions<ToolInputType, ToolOutputType>(\n toolName: string,\n example: ToolExample<ToolInputType, ToolOutputType>,\n): string {\n const input: string | number =\n typeof example.input === 'undefined'\n ? ''\n : typeof example.input === 'string' || typeof example.input === 'number'\n ? example.input\n : JSON.stringify(example.input, null, 2);\n const output: string | number =\n typeof example.output === 'undefined'\n ? ''\n : typeof example.output === 'string' || typeof example.output === 'number'\n ? example.output\n : JSON.stringify(example.output, null, 2);\n\n if (output === '') {\n return `<example>\n<tool_call>\n${toolName}(${input})\n</tool_call>\n</example>`;\n }\n\n return `<example>\n<tool_call>\n${toolName}(${input})\n</tool_call>\n<tool_response>\n${output}\n</tool_response>\n</example>`;\n}\n","import type { Tool } from '@ai-sdk/provider-utils';\nimport type { Environment, CommandLineEnvironmentInterface } from './types';\nimport type { EnvironmentToolBase } from './tools/environment-tool-base';\nimport { ReadFileTool, ReadFileToolName } from './tools/read-file-tool';\nimport { WriteFileTool, WriteFileToolName } from './tools/write-file-tool';\nimport { DeleteFileTool, DeleteFileToolName } from './tools/delete-file-tool';\nimport { EditFileTool, EditFileToolName } from './tools/edit-file-tool';\nimport { MoveFileTool, MoveFileToolName } from './tools/move-file-tool';\nimport { CopyFileTool, CopyFileToolName } from './tools/copy-file-tool';\nimport {\n ReadManyFilesTool,\n ReadManyFilesToolName,\n} from './tools/read-many-files-tool';\nimport {\n GetProjectFileStructureTool,\n GetProjectFileStructureToolName,\n} from './tools/get-project-file-structure-tool';\nimport { GlobTool, GlobToolName } from './tools/glob-tool';\nimport {\n ListDirectoryTool,\n ListDirectoryToolName,\n} from './tools/list-directory-tool';\nimport { RunCommandTool, RunCommandToolName } from './tools/run-command-tool';\n\nconst availableEnvironmentTools = {\n [ReadFileToolName]: ReadFileTool,\n [WriteFileToolName]: WriteFileTool,\n [DeleteFileToolName]: DeleteFileTool,\n [EditFileToolName]: EditFileTool,\n [MoveFileToolName]: MoveFileTool,\n [CopyFileToolName]: CopyFileTool,\n [ReadManyFilesToolName]: ReadManyFilesTool,\n [GetProjectFileStructureToolName]: GetProjectFileStructureTool,\n [GlobToolName]: GlobTool,\n [ListDirectoryToolName]: ListDirectoryTool,\n [RunCommandToolName]: RunCommandTool,\n};\n\ntype EnvironmentToolClasses = {\n [ReadFileToolName]: ReadFileTool;\n [WriteFileToolName]: WriteFileTool;\n [DeleteFileToolName]: DeleteFileTool;\n [EditFileToolName]: EditFileTool;\n [MoveFileToolName]: MoveFileTool;\n [CopyFileToolName]: CopyFileTool;\n [ReadManyFilesToolName]: ReadManyFilesTool;\n [GetProjectFileStructureToolName]: GetProjectFileStructureTool;\n [GlobToolName]: GlobTool;\n [ListDirectoryToolName]: ListDirectoryTool;\n [RunCommandToolName]: RunCommandTool;\n};\n\nconst cliOnlyTools: EnvironmentToolName[] = [\n GetProjectFileStructureToolName,\n GlobToolName,\n ListDirectoryToolName,\n RunCommandToolName,\n];\n\nconst readonlyTools: EnvironmentToolName[] = [\n ReadFileToolName,\n ReadManyFilesToolName,\n GetProjectFileStructureToolName,\n GlobToolName,\n ListDirectoryToolName,\n];\n\nconst dangerousTools: EnvironmentToolName[] = [\n DeleteFileToolName,\n RunCommandToolName,\n];\n\nexport type EnvironmentToolSafetyLevel = 'readonly' | 'basic' | 'all';\nexport const EnvironmentToolSafetyLevels: EnvironmentToolSafetyLevel[] = [\n 'readonly',\n 'basic',\n 'all',\n];\n\ntype EnvironmentToolGenerics<T> =\n T extends EnvironmentToolBase<\n infer ToolConfig,\n infer ToolInput,\n infer ToolOutput,\n infer ToolEnvironment\n >\n ? {\n ToolConfigType: ToolConfig;\n ToolInputType: ToolInput;\n ToolOutputType: ToolOutput;\n ToolEnvironmentType: ToolEnvironment;\n }\n : never;\n\n/*\n * This workaround using a property is required because, when using generics with a base constraint,\n * TypeScript will always resolve the generic to the base constraint when trying to infer types later on.\n * By introducing a dummy property that uses the generic, TypeScript can correctly infer the actual types.\n */\ntype EnvironmentToolConfigOf<T> = T extends { _toolConfig: infer C }\n ? C\n : never;\ntype EnvironmentToolInputTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolInputType'];\ntype EnvironmentToolOutputTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolOutputType'];\ntype EnvironmentToolEnvironmentTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolEnvironmentType'];\n\nexport type EnvironmentToolName = keyof typeof availableEnvironmentTools;\nexport const EnvironmentToolNames = Object.keys(\n availableEnvironmentTools,\n) as EnvironmentToolName[];\n\n/**\n * Creates an environment tool instance based on the provided name, execution environment, and configuration.\n *\n * @param toolName - The name identifying the type of environment tool to create.\n * @param environment - The execution environment to create the tool for.\n * @param config - The configuration object for the environment tool.\n * @returns An instance of the specified environment tool.\n */\nexport function createEnvironmentTool<T extends EnvironmentToolName>(\n toolName: T,\n environment: EnvironmentToolEnvironmentTypeOf<EnvironmentToolClasses[T]>,\n config?: EnvironmentToolConfigOf<EnvironmentToolClasses[T]>,\n): EnvironmentToolClasses[T] {\n // Extra safe-guard - should not be needed.\n if (!(toolName in availableEnvironmentTools)) {\n throw new Error(`Unsupported environment: ${toolName}`);\n }\n\n const EnvironmentToolClass = availableEnvironmentTools[toolName as T];\n\n return new EnvironmentToolClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n environment as any,\n config,\n ) as EnvironmentToolClasses[T];\n}\n\ntype ToolCreatorConfig = EnvironmentToolName extends infer T\n ? T extends EnvironmentToolName\n ? {\n toolName: T;\n toolConfig?: EnvironmentToolConfigOf<EnvironmentToolClasses[T]>;\n }\n : never\n : never;\n\nexport type ToolsDefinition =\n | Array<EnvironmentToolName | ToolCreatorConfig>\n | EnvironmentToolSafetyLevel;\n\ntype SanitizedToolsDefinition = ToolCreatorConfig[];\n\ntype ToolWithIO = EnvironmentToolName extends infer T\n ? T extends EnvironmentToolName\n ? Tool<\n EnvironmentToolInputTypeOf<EnvironmentToolClasses[T]>,\n EnvironmentToolOutputTypeOf<EnvironmentToolClasses[T]>\n >\n : never\n : never;\n\n/**\n * Creates a map of tools for the given environment.\n *\n * @param environment - The execution environment to create the tools for.\n * @param toolsDefinition - The names of the tools to create, or 'readonly', 'basic', or 'all' as a shortcut for groups of available tools.\n * @returns A record mapping tool names to their corresponding Tool instances.\n */\nexport function createToolsForEnvironment(\n environment: Environment,\n toolsDefinition: ToolsDefinition = 'all',\n): Record<string, ToolWithIO> {\n const sanitizedToolsDefinition = sanitizeToolsDefinition(toolsDefinition);\n\n const isCliEnvironment = 'runCommand' in environment;\n\n const tools: Record<string, ToolWithIO> = {};\n for (const toolDefinition of sanitizedToolsDefinition) {\n const actualToolName = toolDefinition.toolName;\n\n // Manual check for CLI-only tools.\n if (!isCliEnvironment && cliOnlyTools.includes(actualToolName)) {\n throw new Error(\n `The \"${actualToolName}\" tool can only be used with command-line environments.`,\n );\n }\n\n const toolNameToUse =\n toolDefinition.toolConfig?.name || toolDefinition.toolName;\n let toolConfig: ToolCreatorConfig['toolConfig'];\n if (toolDefinition.toolConfig) {\n toolConfig = toolDefinition.toolConfig;\n }\n\n if (toolNameToUse in tools) {\n throw new Error(\n `Multiple tools named \"${toolNameToUse}\" are provided - make sure tool names are unique.`,\n );\n }\n\n tools[toolNameToUse] = createEnvironmentTool(\n actualToolName,\n isCliEnvironment\n ? (environment as CommandLineEnvironmentInterface)\n : environment,\n toolConfig,\n );\n }\n\n return tools;\n}\n\n/**\n * Creates a map of tools for the given environment, modifying tool names with the environment name to avoid conflicts.\n *\n * For example, if the environment name is \"env1\" and the tool is \"read_file\", the modified tool name will be \"read_file_in_env1\".\n *\n * @param environmentName - The name of the environment. Will be used in tool names to avoid conflicts.\n * @param environment - The execution environment to create the tools for.\n * @param toolsDefinition - The names of the tools to create, or 'readonly', 'basic', or 'all' as a shortcut for groups of available tools.\n * @returns A record mapping tool names to their corresponding Tool instances.\n */\nexport function createToolsForNamedEnvironment(\n environmentName: string,\n environment: Environment,\n toolsDefinition: ToolsDefinition = 'all',\n): Record<string, ToolWithIO> {\n const sanitizedToolsDefinition = sanitizeToolsDefinition(toolsDefinition);\n\n const toolsDefinitionWithEnvironmentName = sanitizedToolsDefinition.map(\n (toolDefinition): ToolCreatorConfig => {\n if (toolDefinition.toolConfig) {\n const toolNameToUse =\n toolDefinition.toolConfig.name || toolDefinition.toolName;\n return {\n toolName: toolDefinition.toolName,\n toolConfig: {\n ...toolDefinition.toolConfig,\n name: `${toolNameToUse}_in_${environmentName}`,\n },\n };\n }\n return {\n toolName: toolDefinition.toolName,\n toolConfig: {\n name: `${toolDefinition.toolName}_in_${environmentName}`,\n },\n };\n },\n );\n\n return createToolsForEnvironment(\n environment,\n toolsDefinitionWithEnvironmentName,\n );\n}\n\n/**\n * Sanitizes a tools definition into a consistent format.\n *\n * @param toolsDefinition - The tools definition to sanitize.\n * @returns A sanitized array of tool definitions.\n */\nfunction sanitizeToolsDefinition(\n toolsDefinition: ToolsDefinition,\n): SanitizedToolsDefinition {\n if (typeof toolsDefinition === 'string') {\n switch (toolsDefinition) {\n case 'readonly':\n toolsDefinition = readonlyTools;\n break;\n case 'basic':\n toolsDefinition = EnvironmentToolNames.filter(\n (toolName) => !dangerousTools.includes(toolName),\n );\n break;\n default:\n toolsDefinition = [...EnvironmentToolNames];\n }\n }\n\n return toolsDefinition.map((tool) => {\n if (typeof tool === 'string') {\n return { toolName: tool };\n }\n return tool;\n });\n}\n","import type { StepResult, Tool } from 'ai';\n\n/**\n * Returns a formatted log string for a given step result from an AI agent.\n *\n * @param stepResult - The step result to format.\n * @returns A formatted string representing the step log.\n */\nexport function getStepLog(\n stepResult: StepResult<NoInfer<Record<string, Tool>>>,\n): string {\n const { content } = stepResult;\n\n let logEntry = '';\n content.forEach((part) => {\n logEntry += part.type;\n if ('toolName' in part && 'toolCallId' in part && part.toolCallId) {\n logEntry += ` (${part.toolName}, ID ${part.toolCallId})`;\n } else if ('toolName' in part) {\n logEntry += ` (${part.toolName})`;\n }\n logEntry += ': ';\n if (part.type === 'tool-call' && 'input' in part) {\n logEntry +=\n typeof part.input === 'string'\n ? part.input\n : JSON.stringify(part.input);\n } else if (part.type === 'tool-result' && 'output' in part) {\n logEntry +=\n typeof part.output === 'string'\n ? part.output\n : JSON.stringify(part.output);\n } else if (part.type === 'tool-error' && 'error' in part) {\n logEntry +=\n typeof part.error === 'object' &&\n part.error !== null &&\n 'message' in part.error\n ? part.error.message\n : String(part.error);\n } else if (part.type === 'text' && 'text' in part) {\n logEntry += part.text;\n }\n logEntry += '\\n';\n });\n\n return logEntry.trim();\n}\n","import type { FilesystemEnvironmentBase } from './environments/filesystem-environment-base';\nimport {\n DockerEnvironment,\n DockerEnvironmentName,\n} from './environments/docker-environment';\nimport {\n MockFilesystemEnvironment,\n MockFilesystemEnvironmentName,\n} from './environments/mock-filesystem-environment';\nimport {\n NodeFilesystemEnvironment,\n NodeFilesystemEnvironmentName,\n} from './environments/node-filesystem-environment';\nimport {\n UnsafeLocalEnvironment,\n UnsafeLocalEnvironmentName,\n} from './environments/unsafe-local-environment';\n\nconst availableEnvironments = {\n [UnsafeLocalEnvironmentName]: UnsafeLocalEnvironment,\n [DockerEnvironmentName]: DockerEnvironment,\n [MockFilesystemEnvironmentName]: MockFilesystemEnvironment,\n [NodeFilesystemEnvironmentName]: NodeFilesystemEnvironment,\n};\n\ntype EnvironmentClasses = {\n [UnsafeLocalEnvironmentName]: UnsafeLocalEnvironment;\n [DockerEnvironmentName]: DockerEnvironment;\n [MockFilesystemEnvironmentName]: MockFilesystemEnvironment;\n [NodeFilesystemEnvironmentName]: NodeFilesystemEnvironment;\n};\n\ntype EnvironmentConfigOf<T> =\n T extends FilesystemEnvironmentBase<infer X> ? X : never;\n\nexport type EnvironmentName = keyof typeof availableEnvironments;\nexport const EnvironmentNames = Object.keys(\n availableEnvironments,\n) as EnvironmentName[];\n\n/**\n * Creates an environment instance based on the provided name and configuration.\n *\n * @param environmentName - The name identifying the type of environment to create.\n * @param config - The configuration object for the environment.\n * @returns An instance of the specified environment.\n */\nexport function createEnvironment<T extends EnvironmentName>(\n environmentName: T,\n config: EnvironmentConfigOf<EnvironmentClasses[T]>,\n): EnvironmentClasses[T] {\n // Extra safe-guard - should not be needed.\n if (!(environmentName in availableEnvironments)) {\n throw new Error(`Unsupported environment: ${environmentName}`);\n }\n\n const EnvironmentClass = availableEnvironments[environmentName as T];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return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AAqB,GAAG;AAAA,EACzB,CAAC,6BAA6B,GAAG;AAAA,EACjC,CAAC,6BAA6B,GAAG;AACnC;AAaO,IAAM,mBAAmB,OAAO;AAAA,EACrC;AACF;AASO,SAAS,kBACd,iBACA,QACuB;AAEvB,MAAI,EAAE,mBAAmB,wBAAwB;AAC/C,UAAM,IAAI,MAAM,4BAA4B,eAAe,EAAE;AAAA,EAC/D;AAEA,QAAM,mBAAmB,sBAAsB,eAAoB;AAGnE,SAAO,IAAI,iBAAiB,MAAa;AAC3C;","names":["path","path","import_node_path","path","fs","import_node_child_process","import_zod","import_zod","string","path","import_zod","path","escapedPath","import_zod","path","import_zod","import_zod","import_zod","import_node_path","path","import_zod","formatModelResponse","path","import_zod","import_zod","import_zod","environmentTools","Agent"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/environments/docker-environment.ts","../src/util/escape-command.ts","../src/environments/mock-filesystem-environment.ts","../src/environments/node-filesystem-environment.ts","../src/environments/unsafe-local-environment.ts","../src/tools/copy-file-tool.ts","../src/tools/delete-file-tool.ts","../src/tools/edit-file-tool.ts","../src/tools/get-project-file-structure-tool.ts","../src/util/build-tree-from-files.ts","../src/util/get-gitignored-paths.ts","../src/tools/glob-tool.ts","../src/util/glob-to-reg-exp.ts","../src/tools/grep-tool.ts","../src/tools/list-directory-tool.ts","../src/tools/move-file-tool.ts","../src/tools/read-file-tool.ts","../src/util/get-language-identifier-from-file-path.ts","../src/tools/read-many-files-tool.ts","../src/tools/run-command-tool.ts","../src/tools/write-file-tool.ts","../src/tools/submit-tool.ts","../src/agent-creators.ts","../src/instructions.ts","../src/tool-creators.ts","../src/util/truncate.ts","../src/util/get-step-log.ts","../src/environment-creators.ts"],"sourcesContent":["/*\n * Environments\n */\nexport * from './environments/docker-environment';\nexport * from './environments/mock-filesystem-environment';\nexport * from './environments/node-filesystem-environment';\nexport * from './environments/unsafe-local-environment';\n\n/*\n * Environment tools\n */\nexport * from './tools/copy-file-tool';\nexport * from './tools/delete-file-tool';\nexport * from './tools/edit-file-tool';\nexport * from './tools/get-project-file-structure-tool';\nexport * from './tools/glob-tool';\nexport * from './tools/grep-tool';\nexport * from './tools/list-directory-tool';\nexport * from './tools/move-file-tool';\nexport * from './tools/read-file-tool';\nexport * from './tools/read-many-files-tool';\nexport * from './tools/run-command-tool';\nexport * from './tools/write-file-tool';\n\n/*\n * Misc tools\n */\nexport * from './tools/submit-tool';\n\n/*\n * Factory functions\n */\nexport * from './agent-creators';\nexport * from './environment-creators';\nexport * from './tool-creators';\n\n/*\n * Types\n */\nexport * from './types';\n","import { exec } from 'node:child_process';\nimport {\n UnixEnvironmentBase,\n escapeCommandArg,\n} from '@ai-code-agents/environment-utils';\nimport { escapeCommand } from '../util/escape-command';\n\nexport type DockerEnvironmentConfig = {\n containerId: string;\n directoryPath?: string;\n};\n\nexport const DockerEnvironmentName = 'docker';\n\n/**\n * A Docker-based execution environment that interacts with a specified Docker container.\n */\nexport class DockerEnvironment extends UnixEnvironmentBase<DockerEnvironmentConfig> {\n protected readonly _commandPrefix: string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: DockerEnvironmentConfig) {\n super(config);\n\n const { directoryPath } = this._envConfig;\n this._commandPrefix = directoryPath\n ? `cd ${escapeCommandArg(directoryPath)} && `\n : '';\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return DockerEnvironmentName;\n }\n\n /**\n * Executes a command in the environment and returns the exit code, stdout, and stderr.\n *\n * @param command - The command to execute.\n * @returns A promise that resolves to a tuple containing the exit code, stdout, and stderr.\n */\n protected async executeCommand(\n command: string,\n ): Promise<[number, string, string]> {\n return new Promise((resolve) => {\n exec(\n `docker exec ${this._envConfig.containerId} sh -c ${escapeCommand(this._commandPrefix + command)}`,\n (error, stdout, stderr) => {\n const exitCode = error ? (error.code ?? 1) : 0;\n resolve([exitCode, stdout, stderr]);\n },\n );\n });\n }\n}\n","/**\n * Escapes a command string to be safely passed as a single argument to `sh -c`.\n *\n * This function properly escapes backslashes and double quotes in the command\n * string, then wraps the entire command in double quotes. This ensures that\n * the command string is treated as a single argument and shell metacharacters\n * are not interpreted prematurely.\n *\n * @param command - The command string to escape.\n * @returns The escaped command string wrapped in double quotes.\n */\nexport function escapeCommand(command: string): string {\n // First escape backslashes, then double quotes\n const escaped = command.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n return `\"${escaped}\"`;\n}\n","import path from 'node:path';\nimport { FilesystemEnvironmentBase } from '@ai-code-agents/environment-utils';\n\nexport type MockFilesystemEnvironmentConfig = {\n initialFiles?: Record<string, string>;\n directoryPath?: string;\n};\n\nexport const MockFilesystemEnvironmentName = 'mock-filesystem';\n\n/**\n * An in-memory execution environment that simulates a filesystem.\n *\n * This environment is useful for testing purposes where you want to control the\n * filesystem state without interacting with the actual disk.\n */\nexport class MockFilesystemEnvironment extends FilesystemEnvironmentBase<MockFilesystemEnvironmentConfig> {\n protected readonly files: Map<string, string>;\n protected readonly _preparePath: (filePath: string) => string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: MockFilesystemEnvironmentConfig = {}) {\n super(config);\n\n const { initialFiles, directoryPath } = this._envConfig;\n this.files = initialFiles\n ? new Map(Object.entries(initialFiles))\n : new Map<string, string>();\n this._preparePath = directoryPath\n ? (filePath: string) => path.join(directoryPath, filePath)\n : (filePath: string) => filePath;\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return MockFilesystemEnvironmentName;\n }\n\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected async fileExists(relativePath: string): Promise<boolean> {\n return this.files.has(this._preparePath(relativePath));\n }\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected async readFileContent(relativePath: string): Promise<string> {\n return this.files.get(this._preparePath(relativePath)) ?? '';\n }\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected async writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void> {\n this.files.set(this._preparePath(relativePath), content);\n }\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected async deleteFileContent(relativePath: string): Promise<void> {\n this.files.delete(this._preparePath(relativePath));\n }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { FilesystemEnvironmentBase } from '@ai-code-agents/environment-utils';\n\nexport type NodeFilesystemEnvironmentConfig = {\n directoryPath: string;\n};\n\nexport const NodeFilesystemEnvironmentName = 'node-filesystem';\n\n/**\n * A Node.js filesystem-based execution environment.\n *\n * This environment uses Node.js fs/promises APIs to provide filesystem operations\n * within a specified directory path. All relative file paths are resolved relative\n * to the configured directoryPath.\n */\nexport class NodeFilesystemEnvironment extends FilesystemEnvironmentBase<NodeFilesystemEnvironmentConfig> {\n /**\n * Constructs a new NodeFilesystemEnvironment instance.\n *\n * @param config - Environment configuration including the mandatory directoryPath.\n */\n constructor(config: NodeFilesystemEnvironmentConfig) {\n if (!config.directoryPath) {\n throw new Error('The directory path must be provided');\n }\n\n super(config);\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return NodeFilesystemEnvironmentName;\n }\n\n /**\n * Checks whether a file exists at the specified path relative to the project directory.\n *\n * @param relativePath - The path to the file to check, relative to the project directory.\n * @returns True if the file exists, false otherwise.\n */\n protected async fileExists(relativePath: string): Promise<boolean> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n\n try {\n await fs.stat(absolutePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the content of a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to read, relative to the project directory.\n * @returns The content of the file.\n */\n protected async readFileContent(relativePath: string): Promise<string> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n return fs.readFile(absolutePath, 'utf-8');\n }\n\n /**\n * Writes content to a file at the specified path, relative to the project directory.\n *\n * This method unconditionally writes the content, even if a file already exists at the path, or if the file is new.\n *\n * @param relativePath - The path to the file to write, relative to the project directory.\n * @param content - The content to write to the file.\n */\n protected async writeFileContent(\n relativePath: string,\n content: string,\n ): Promise<void> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n await fs.writeFile(absolutePath, content, 'utf-8');\n }\n\n /**\n * Deletes a file at the specified path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the file exists.\n *\n * @param relativePath - The path to the file to delete, relative to the project directory.\n */\n protected async deleteFileContent(relativePath: string): Promise<void> {\n const absolutePath = path.join(this._envConfig.directoryPath, relativePath);\n await fs.rm(absolutePath);\n }\n\n /**\n * Moves the content of a file from a source path to a destination path, relative to the project directory.\n *\n * When this method is called, it is guaranteed that the source file exists.\n * This method unconditionally moves the content, even if a file already exists at the destination path.\n *\n * @param relativeSourcePath - The path to the file to move, relative to the project directory.\n * @param relativeDestinationPath - The path to move the file to, relative to the project directory.\n */\n protected override async moveFileContent(\n relativeSourcePath: string,\n relativeDestinationPath: string,\n ): Promise<void> {\n const sourcePath = path.join(\n this._envConfig.directoryPath,\n relativeSourcePath,\n );\n const destinationPath = path.join(\n this._envConfig.directoryPath,\n relativeDestinationPath,\n );\n await fs.rename(sourcePath, destinationPath);\n }\n}\n","import { exec } from 'node:child_process';\nimport {\n UnixEnvironmentBase,\n escapeCommandArg,\n} from '@ai-code-agents/environment-utils';\n\nexport type UnsafeLocalEnvironmentConfig = {\n directoryPath: string;\n};\n\nexport const UnsafeLocalEnvironmentName = 'unsafe-local';\n\n/**\n * A local command line execution environment in a specific directory, without any safety mechanisms.\n *\n * WARNING: This environment is unsafe because it allows unrestricted access to\n * the local file system and command line. It should only be used in controlled\n * environments where security is not a concern.\n */\nexport class UnsafeLocalEnvironment extends UnixEnvironmentBase<UnsafeLocalEnvironmentConfig> {\n protected readonly _commandPrefix: string;\n\n /**\n * Constructs a new environment instance.\n *\n * @param config - Environment configuration.\n */\n constructor(config: UnsafeLocalEnvironmentConfig) {\n const { directoryPath } = config;\n if (!directoryPath) {\n throw new Error('The directory path must be provided');\n }\n if (!directoryPath.startsWith('/')) {\n throw new Error('The directory path must be absolute (start with \"/\")');\n }\n\n super(config);\n\n this._commandPrefix = `cd ${escapeCommandArg(directoryPath)} && `;\n }\n\n /**\n * Gets the environment name.\n *\n * @returns The environment name.\n */\n get name(): string {\n return UnsafeLocalEnvironmentName;\n }\n\n /**\n * Executes a command in the environment and returns the exit code, stdout, and stderr.\n *\n * @param command - The command to execute.\n * @returns A promise that resolves to a tuple containing the exit code, stdout, and stderr.\n */\n protected async executeCommand(\n command: string,\n ): Promise<[number, string, string]> {\n return new Promise((resolve) => {\n exec(`${this._commandPrefix}${command}`, (error, stdout, stderr) => {\n const exitCode = error ? (error.code ?? 1) : 0;\n resolve([exitCode, stdout, stderr]);\n });\n });\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n CopyFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const CopyFileToolName = 'copy_file';\n\nexport type CopyFileToolConfig = ToolConfig;\n\nexport const CopyFileToolInput = z.object({\n sourcePath: z.string().meta({\n description:\n 'The path to the file to copy, relative to the project directory.',\n }),\n destinationPath: z.string().meta({\n description:\n 'The path to the destination where the file should be copied, relative to the project directory. If the file already exists, it will be overwritten.',\n }),\n});\n\nexport type CopyFileToolInput = z.infer<typeof CopyFileToolInput>;\n\nexport const CopyFileToolOutput = CopyFileResult;\n\nexport type CopyFileToolOutput = z.infer<typeof CopyFileToolOutput>;\n\n/**\n * Class for the CopyFile tool.\n */\nexport class CopyFileTool extends EnvironmentToolBase<\n CopyFileToolConfig,\n CopyFileToolInput,\n CopyFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n CopyFileToolInput,\n CopyFileToolOutput\n > {\n return {\n name: CopyFileToolName,\n description: 'Copies a file from a source path to a destination path.',\n inputSchema: CopyFileToolInput,\n outputSchema: CopyFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: CopyFileToolInput,\n ): Promise<CopyFileToolOutput> {\n return env.copyFile(input.sourcePath, input.destinationPath);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<CopyFileToolInput, CopyFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: `File \\`${output.sourcePath}\\` copied successfully to \\`${output.destinationPath}\\`.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<CopyFileToolInput, CopyFileToolOutput>> {\n return [\n {\n input: {\n sourcePath: 'src/index.ts',\n destinationPath: 'index.ts',\n },\n output: 'File `src/index.ts` copied successfully to `index.ts`.',\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n DeleteFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const DeleteFileToolName = 'delete_file';\n\nexport type DeleteFileToolConfig = ToolConfig;\n\nexport const DeleteFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to delete, relative to the project directory.',\n }),\n});\n\nexport type DeleteFileToolInput = z.infer<typeof DeleteFileToolInput>;\n\nexport const DeleteFileToolOutput = DeleteFileResult;\n\nexport type DeleteFileToolOutput = z.infer<typeof DeleteFileToolOutput>;\n\n/**\n * Class for the DeleteFile tool.\n */\nexport class DeleteFileTool extends EnvironmentToolBase<\n DeleteFileToolConfig,\n DeleteFileToolInput,\n DeleteFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n DeleteFileToolInput,\n DeleteFileToolOutput\n > {\n return {\n name: DeleteFileToolName,\n description: 'Deletes the file at the specified path.',\n inputSchema: DeleteFileToolInput,\n outputSchema: DeleteFileToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: DeleteFileToolInput,\n ): Promise<DeleteFileToolOutput> {\n return env.deleteFile(input.path);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<DeleteFileToolInput, DeleteFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: `File \\`${output.path}\\` deleted successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<DeleteFileToolInput, DeleteFileToolOutput>\n > {\n return [\n {\n input: {\n path: 'src/components/Chart.tsx',\n },\n output: 'File `src/components/Chart.tsx` deleted successfully.',\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const EditFileToolName = 'edit_file';\n\nexport type EditFileToolConfig = ToolConfig;\n\nexport const EditFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to edit, relative to the project directory.',\n }),\n oldString: z.string().meta({\n description: 'The exact string to replace in the file.',\n }),\n newString: z.string().meta({\n description: 'The string to replace the old string with.',\n }),\n replaceAll: z.boolean().optional().meta({\n description:\n 'Whether to replace all occurrences of the old string. Defaults to false.',\n }),\n});\n\nexport type EditFileToolInput = z.infer<typeof EditFileToolInput>;\n\nexport const EditFileToolOutput = z.object({\n path: z.string().meta({\n description: 'The path to the file that was edited.',\n }),\n oldString: z.string().meta({\n description: 'The old string that was replaced.',\n }),\n newString: z.string().meta({\n description: 'The new string that replaced the old string.',\n }),\n replacements: z.number().meta({\n description: 'The number of replacements made.',\n }),\n message: z.string().meta({\n description: 'A message indicating the result of the edit operation.',\n }),\n});\n\nexport type EditFileToolOutput = z.infer<typeof EditFileToolOutput>;\n\n/**\n * Escapes special regex characters in a string for literal matching.\n *\n * @param string - The string to escape.\n * @returns The escaped string.\n */\nfunction escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Class for the EditFile tool.\n */\nexport class EditFileTool extends EnvironmentToolBase<\n EditFileToolConfig,\n EditFileToolInput,\n EditFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n EditFileToolInput,\n EditFileToolOutput\n > {\n return {\n name: EditFileToolName,\n description: 'Edits a file by replacing strings.',\n inputSchema: EditFileToolInput,\n outputSchema: EditFileToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: EditFileToolInput,\n ): Promise<EditFileToolOutput> {\n const { path, oldString, newString, replaceAll = false } = input;\n\n const readResult = await env.readFile(path);\n let content = readResult.content;\n let replacements = 0;\n\n if (replaceAll) {\n const escapedOldString = escapeRegExp(oldString);\n const regex = new RegExp(escapedOldString, 'g');\n const matches = content.match(regex);\n replacements = matches ? matches.length : 0;\n content = content.replace(regex, newString);\n } else {\n const index = content.indexOf(oldString);\n if (index !== -1) {\n content =\n content.substring(0, index) +\n newString +\n content.substring(index + oldString.length);\n replacements = 1;\n }\n }\n\n await env.writeFile(path, content);\n\n const message =\n replacements > 0\n ? `Successfully made ${replacements} replacement(s) in file.`\n : 'No replacements made - old string not found.';\n\n return {\n path,\n oldString,\n newString,\n replacements,\n message,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<EditFileToolInput, EditFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: `Edited file \\`${output.path}\\` with ${output.replacements} replacement(s).`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<EditFileToolInput, EditFileToolOutput>> {\n return [\n {\n input: {\n path: 'src/example.ts',\n oldString: 'console.log(\"hello\");',\n newString: 'console.log(\"world\");',\n replaceAll: false,\n },\n output: {\n path: 'src/example.ts',\n oldString: 'console.log(\"hello\");',\n newString: 'console.log(\"world\");',\n replacements: 1,\n message: 'Successfully made 1 replacement(s) in file.',\n },\n },\n {\n input: {\n path: 'src/example.ts',\n oldString: 'var',\n newString: 'let',\n replaceAll: true,\n },\n output: {\n path: 'src/example.ts',\n oldString: 'var',\n newString: 'let',\n replacements: 3,\n message: 'Successfully made 3 replacement(s) in file.',\n },\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n escapeCommandArg,\n} from '@ai-code-agents/environment-utils';\nimport { buildTreeFromFiles } from '../util/build-tree-from-files';\nimport { getGitIgnoredPaths } from '../util/get-gitignored-paths';\n\nexport const GetProjectFileStructureToolName = 'get_project_file_structure';\n\nexport type GetProjectFileStructureToolConfig = ToolConfig;\n\nexport const GetProjectFileStructureToolInput = z.object({\n path: z.string().optional().meta({\n description:\n 'Root path to list files from, relative to the project directory. Defaults to \".\".',\n }),\n excludeGitIgnored: z.boolean().optional().meta({\n description: 'Whether to exclude files ignored by Git. Defaults to true.',\n }),\n});\n\nexport type GetProjectFileStructureToolInput = z.infer<\n typeof GetProjectFileStructureToolInput\n>;\n\nexport const GetProjectFileStructureToolOutput = z.object({\n files: z.array(z.string()).meta({\n description: 'List of all file paths found, relative to the root path.',\n }),\n excludeGitIgnored: z.boolean().meta({\n description: 'Whether files ignored by Git were excluded.',\n }),\n});\n\nexport type GetProjectFileStructureToolOutput = z.infer<\n typeof GetProjectFileStructureToolOutput\n>;\n\n/**\n * Class for the GetProjectFileStructure tool.\n */\nexport class GetProjectFileStructureTool extends EnvironmentToolBase<\n GetProjectFileStructureToolConfig,\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput\n > {\n return {\n name: GetProjectFileStructureToolName,\n description:\n 'Recursively lists all files in the project directory and formats them as a tree structure.',\n inputSchema: GetProjectFileStructureToolInput,\n outputSchema: GetProjectFileStructureToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: GetProjectFileStructureToolInput,\n ): Promise<GetProjectFileStructureToolOutput> {\n const { path = '.', excludeGitIgnored = true } = input;\n const escapedPath = escapeCommandArg(path);\n\n // The `find` command needs to be executed from the project root to ensure\n // paths are relative to the project root.\n let command = `find ${escapedPath} -type f`;\n\n // Exclude .gitignore patterns if requested.\n if (excludeGitIgnored) {\n const gitIgnoredPaths = await getGitIgnoredPaths(env);\n\n for (const gitIgnoredPath of gitIgnoredPaths) {\n // If the path doesn't end in a slash, it could be a file or a directory. Otherwise, it's a directory.\n if (!gitIgnoredPath.endsWith('/')) {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}/*`);\n command += ` -not -name ${escapeCommandArg(gitIgnoredPath)} -not -path ${escapedPath}`;\n } else {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}*`);\n command += ` -not -path ${escapedPath}`;\n }\n }\n }\n\n command += ' | sort';\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to get project file structure with command \"${command}\": ${stderr}`,\n );\n }\n\n const files = stdout\n .split('\\n')\n .map((path) => path.trim())\n .filter(Boolean); // Filter out empty strings.\n\n const trimInitialDotSlash = (path: string) =>\n path.startsWith('./') ? path.slice(2) : path;\n\n return {\n files: files.map(trimInitialDotSlash),\n excludeGitIgnored,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput\n >,\n ): ModelFormattedToolResult {\n const { output } = options;\n\n const tree = buildTreeFromFiles(output.files);\n\n if (!tree) {\n return {\n type: 'text',\n value: 'No files found.',\n };\n }\n\n return {\n type: 'text',\n value: tree,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<\n GetProjectFileStructureToolInput,\n GetProjectFileStructureToolOutput\n >\n > {\n return [\n {\n input: {},\n output: `├── **src/**\n│ ├── **components/**\n│ │ ├── **Button.js**\n│ │ └── **Header.js**\n│ └── **index.js**\n├── **tests/**\n│ └── **test_runner.py**\n├── .gitignore\n├── README.md\n└── package.json`,\n },\n ];\n }\n}\n","interface TreeNode {\n [key: string]: TreeNode;\n}\n\n/**\n * Renders the tree structure as a string.\n *\n * @param node - The current tree node to render.\n * @param prefix - The prefix string for indentation.\n * @returns The rendered tree string.\n */\nfunction renderTree(node: TreeNode, prefix = ''): string {\n const entries = Object.keys(node).sort();\n let result = '';\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n const isLast = i === entries.length - 1;\n const connector = isLast ? '└── ' : '├── ';\n const nextPrefix = prefix + (isLast ? ' ' : '│ ');\n\n result += prefix + connector + '**' + entry + '**' + '\\n';\n\n if (Object.keys(node[entry]).length > 0) {\n result += renderTree(node[entry], nextPrefix);\n }\n }\n\n return result;\n}\n\n/**\n * Builds a tree-like string representation from a list of file paths.\n *\n * @param files - Array of file paths relative to the root.\n * @returns A string representing the file structure as a tree.\n */\nexport function buildTreeFromFiles(files: string[]): string {\n if (files.length === 0) {\n return '';\n }\n\n // Sort files to ensure consistent ordering\n const sortedFiles = [...files].sort();\n\n // Build a tree structure\n const tree: TreeNode = {};\n\n for (const file of sortedFiles) {\n const parts = file.split('/');\n let current = tree;\n for (const part of parts) {\n if (!current[part]) {\n current[part] = {};\n }\n current = current[part];\n }\n }\n\n return renderTree(tree).trim();\n}\n","import path from 'node:path';\nimport {\n type CommandLineEnvironmentInterface,\n escapeCommandArg,\n} from '@ai-code-agents/environment-utils';\n\n/**\n * Gets the list of paths ignored by Git by reading the closest .gitignore file.\n *\n * @param env - The execution environment to use.\n * @returns A promise that resolves to the list of ignored paths.\n */\nexport async function getGitIgnoredPaths(\n env: CommandLineEnvironmentInterface,\n): Promise<string[]> {\n const gitignorePath = await getClosestGitIgnorePath(env);\n if (!gitignorePath) {\n return [];\n }\n\n const { stdout: pwd } = await env.runCommand('pwd');\n const currentDir = pwd.trim();\n const gitignoreDir = path.dirname(gitignorePath);\n\n try {\n const { stdout, exitCode } = await env.runCommand(\n `cat ${escapeCommandArg(gitignorePath)}`,\n );\n if (exitCode !== 0) {\n return [];\n }\n\n const rawRules = stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#')); // Ignore empty lines and comments.\n\n const relPath = path.relative(gitignoreDir, currentDir);\n if (relPath === '') {\n return rawRules.map((rule) =>\n rule.startsWith('/') ? rule.slice(1) : rule,\n );\n }\n\n const relPathSegments = relPath.split(path.sep);\n const sanitizedRules: string[] = [];\n\n for (const rule of rawRules) {\n // A rule is anchored if it starts with / or has a / in the middle.\n const isAnchored =\n rule.startsWith('/') ||\n (rule.includes('/') && rule.indexOf('/') !== rule.length - 1);\n\n // Rules starting with **/ are effectively non-anchored for our purposes of matching anywhere.\n if (!isAnchored || rule.startsWith('**/')) {\n sanitizedRules.push(rule.startsWith('**/') ? rule.slice(3) : rule);\n continue;\n }\n\n const normalizedRule = rule.startsWith('/') ? rule.slice(1) : rule;\n const cleanRule = normalizedRule.endsWith('/')\n ? normalizedRule.slice(0, -1)\n : normalizedRule;\n const ruleSegments = cleanRule.split('/');\n\n let matches = true;\n let i = 0;\n for (; i < relPathSegments.length; i++) {\n if (i >= ruleSegments.length) {\n // Rule is a parent of the current directory (e.g. rule 'packages/' and we are in 'packages/env-utils').\n // This means everything in the current directory is ignored.\n sanitizedRules.push('.');\n matches = false;\n break;\n }\n\n if (!matchSegment(ruleSegments[i], relPathSegments[i])) {\n matches = false;\n break;\n }\n }\n\n if (matches) {\n const remaining = ruleSegments.slice(i).join('/');\n if (remaining) {\n sanitizedRules.push(\n normalizedRule.endsWith('/') && !remaining.endsWith('/')\n ? `${remaining}/`\n : remaining,\n );\n } else {\n sanitizedRules.push('.');\n }\n }\n }\n\n return [...new Set(sanitizedRules)];\n } catch (_error) {\n return [];\n }\n}\n\n/**\n * Matches a single path segment against a glob pattern segment.\n *\n * @param pattern - The pattern segment (e.g. 'packages', '*', 'env-*').\n * @param segment - The actual path segment.\n * @returns True if it matches, false otherwise.\n */\nfunction matchSegment(pattern: string, segment: string): boolean {\n if (pattern === '*') {\n return true;\n }\n if (pattern === segment) {\n return true;\n }\n if (pattern.includes('*') || pattern.includes('?')) {\n // Convert glob to regex\n const regexStr = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape regex special chars\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n const regex = new RegExp(`^${regexStr}$`);\n return regex.test(segment);\n }\n return false;\n}\n\n/**\n * Gets the path to the closest .gitignore file.\n *\n * @param env - The execution environment to use.\n * @returns A promise that resolves to the path to the closest .gitignore file, or an empty string if none is found.\n */\nasync function getClosestGitIgnorePath(\n env: CommandLineEnvironmentInterface,\n): Promise<string> {\n // Use POSIX-compliant [ ] syntax instead of bash-specific [[ ]] for cross-platform compatibility.\n const command =\n 'd=$PWD; while [ -n \"$d\" ] && [ ! -f \"$d/.gitignore\" ]; do d=${d%/*}; done; [ -f \"$d/.gitignore\" ] && echo \"$d/.gitignore\"';\n const { stdout } = await env.runCommand(command);\n return stdout.trim();\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n escapeCommandArg,\n validateRelativePath,\n} from '@ai-code-agents/environment-utils';\nimport { globToRegExp } from '../util/glob-to-reg-exp';\nimport { getGitIgnoredPaths } from '../util/get-gitignored-paths';\n\nexport const GlobToolName = 'glob';\n\nexport type GlobToolConfig = ToolConfig;\n\nexport const GlobToolInput = z.object({\n searchPattern: z.string().meta({\n description:\n 'The glob pattern to search for, relative to the search path / project directory (e.g. \"**/*.ts\", \"docs/*.md\").',\n }),\n searchPath: z.string().optional().meta({\n description:\n 'The path to search within, relative to the project directory. Defaults to the project directory.',\n }),\n excludeGitIgnored: z.boolean().optional().meta({\n description: 'Whether to exclude files ignored by Git. Defaults to true.',\n }),\n});\n\nexport type GlobToolInput = z.infer<typeof GlobToolInput>;\n\nexport const GlobToolOutput = z.object({\n searchPattern: z.string().meta({\n description: 'The glob pattern that was searched for.',\n }),\n searchPath: z.string().meta({\n description: 'The path that was searched within.',\n }),\n excludeGitIgnored: z.boolean().meta({\n description: 'Whether files ignored by Git were excluded.',\n }),\n matchingPaths: z.array(z.string()).meta({\n description:\n 'The list of file paths that matched the glob search, relative to the project directory.',\n }),\n});\n\nexport type GlobToolOutput = z.infer<typeof GlobToolOutput>;\n\n/**\n * Class for the Glob tool.\n */\nexport class GlobTool extends EnvironmentToolBase<\n GlobToolConfig,\n GlobToolInput,\n GlobToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n GlobToolInput,\n GlobToolOutput\n > {\n return {\n name: GlobToolName,\n description:\n 'Runs a glob search to find matching file paths in the project.',\n inputSchema: GlobToolInput,\n outputSchema: GlobToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: GlobToolInput,\n ): Promise<GlobToolOutput> {\n const { searchPattern, searchPath = '', excludeGitIgnored = true } = input;\n\n if (searchPattern.startsWith('/')) {\n throw new Error(\n 'The search pattern must not start with a forward slash.',\n );\n }\n\n if (searchPath) {\n validateRelativePath(searchPath);\n }\n\n const untrailingslashedSearchPath =\n searchPath === '' ? '.' : searchPath.replace(/\\/+$/, '');\n\n const escapedSearchPath = escapeCommandArg(untrailingslashedSearchPath);\n\n // The `find` command needs to be executed from the project root to ensure\n // paths are relative to the project root.\n let command = `find ${escapedSearchPath} -type f`;\n\n // Exclude .gitignore patterns if requested.\n if (excludeGitIgnored) {\n const gitIgnoredPaths = await getGitIgnoredPaths(env);\n\n for (const gitIgnoredPath of gitIgnoredPaths) {\n // If the path doesn't end in a slash, it could be a file or a directory. Otherwise, it's a directory.\n if (!gitIgnoredPath.endsWith('/')) {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}/*`);\n command += ` -not -name ${escapeCommandArg(gitIgnoredPath)} -not -path ${escapedPath}`;\n } else {\n const escapedPath = escapeCommandArg(`*/${gitIgnoredPath}*`);\n command += ` -not -path ${escapedPath}`;\n }\n }\n }\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to glob files with command \"${command}\": ${stderr}`,\n );\n }\n\n const matchingPaths = stdout\n .split('\\n')\n .map((path) => path.trim())\n .filter(Boolean); // Filter out empty strings.\n\n const trimInitialDotSlash = (path: string) =>\n path.startsWith('./') ? path.slice(2) : path;\n\n if (searchPattern !== '' && searchPattern !== '**') {\n const combinedPattern = `${untrailingslashedSearchPath}/${searchPattern}`;\n\n const regExp = globToRegExp(combinedPattern);\n const filteredMatchingPaths = matchingPaths.filter((path) =>\n regExp.test(path),\n );\n\n return {\n searchPattern,\n searchPath,\n excludeGitIgnored,\n matchingPaths: filteredMatchingPaths.map(trimInitialDotSlash),\n };\n }\n\n return {\n searchPattern,\n searchPath,\n excludeGitIgnored,\n matchingPaths: matchingPaths.map(trimInitialDotSlash),\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<GlobToolInput, GlobToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n\n if (output.matchingPaths.length === 0) {\n return {\n type: 'text',\n value: 'No matching files found.',\n };\n }\n\n const bulletPoints = output.matchingPaths\n .map((path) => `- \\`${path}\\``)\n .join('\\n');\n\n return {\n type: 'text',\n value: `Matching files:\n${bulletPoints}\n`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<GlobToolInput, GlobToolOutput>> {\n return [\n {\n input: {\n searchPattern: 'src/**/*.tsx',\n },\n output: `Matching files:\n- \\`src/app/page.tsx\\`\n- \\`src/components/chart.tsx\\`\n- \\`src/components/footer.tsx\\`\n- \\`src/components/header.tsx\\`\n`,\n },\n {\n input: {\n searchPattern: '*',\n searchPath: 'packages/my-project',\n },\n output: `Matching files:\n- \\`packages/my-project/package.json\\`\n- \\`packages/my-project/README.md\\`\n- \\`packages/my-project/tsconfig.json\\`\n- \\`packages/my-project/vitest.config.ts\\`\n`,\n },\n ];\n }\n}\n","/**\n * Converts a glob pattern to a regular expression.\n *\n * This is a best-effort implementation and may not cover all edge cases of\n * glob patterns. It supports `*`, `**`, and `?`.\n *\n * @param glob - The glob pattern to convert.\n * @returns A regular expression that matches the glob pattern.\n */\nexport function globToRegExp(glob: string): RegExp {\n let reStr = '';\n for (let i = 0; i < glob.length; i++) {\n const char = glob[i];\n switch (char) {\n case '*':\n if (glob[i + 1] === '*') {\n // Handle '**/' pattern\n if (glob[i + 2] === '/') {\n reStr += '(?:.*\\\\/)?';\n i += 2; // Consume '**/'\n } else {\n reStr += '.*';\n i++; // Consume the second '*'\n }\n } else {\n reStr += '[^/]*';\n }\n break;\n case '?':\n reStr += '[^/]';\n break;\n // Escape characters with special meaning in regex.\n case '.':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '+':\n case '^':\n case '$':\n case '|':\n case '\\\\':\n reStr += `\\\\${char}`;\n break;\n default:\n reStr += char;\n }\n }\n return new RegExp(`^${reStr}$`);\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n escapeCommandArg,\n validateRelativePath,\n} from '@ai-code-agents/environment-utils';\nimport { GlobTool } from './glob-tool';\n\nexport const GrepToolName = 'grep';\n\nexport type GrepToolConfig = ToolConfig;\n\nexport const GrepToolInput = z.object({\n regexpPattern: z.string().meta({\n description:\n 'The regular expression pattern to search for in file contents.',\n }),\n searchPattern: z.string().optional().meta({\n description:\n 'The glob pattern to filter which files are searched (e.g. \"**/*.ts\"). If omitted, searches all files.',\n }),\n searchPath: z.string().optional().meta({\n description:\n 'The path to search within, relative to the project directory. Defaults to the project directory.',\n }),\n contextLines: z.number().int().nonnegative().optional().meta({\n description:\n 'The number of context lines to include before and after each match.',\n }),\n});\n\nexport type GrepToolInput = z.infer<typeof GrepToolInput>;\n\nconst GrepMatch = z.object({\n path: z.string().meta({\n description:\n 'The path to the file containing the match, relative to the project directory.',\n }),\n lineNumber: z.number().int().meta({\n description: 'The line number of the match (1-based).',\n }),\n line: z.string().meta({\n description: 'The content of the matching line.',\n }),\n beforeContext: z.array(z.string()).optional().meta({\n description: 'Lines of context before the match.',\n }),\n afterContext: z.array(z.string()).optional().meta({\n description: 'Lines of context after the match.',\n }),\n});\n\nexport type GrepMatch = z.infer<typeof GrepMatch>;\n\nexport const GrepToolOutput = z.object({\n regexpPattern: z.string().meta({\n description: 'The regular expression pattern that was searched for.',\n }),\n searchPattern: z.string().optional().meta({\n description: 'The glob pattern used to filter files.',\n }),\n searchPath: z.string().optional().meta({\n description: 'The path that was searched within.',\n }),\n contextLines: z.number().optional().meta({\n description: 'The number of context lines included.',\n }),\n matches: z.array(GrepMatch).meta({\n description: 'The list of matches found.',\n }),\n});\n\nexport type GrepToolOutput = z.infer<typeof GrepToolOutput>;\n\n/**\n * Class for the Grep tool.\n */\nexport class GrepTool extends EnvironmentToolBase<\n GrepToolConfig,\n GrepToolInput,\n GrepToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n GrepToolInput,\n GrepToolOutput\n > {\n return {\n name: GrepToolName,\n description:\n 'Searches for a regular expression pattern within the content of files in the project.',\n inputSchema: GrepToolInput,\n outputSchema: GrepToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: GrepToolInput,\n ): Promise<GrepToolOutput> {\n const {\n regexpPattern,\n searchPattern,\n searchPath = '',\n contextLines = 0,\n } = input;\n\n if (searchPath) {\n validateRelativePath(searchPath);\n }\n\n // Use GlobTool to find files to search.\n const globTool = new GlobTool(env);\n const globResult = await globTool.execute(\n {\n searchPattern: searchPattern || '**/*',\n searchPath,\n },\n {} as never,\n );\n\n const filesToSearch = globResult.matchingPaths;\n\n if (filesToSearch.length === 0) {\n return {\n regexpPattern,\n searchPattern,\n searchPath,\n contextLines,\n matches: [],\n };\n }\n\n // Batch files to avoid command line length limits.\n const BATCH_SIZE = 50;\n const matches: GrepMatch[] = [];\n\n for (let i = 0; i < filesToSearch.length; i += BATCH_SIZE) {\n const batch = filesToSearch.slice(i, i + BATCH_SIZE);\n const escapedFilePaths = batch.map(escapeCommandArg).join(' ');\n\n // grep options:\n // -n: print line number\n // -H: print file name\n // -I: ignore binary files\n // -E: extended regex\n const command = `grep -n -H -I -E ${escapeCommandArg(regexpPattern)} ${escapedFilePaths}`;\n\n const { stdout, exitCode } = await env.runCommand(command);\n\n // exitCode 0 means matches found.\n // exitCode 1 means no matches found.\n // exitCode > 1 means error.\n if (exitCode > 1) {\n throw new Error(`Failed to execute grep command \"${command}\".`);\n }\n\n if (stdout) {\n const lines = stdout.split('\\n');\n for (const line of lines) {\n if (!line.trim()) continue;\n\n // Parse grep output: filename:lineNumber:content\n // Note: filename or content might contain colons.\n // Since we use -H, it always starts with filename.\n // We know the filenames we passed in, but grep might output them relative to CWD.\n // However, since we passed relative paths to grep, it should output relative paths.\n\n const firstColonIndex = line.indexOf(':');\n if (firstColonIndex === -1) continue;\n\n const secondColonIndex = line.indexOf(':', firstColonIndex + 1);\n if (secondColonIndex === -1) continue;\n\n const filePath = line.substring(0, firstColonIndex);\n const lineNumberStr = line.substring(\n firstColonIndex + 1,\n secondColonIndex,\n );\n const content = line.substring(secondColonIndex + 1);\n\n const lineNumber = parseInt(lineNumberStr, 10);\n if (isNaN(lineNumber)) continue;\n\n matches.push({\n path: filePath,\n lineNumber,\n line: content,\n });\n }\n }\n }\n\n // If context is requested, we need to read the files.\n if (contextLines > 0 && matches.length > 0) {\n // Group matches by file to minimize file reads.\n const matchesByFile = new Map<string, GrepMatch[]>();\n for (const match of matches) {\n if (!matchesByFile.has(match.path)) {\n matchesByFile.set(match.path, []);\n }\n matchesByFile.get(match.path)!.push(match);\n }\n\n for (const [filePath, fileMatches] of matchesByFile) {\n try {\n const { content } = await env.readFile(filePath);\n const lines = content.split('\\n');\n\n for (const match of fileMatches) {\n const lineIndex = match.lineNumber - 1;\n const start = Math.max(0, lineIndex - contextLines);\n const end = Math.min(lines.length, lineIndex + contextLines + 1);\n\n match.beforeContext = lines.slice(start, lineIndex);\n match.afterContext = lines.slice(lineIndex + 1, end);\n }\n } catch (_error) {\n // Ignore errors reading file for context.\n }\n }\n }\n\n return {\n regexpPattern,\n searchPattern,\n searchPath,\n contextLines,\n matches,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<GrepToolInput, GrepToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n\n if (output.matches.length === 0) {\n return {\n type: 'text',\n value: 'No matches found.',\n };\n }\n\n let result = `Found ${output.matches.length} matches:\\n`;\n\n // Group by file for display\n const matchesByFile = new Map<string, GrepMatch[]>();\n for (const match of output.matches) {\n if (!matchesByFile.has(match.path)) {\n matchesByFile.set(match.path, []);\n }\n matchesByFile.get(match.path)!.push(match);\n }\n\n for (const [filePath, matches] of matchesByFile) {\n result += `\\nFile: ${filePath}\\n`;\n for (const match of matches) {\n if (match.beforeContext && match.beforeContext.length > 0) {\n match.beforeContext.forEach((line, idx) => {\n result += ` ${match.lineNumber - match.beforeContext!.length + idx}: ${line}\\n`;\n });\n }\n result += `> ${match.lineNumber}: ${match.line}\\n`;\n if (match.afterContext && match.afterContext.length > 0) {\n match.afterContext.forEach((line, idx) => {\n result += ` ${match.lineNumber + 1 + idx}: ${line}\\n`;\n });\n }\n if (output.contextLines && output.contextLines > 0) {\n result += '---\\n';\n }\n }\n }\n\n return {\n type: 'text',\n value: result,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<GrepToolInput, GrepToolOutput>> {\n return [\n {\n input: {\n regexpPattern: 'interface.*Tool',\n searchPattern: 'src/**/*.ts',\n },\n output: `Found 2 matches:\n\nFile: src/types.ts\n> 120: export interface ToolInterface<ToolInputType, ToolOutputType> {\n> 135: export interface EnvironmentToolInterface<\n\nFile: src/tools/tool-base.ts\n> 10: export abstract class ToolBase<\n`,\n },\n {\n input: {\n regexpPattern: 'TODO',\n contextLines: 1,\n },\n output: `Found 1 matches:\n\nFile: src/index.ts\n 10: // Some code before\n> 11: // TODO: Implement feature X\n 12: // Some code after\n`,\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n escapeCommandArg,\n} from '@ai-code-agents/environment-utils';\n\nexport const ListDirectoryToolName = 'list_directory';\n\nexport type ListDirectoryToolConfig = ToolConfig;\n\nexport const ListDirectoryToolInput = z.object({\n path: z.string().meta({\n description:\n 'The directory path to list, relative to the project directory.',\n }),\n});\n\nexport type ListDirectoryToolInput = z.infer<typeof ListDirectoryToolInput>;\n\nexport const ListDirectoryToolOutput = z.object({\n path: z.string().meta({\n description: 'The directory path that was listed.',\n }),\n files: z.array(z.string()).meta({\n description: 'List of files in the directory.',\n }),\n directories: z.array(z.string()).meta({\n description: 'List of subdirectories in the directory.',\n }),\n});\n\nexport type ListDirectoryToolOutput = z.infer<typeof ListDirectoryToolOutput>;\n\n/**\n * Class for the ListDirectory tool.\n */\nexport class ListDirectoryTool extends EnvironmentToolBase<\n ListDirectoryToolConfig,\n ListDirectoryToolInput,\n ListDirectoryToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ListDirectoryToolInput,\n ListDirectoryToolOutput\n > {\n return {\n name: ListDirectoryToolName,\n description:\n 'Lists all files and directories in the specified directory, differentiating between files and directories. Non-recursive.',\n inputSchema: ListDirectoryToolInput,\n outputSchema: ListDirectoryToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: ListDirectoryToolInput,\n ): Promise<ListDirectoryToolOutput> {\n const escapedPath = escapeCommandArg(input.path);\n const command = `ls -la ${escapedPath}`;\n\n const { stdout, stderr, exitCode } = await env.runCommand(command);\n\n if (exitCode !== 0) {\n throw new Error(\n `Failed to list directory \"${input.path}\" with command \"${command}\": ${stderr}`,\n );\n }\n\n const lines = stdout.split('\\n').filter((line) => line.trim() !== '');\n const files: string[] = [];\n const directories: string[] = [];\n\n // Skip the first line (total) and process each entry\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n // ls -la format: permissions links owner group size month day time name\n // First character indicates type: d=directory, -=file, l=symlink, etc.\n const typeChar = line.charAt(0);\n const parts = line.split(/\\s+/);\n const name = parts[parts.length - 1];\n\n // Skip . and .. entries\n if (name === '.' || name === '..') continue;\n\n if (typeChar === 'd') {\n directories.push(name);\n } else if (typeChar === '-') {\n files.push(name);\n }\n // Ignore other types (symlinks, etc.) for now\n }\n\n return {\n path: input.path,\n files,\n directories,\n };\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<\n ListDirectoryToolInput,\n ListDirectoryToolOutput\n >,\n ): ModelFormattedToolResult {\n const { output } = options;\n\n const formatEntries = (entries: string[], type: string) => {\n if (entries.length === 0) {\n return `No ${type} found.`;\n }\n const bulletPoints = entries.map((name) => `- \\`${name}\\``).join('\\n');\n return `${type.charAt(0).toUpperCase() + type.slice(1)}:\\n${bulletPoints}`;\n };\n\n const filesSection = formatEntries(output.files, 'files');\n const directoriesSection = formatEntries(output.directories, 'directories');\n\n return {\n type: 'text',\n value: `Directory listing for \\`${output.path}\\`:\\n\\n${filesSection}\\n\\n${directoriesSection}`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<ListDirectoryToolInput, ListDirectoryToolOutput>\n > {\n return [\n {\n input: {\n path: 'src',\n },\n output: `Directory listing for \\`src\\`:\n\nFiles:\n- \\`index.ts\\`\n- \\`utils.ts\\`\n\nDirectories:\n- \\`components\\`\n- \\`hooks\\``,\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n MoveFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const MoveFileToolName = 'move_file';\n\nexport type MoveFileToolConfig = ToolConfig;\n\nexport const MoveFileToolInput = z.object({\n sourcePath: z.string().meta({\n description:\n 'The path to the file to move, relative to the project directory.',\n }),\n destinationPath: z.string().meta({\n description:\n 'The path to the destination where the file should be moved, relative to the project directory. If the file already exists, it will be overwritten.',\n }),\n});\n\nexport type MoveFileToolInput = z.infer<typeof MoveFileToolInput>;\n\nexport const MoveFileToolOutput = MoveFileResult;\n\nexport type MoveFileToolOutput = z.infer<typeof MoveFileToolOutput>;\n\n/**\n * Class for the MoveFile tool.\n */\nexport class MoveFileTool extends EnvironmentToolBase<\n MoveFileToolConfig,\n MoveFileToolInput,\n MoveFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n MoveFileToolInput,\n MoveFileToolOutput\n > {\n return {\n name: MoveFileToolName,\n description: 'Moves a file from a source path to a destination path.',\n inputSchema: MoveFileToolInput,\n outputSchema: MoveFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: MoveFileToolInput,\n ): Promise<MoveFileToolOutput> {\n return env.moveFile(input.sourcePath, input.destinationPath);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<MoveFileToolInput, MoveFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: `File \\`${output.sourcePath}\\` moved successfully to \\`${output.destinationPath}\\`.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<MoveFileToolInput, MoveFileToolOutput>> {\n return [\n {\n input: {\n sourcePath: 'src/lib/types.ts',\n destinationPath: 'lib/index.ts',\n },\n output: 'File `src/lib/types.ts` moved successfully to `lib/index.ts`.',\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n ReadFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\nimport { getLanguageIdentifierFromFilePath } from '../util/get-language-identifier-from-file-path';\n\nexport const ReadFileToolName = 'read_file';\n\nexport type ReadFileToolConfig = ToolConfig;\n\nexport const ReadFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to read, relative to the project directory.',\n }),\n});\n\nexport type ReadFileToolInput = z.infer<typeof ReadFileToolInput>;\n\nexport const ReadFileToolOutput = ReadFileResult;\n\nexport type ReadFileToolOutput = z.infer<typeof ReadFileToolOutput>;\n\nconst formatModelResponse = (output: ReadFileToolOutput) => {\n const language = getLanguageIdentifierFromFilePath(output.path);\n return `File: \\`${output.path}\\`\nContent:\n\\`\\`\\`${language}\n${output.content}\n\\`\\`\\`\n`;\n};\n\n/**\n * Class for the ReadFile tool.\n */\nexport class ReadFileTool extends EnvironmentToolBase<\n ReadFileToolConfig,\n ReadFileToolInput,\n ReadFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ReadFileToolInput,\n ReadFileToolOutput\n > {\n return {\n name: ReadFileToolName,\n description: 'Reads the content of a file at the specified path.',\n inputSchema: ReadFileToolInput,\n outputSchema: ReadFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: ReadFileToolInput,\n ): Promise<ReadFileToolOutput> {\n return env.readFile(input.path);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<ReadFileToolInput, ReadFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: formatModelResponse(output),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<ReadFileToolInput, ReadFileToolOutput>> {\n const exampleContent = `import clsx from 'clsx';\n\ntype LoaderProps = {\n className?: string;\n};\n\nexport function Loader(props: LoaderProps) {\n const { className } = props;\n\n return (\n <div className={clsx('loader', className)}>\n Loading…\n </div>\n );\n}\n`;\n\n return [\n {\n input: {\n path: 'src/components/Loader.tsx',\n },\n output: formatModelResponse({\n path: 'src/components/Loader.tsx',\n content: exampleContent,\n }),\n },\n ];\n }\n}\n","/**\n * External dependencies\n */\nimport path from 'node:path';\n\nexport type ProgrammingLanguage = {\n identifier: string;\n name: string;\n fileExtensions: string[];\n};\n\nconst jsLanguage: ProgrammingLanguage = {\n identifier: 'javascript',\n name: 'JavaScript',\n fileExtensions: ['js', 'jsx'],\n};\n\nconst tsLanguage: ProgrammingLanguage = {\n identifier: 'typescript',\n name: 'TypeScript',\n fileExtensions: ['ts', 'tsx'],\n};\n\nconst ymlLanguage: ProgrammingLanguage = {\n identifier: 'yaml',\n name: 'YAML',\n fileExtensions: ['yml', 'yaml'],\n};\n\n/**\n * Language detection by file extension.\n */\nconst EXTENSION_TO_LANGUAGE: Record<string, ProgrammingLanguage> = {\n ts: tsLanguage,\n tsx: tsLanguage,\n js: jsLanguage,\n jsx: jsLanguage,\n py: {\n identifier: 'python',\n name: 'Python',\n fileExtensions: ['py'],\n },\n java: {\n identifier: 'java',\n name: 'Java',\n fileExtensions: ['java'],\n },\n c: {\n identifier: 'c',\n name: 'C',\n fileExtensions: ['c'],\n },\n cpp: {\n identifier: 'cpp',\n name: 'C++',\n fileExtensions: ['cpp'],\n },\n cs: {\n identifier: 'chsarp',\n name: 'C#',\n fileExtensions: ['cs'],\n },\n go: {\n identifier: 'go',\n name: 'Go',\n fileExtensions: ['go'],\n },\n rs: {\n identifier: 'rust',\n name: 'Rust',\n fileExtensions: ['rs'],\n },\n php: {\n identifier: 'php',\n name: 'PHP',\n fileExtensions: ['php'],\n },\n rb: {\n identifier: 'ruby',\n name: 'Ruby',\n fileExtensions: ['rb'],\n },\n swift: {\n identifier: 'swift',\n name: 'Swift',\n fileExtensions: ['swift'],\n },\n kt: {\n identifier: 'kotlin',\n name: 'Kotlin',\n fileExtensions: ['kt'],\n },\n scala: {\n identifier: 'scala',\n name: 'Scala',\n fileExtensions: ['scala'],\n },\n html: {\n identifier: 'html',\n name: 'HTML',\n fileExtensions: ['html'],\n },\n css: {\n identifier: 'css',\n name: 'CSS',\n fileExtensions: ['css'],\n },\n sass: {\n identifier: 'sass',\n name: 'Sass',\n fileExtensions: ['sass'],\n },\n scss: {\n identifier: 'scss',\n name: 'SCSS',\n fileExtensions: ['scss'],\n },\n less: {\n identifier: 'less',\n name: 'Less',\n fileExtensions: ['less'],\n },\n json: {\n identifier: 'json',\n name: 'JSON',\n fileExtensions: ['json'],\n },\n md: {\n identifier: 'markdown',\n name: 'Markdown',\n fileExtensions: ['md'],\n },\n toml: {\n identifier: 'toml',\n name: 'TOML',\n fileExtensions: ['toml'],\n },\n yml: ymlLanguage,\n yaml: ymlLanguage,\n xml: {\n identifier: 'xml',\n name: 'XML',\n fileExtensions: ['xml'],\n },\n sql: {\n identifier: 'sql',\n name: 'SQL',\n fileExtensions: ['sql'],\n },\n graphql: {\n identifier: 'graphql',\n name: 'GraphQL',\n fileExtensions: ['graphql'],\n },\n sh: {\n identifier: 'bash',\n name: 'Shell',\n fileExtensions: ['sh'],\n },\n ps1: {\n identifier: 'bash',\n name: 'PowerShell',\n fileExtensions: ['ps1'],\n },\n};\n\n/**\n * Returns programming language information for a file path.\n *\n * @param filePath - File path.\n * @returns Programming language information, or null if none could be identified.\n */\nfunction getLanguageFromFilePath(\n filePath: string,\n): ProgrammingLanguage | undefined {\n const extension = path.extname(filePath).slice(1).toLowerCase() || '';\n return EXTENSION_TO_LANGUAGE[extension];\n}\n\n/**\n * Returns the programming language identifier for a file path.\n *\n * @param filePath - File path.\n * @returns Programming language identifier, or empty string if none could be identified.\n */\nexport function getLanguageIdentifierFromFilePath(filePath: string): string {\n const language = getLanguageFromFilePath(filePath);\n return language ? language.identifier : '';\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n ReadFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\nimport { getLanguageIdentifierFromFilePath } from '../util/get-language-identifier-from-file-path';\n\nexport const ReadManyFilesToolName = 'read_many_files';\n\nexport type ReadManyFilesToolConfig = ToolConfig;\n\nexport const ReadManyFilesToolInput = z.object({\n paths: z.array(z.string()).meta({\n description:\n 'The paths to the files to read, relative to the project directory.',\n }),\n});\n\nexport type ReadManyFilesToolInput = z.infer<typeof ReadManyFilesToolInput>;\n\nexport const ReadManyFilesToolOutput = z.record(z.string(), ReadFileResult);\n\nexport type ReadManyFilesToolOutput = z.infer<typeof ReadManyFilesToolOutput>;\n\nconst formatModelResponse = (output: ReadManyFilesToolOutput[string]) => {\n const language = getLanguageIdentifierFromFilePath(output.path);\n return `File: \\`${output.path}\\`\nContent:\n\\`\\`\\`${language}\n${output.content}\n\\`\\`\\`\n`;\n};\n\n/**\n * Class for the ReadManyFiles tool.\n */\nexport class ReadManyFilesTool extends EnvironmentToolBase<\n ReadManyFilesToolConfig,\n ReadManyFilesToolInput,\n ReadManyFilesToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n ReadManyFilesToolInput,\n ReadManyFilesToolOutput\n > {\n return {\n name: ReadManyFilesToolName,\n description: 'Reads the contents of the files at the specified paths.',\n inputSchema: ReadManyFilesToolInput,\n outputSchema: ReadManyFilesToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected async executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: ReadManyFilesToolInput,\n ): Promise<ReadManyFilesToolOutput> {\n const results: ReadFileResult[] = await Promise.all(\n input.paths.map((path) => env.readFile(path)),\n );\n\n return results.reduce((acc, result) => {\n acc[result.path] = result;\n return acc;\n }, {} as ReadManyFilesToolOutput);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<\n ReadManyFilesToolInput,\n ReadManyFilesToolOutput\n >,\n ): ModelFormattedToolResult {\n const { output } = options;\n\n const fileContentResponses = Object.values(output).map((fileResult) =>\n formatModelResponse(fileResult),\n );\n\n return {\n type: 'text',\n value: fileContentResponses.join('\\n'),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<ReadManyFilesToolInput, ReadManyFilesToolOutput>\n > {\n const exampleContent1 = `import clsx from 'clsx';\n\ntype LoaderProps = {\n className?: string;\n};\n\nexport function Loader(props: LoaderProps) {\n const { className } = props;\n\n return (\n <div className={clsx('loader', className)}>\n Loading…\n </div>\n );\n}\n`;\n const exampleContent2 = `export function snakeCaseToCamelCase(snakeCase: string): string {\n return snakeCase.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n`;\n\n return [\n {\n input: {\n paths: [\n 'src/components/Loader.tsx',\n 'src/util/snake-case-to-camel-case.ts',\n ],\n },\n output:\n formatModelResponse({\n path: 'src/components/Loader.tsx',\n content: exampleContent1,\n }) +\n '\\n' +\n formatModelResponse({\n path: 'src/util/snake-case-to-camel-case.ts',\n content: exampleContent2,\n }),\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n RunCommandResult,\n type CommandLineEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const RunCommandToolName = 'run_command';\n\nexport type RunCommandToolConfig = ToolConfig;\n\nexport const RunCommandToolInput = z.object({\n command: z\n .string()\n .meta({ description: 'The CLI command to run, including all arguments.' }),\n});\n\nexport type RunCommandToolInput = z.infer<typeof RunCommandToolInput>;\n\nexport const RunCommandToolOutput = RunCommandResult;\n\nexport type RunCommandToolOutput = z.infer<typeof RunCommandToolOutput>;\n\n/**\n * Formats the command result into a model-friendly response string.\n *\n * @param output - The command result output.\n * @returns The formatted string for model consumption.\n */\nfunction formatCommandResultToModelResponse(output: RunCommandResult) {\n const stdout = !output.stdout.trim()\n ? '(none)'\n : `\n\\`\\`\\`\n${output.stdout}\n\\`\\`\\``;\n const stderr = !output.stderr.trim()\n ? '(none)'\n : `\n\\`\\`\\`\n${output.stderr}\n\\`\\`\\``;\n\n return `Command: \\`${output.command}\\`\nExit Code: ${output.exitCode}\nOutput (stdout): ${stdout}\nError Output (stderr): ${stderr}\n`;\n}\n\n/**\n * Class for the RunCommand tool.\n *\n * WARNING: This tool can be dangerous if misused. It allows executing arbitrary commands in the environment.\n * Only allow using this tool in sandboxed environments where the potential risks are understood and mitigated.\n */\nexport class RunCommandTool extends EnvironmentToolBase<\n RunCommandToolConfig,\n RunCommandToolInput,\n RunCommandToolOutput,\n CommandLineEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n RunCommandToolInput,\n RunCommandToolOutput\n > {\n return {\n name: RunCommandToolName,\n description: 'Runs the specific CLI command.',\n inputSchema: RunCommandToolInput,\n outputSchema: RunCommandToolOutput,\n needsApproval: true,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: CommandLineEnvironmentInterface,\n input: RunCommandToolInput,\n ): Promise<RunCommandToolOutput> {\n return env.runCommand(input.command);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<RunCommandToolInput, RunCommandToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: formatCommandResultToModelResponse(output),\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<\n ToolExample<RunCommandToolInput, RunCommandToolOutput>\n > {\n const exampleGitOutput = `diff --git a/src/util/string-utils.ts b/src/util/string-utils.ts\nindex 1836072..b13adef 100644\n--- a/src/util/string-utils.ts\n+++ b/src/util/string-utils.ts\n@@ -1,3 +1,7 @@\n export function snakeCaseToCamelCase(str: string): string {\n return str.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase());\n }\n+\n+export function camelCaseToSnakeCase(str: string): string {\n+ return str.replace(/([A-Z])/g, (match) => \\`_\\${match.toLowerCase()}\\`);\n+}\n`;\n\n const exampleNpmOutput = `\nadded 1 package, and changed 1 package in 2s\n\n156 packages are looking for funding\n run \\`npm fund\\` for details`;\n\n const exampleMkdirError = `mkdir: src/lib: No such file or directory\n`;\n\n return [\n {\n input: {\n command: 'git --no-pager diff',\n },\n output: formatCommandResultToModelResponse({\n command: 'git --no-pager diff',\n exitCode: 0,\n stdout: exampleGitOutput,\n stderr: '',\n }),\n },\n {\n input: {\n command: 'npm install zod',\n },\n output: formatCommandResultToModelResponse({\n command: 'npm install zod',\n exitCode: 0,\n stdout: exampleNpmOutput,\n stderr: '',\n }),\n },\n {\n input: {\n command: 'mkdir src/lib/api',\n },\n output: formatCommandResultToModelResponse({\n command: 'mkdir src/lib/api',\n exitCode: 1,\n stdout: '',\n stderr: exampleMkdirError,\n }),\n },\n ];\n }\n}\n","import { z } from 'zod';\nimport {\n EnvironmentToolBase,\n type EnvironmentToolMetadata,\n WriteFileResult,\n type FilesystemEnvironmentInterface,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const WriteFileToolName = 'write_file';\n\nexport type WriteFileToolConfig = ToolConfig;\n\nexport const WriteFileToolInput = z.object({\n path: z.string().meta({\n description:\n 'The path to the file to write, relative to the project directory.',\n }),\n content: z.string().meta({\n description:\n 'The content to write to the file. If the file already exists, the content will replace existing content.',\n }),\n});\n\nexport type WriteFileToolInput = z.infer<typeof WriteFileToolInput>;\n\nexport const WriteFileToolOutput = WriteFileResult;\n\nexport type WriteFileToolOutput = z.infer<typeof WriteFileToolOutput>;\n\n/**\n * Class for the WriteFile tool.\n */\nexport class WriteFileTool extends EnvironmentToolBase<\n WriteFileToolConfig,\n WriteFileToolInput,\n WriteFileToolOutput,\n FilesystemEnvironmentInterface\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): EnvironmentToolMetadata<\n WriteFileToolInput,\n WriteFileToolOutput\n > {\n return {\n name: WriteFileToolName,\n description: 'Writes content to a file at the specified path.',\n inputSchema: WriteFileToolInput,\n outputSchema: WriteFileToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool in the given execution environment with the given input.\n *\n * @param env - The execution environment to use.\n * @param input - The input for the tool.\n * @returns A promise that resolves to the tool execution result.\n */\n protected executeForEnvironment(\n env: FilesystemEnvironmentInterface,\n input: WriteFileToolInput,\n ): Promise<WriteFileToolOutput> {\n return env.writeFile(input.path, input.content);\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param options - The tool result, including the output from the tool execution.\n * @returns The formatted tool result.\n */\n toModelOutput(\n options: ModelToolResultToFormat<WriteFileToolInput, WriteFileToolOutput>,\n ): ModelFormattedToolResult {\n const { output } = options;\n return {\n type: 'text',\n value: `File \\`${output.path}\\` written successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<WriteFileToolInput, WriteFileToolOutput>> {\n const exampleContent = `export function snakeCaseToCamelCase(snakeCase: string): string {\n return snakeCase.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n`;\n\n return [\n {\n input: {\n path: 'src/util/snake-case-to-camel-case.ts',\n content: exampleContent,\n },\n output:\n 'File `src/util/snake-case-to-camel-case.ts` written successfully.',\n },\n ];\n }\n}\n","import type { ToolExecutionOptions } from 'ai';\nimport { z } from 'zod';\nimport {\n ToolBase,\n type ToolMetadata,\n type ToolConfig,\n type ToolExample,\n type ModelToolResultToFormat,\n type ModelFormattedToolResult,\n} from '@ai-code-agents/environment-utils';\n\nexport const SubmitToolName = 'submit';\n\nexport type SubmitToolConfig = ToolConfig;\n\nexport const SubmitToolInput = z.object({});\n\nexport type SubmitToolInput = z.infer<typeof SubmitToolInput>;\n\nexport const SubmitToolOutput = z.object({});\n\nexport type SubmitToolOutput = z.infer<typeof SubmitToolOutput>;\n\n/**\n * Class for the Submit tool.\n */\nexport class SubmitTool extends ToolBase<\n SubmitToolConfig,\n SubmitToolInput,\n SubmitToolOutput\n> {\n /**\n * Returns the metadata for the tool.\n *\n * The name, description, and needsApproval properties are defaults which can be overridden in the constructor.\n *\n * @returns The tool metadata.\n */\n protected getMetadata(): ToolMetadata<SubmitToolInput, SubmitToolOutput> {\n return {\n name: SubmitToolName,\n description: 'Submits the current task, indicating that it is completed.',\n inputSchema: SubmitToolInput,\n outputSchema: SubmitToolOutput,\n needsApproval: false,\n };\n }\n\n /**\n * Executes the tool with the given input.\n *\n * @param _ - The input for the tool. Unused.\n * @param __ - Options for the tool execution. Unused.\n * @returns A promise that resolves to the tool execution result.\n */\n async execute(\n _: SubmitToolInput,\n __: ToolExecutionOptions,\n ): Promise<SubmitToolOutput> {\n return {};\n }\n\n /**\n * Converts the tool output to a format suitable for model consumption.\n *\n * @param _ - The tool result, including the output from the tool execution. Unused.\n * @returns The formatted tool result.\n */\n toModelOutput(\n _: ModelToolResultToFormat<SubmitToolInput, SubmitToolOutput>,\n ): ModelFormattedToolResult {\n return {\n type: 'text',\n value: `Task submitted successfully.`,\n };\n }\n\n /**\n * Gets the examples for the tool.\n *\n * @returns The tool examples.\n */\n get examples(): Array<ToolExample<SubmitToolInput, SubmitToolOutput>> {\n return [];\n }\n}\n","import type { Tool } from '@ai-sdk/provider-utils';\nimport {\n ToolLoopAgent,\n type ToolLoopAgentSettings,\n type SystemModelMessage,\n stepCountIs,\n hasToolCall,\n} from 'ai';\nimport { getAdditionalInstructions } from './instructions';\nimport {\n createToolsForEnvironment,\n createToolsForNamedEnvironment,\n type ToolsDefinition,\n} from './tool-creators';\nimport type { Environment } from './types';\nimport { SubmitTool, SubmitToolName } from './tools/submit-tool';\nimport { getStepLog } from './util/get-step-log';\n\ntype FlexibleAgent = ToolLoopAgent<never, Record<string, Tool>>;\ntype FlexibleAgentSettings = ToolLoopAgentSettings<never, Record<string, Tool>>;\n\nexport type CodeAgentToolsCreatorConfig =\n | {\n environment: Environment;\n environmentToolsDefinition: ToolsDefinition;\n }\n | {\n environments: Record<string, Environment>;\n environmentToolsDefinition: Record<string, ToolsDefinition>;\n };\n\nexport type CodeAgentCreatorConfig = FlexibleAgentSettings & {\n maxSteps: number;\n allowSubmit?: boolean;\n logStep?: (stepLog: string, stepIndex: number) => void;\n omitAdditionalInstructions?: boolean;\n} & (CodeAgentToolsCreatorConfig | Record<string, never>);\n\ntype FlexibleAgentTools = Exclude<FlexibleAgentSettings['tools'], undefined>;\n\ntype FlexibleAgentStopWhen = Exclude<\n FlexibleAgentSettings['stopWhen'],\n undefined\n>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype FirstFunctionArgument<T> = T extends (arg1: infer U, ...args: any[]) => any\n ? U\n : never;\n\n/**\n * Creates an AI code agent configured to operate on one or more specified execution environments with tools.\n *\n * @param agentConfig - Configuration options for the code agent, including environments, tools definition, and agent settings.\n * @returns An agent instance configured with the specified environment tools and settings.\n */\nexport function createCodeAgent(\n agentConfig: CodeAgentCreatorConfig,\n): FlexibleAgent {\n return new ToolLoopAgent(createCodeAgentSettings(agentConfig));\n}\n\n/**\n * Creates settings object for an AI code agent configured to operate on one or more specified execution environments with tools.\n *\n * @param agentConfig - Configuration options for the code agent, including environments, tools definition, and agent settings.\n * @returns An agent settings object configured with the specified environment tools and settings.\n */\nexport function createCodeAgentSettings(\n agentConfig: CodeAgentCreatorConfig,\n): FlexibleAgentSettings {\n const {\n maxSteps,\n allowSubmit,\n logStep,\n omitAdditionalInstructions,\n tools: originalTools,\n stopWhen: originalStopWhen,\n prepareStep: originalPrepareStep,\n instructions: originalSystemInstruction,\n ...remainingConfig\n } = agentConfig;\n\n let agentSettings: FlexibleAgentSettings;\n let tools: FlexibleAgentTools;\n if ('environments' in remainingConfig) {\n const { environments, environmentToolsDefinition, ...agentSettingsInput } =\n remainingConfig;\n agentSettings = { ...agentSettingsInput };\n\n tools = createCodeAgentTools(\n { environments, environmentToolsDefinition },\n originalTools,\n );\n } else if ('environment' in remainingConfig) {\n const { environment, environmentToolsDefinition, ...agentSettingsInput } =\n remainingConfig;\n agentSettings = { ...agentSettingsInput };\n\n tools = createCodeAgentTools(\n { environment, environmentToolsDefinition },\n originalTools,\n );\n } else {\n agentSettings = { ...remainingConfig };\n\n tools = originalTools || {};\n }\n\n if (allowSubmit) {\n if (SubmitToolName in tools) {\n throw new Error(\n `Tool name conflict: The Submit tool name \"${SubmitToolName}\" is already used by another tool.`,\n );\n }\n tools[SubmitToolName] = new SubmitTool();\n }\n\n if (Object.keys(tools).length > 0) {\n agentSettings.tools = tools;\n }\n\n let stepCount = 0;\n const prepareStep = logStep\n ? (prepareStepInput: FirstFunctionArgument<typeof originalPrepareStep>) => {\n const { steps } = prepareStepInput;\n if (steps.length > 0) {\n stepCount += 1;\n const stepLog = getStepLog(steps[steps.length - 1]);\n logStep(`=== Step ${stepCount} ===\\n${stepLog}`, stepCount - 1);\n }\n if (originalPrepareStep) {\n return originalPrepareStep(prepareStepInput);\n }\n return undefined;\n }\n : originalPrepareStep;\n\n const stopWhenCondition = allowSubmit\n ? [stepCountIs(maxSteps), hasToolCall(SubmitToolName)]\n : stepCountIs(maxSteps);\n const stopWhen = originalStopWhen\n ? mergeStopWhen(originalStopWhen, stopWhenCondition)\n : stopWhenCondition;\n\n const instructions = !omitAdditionalInstructions\n ? mergeSystemInstructions(\n originalSystemInstruction,\n getAdditionalInstructions({ maxSteps, allowSubmit, tools }),\n )\n : originalSystemInstruction;\n\n return {\n ...agentSettings,\n instructions,\n prepareStep,\n stopWhen,\n };\n}\n\n/**\n * Creates agent tools based on the provided configuration.\n *\n * This function generates a set of tools for one or more environments, depending on the configuration.\n * If `environments` is provided, it creates tools for each named environment using the corresponding\n * tools definition. If `environment` is provided, it creates tools for a single environment.\n * The generated tools can be merged with optional original tools.\n *\n * @param agentToolsConfig - The configuration object specifying environments and their tools definitions.\n * @param originalTools - Optional existing tools to merge with the newly created environment tools.\n * @returns An object containing the created agent tools, merged with original tools if provided.\n */\nexport function createCodeAgentTools(\n agentToolsConfig: CodeAgentToolsCreatorConfig,\n originalTools?: FlexibleAgentTools,\n): FlexibleAgentTools {\n if ('environments' in agentToolsConfig) {\n const { environments, environmentToolsDefinition } = agentToolsConfig;\n\n const environmentTools: Record<string, Tool> = {};\n for (const [environmentName, environment] of Object.entries(environments)) {\n if (!(environmentName in environmentToolsDefinition)) {\n throw new Error(\n `No tools definition provided for environment \"${environmentName}\". Please provide a tools definition for each environment.`,\n );\n }\n const envTools = createToolsForNamedEnvironment(\n environmentName,\n environment,\n environmentToolsDefinition[environmentName],\n );\n for (const [toolName, tool] of Object.entries(envTools)) {\n if (toolName in environmentTools) {\n throw new Error(\n `Tool name conflict: The tool name \"${toolName}\" from environment \"${environmentName}\" is already used by another environment's tools.`,\n );\n }\n environmentTools[toolName] = tool;\n }\n }\n\n return originalTools\n ? mergeTools(environmentTools, originalTools)\n : environmentTools;\n }\n\n if ('environment' in agentToolsConfig) {\n const { environment, environmentToolsDefinition } = agentToolsConfig;\n\n const environmentTools: Record<string, Tool> = createToolsForEnvironment(\n environment,\n environmentToolsDefinition,\n );\n\n return originalTools\n ? mergeTools(environmentTools, originalTools)\n : environmentTools;\n }\n\n throw new Error(\n 'No environments provided in agent tools configuration. Please provide either \"environment\" or \"environments\".',\n );\n}\n\n/**\n * Merges two sets of tools into one, ensuring no name conflicts.\n *\n * @param baseTools - The base set of tools.\n * @param additionalTools - Additional tools to merge into the base set.\n * @returns A new record containing all tools from both sets.\n */\nfunction mergeTools(\n baseTools: FlexibleAgentTools,\n additionalTools: FlexibleAgentTools,\n): FlexibleAgentTools {\n const tools = { ...baseTools };\n for (const [toolName, tool] of Object.entries(additionalTools)) {\n if (toolName in tools) {\n throw new Error(\n `Tool name conflict: The additional tool name \"${toolName}\" is already used by the code environment tools.`,\n );\n }\n tools[toolName] = tool;\n }\n return tools;\n}\n\n/**\n * Merges two stopWhen conditions into one.\n *\n * @param baseStopWhen - The base stopWhen condition.\n * @param additionalStopWhen - The additional stopWhen condition to merge.\n * @returns A combined stopWhen condition.\n */\nfunction mergeStopWhen(\n baseStopWhen: FlexibleAgentStopWhen,\n additionalStopWhen: FlexibleAgentStopWhen,\n): FlexibleAgentStopWhen {\n if (Array.isArray(baseStopWhen)) {\n if (Array.isArray(additionalStopWhen)) {\n return [...baseStopWhen, ...additionalStopWhen];\n }\n\n return [...baseStopWhen, additionalStopWhen];\n }\n\n if (Array.isArray(additionalStopWhen)) {\n return [baseStopWhen, ...additionalStopWhen];\n }\n\n return [baseStopWhen, additionalStopWhen];\n}\n\n/**\n * Merges the base system instructions with additional instructions.\n *\n * If no base system instructions are provided, only the additional instructions are returned.\n *\n * @param baseInstructions - The base system instructions, or undefined if none.\n * @param additionalInstructions - The additional instructions to append.\n * @returns The merged system instructions.\n */\nfunction mergeSystemInstructions(\n baseInstructions:\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined,\n additionalInstructions: string,\n): string | SystemModelMessage | SystemModelMessage[] {\n if (baseInstructions) {\n if (Array.isArray(baseInstructions)) {\n return [\n ...baseInstructions,\n {\n role: 'system',\n content: additionalInstructions,\n },\n ];\n }\n if (typeof baseInstructions === 'object') {\n return {\n ...baseInstructions,\n content: `${baseInstructions.content.trimEnd()}\\n\\n${additionalInstructions}`,\n };\n }\n return `${baseInstructions.trimEnd()}\\n\\n${additionalInstructions}`;\n }\n return additionalInstructions;\n}\n","import type { ToolExample } from '@ai-code-agents/environment-utils';\nimport type { Tool } from '@ai-sdk/provider-utils';\nimport { SubmitToolName } from './tools/submit-tool';\n\n// See https://github.com/galfrevn/promptsmith.\ntype ConstraintType = 'must' | 'must_not' | 'should' | 'should_not';\ntype ConstraintsByType = {\n [key in ConstraintType]?: string[];\n};\n\ntype ConstraintsConfig = {\n maxSteps: number;\n allowSubmit?: boolean;\n};\n\ntype AdditionalInstructionsConfig = ConstraintsConfig & {\n tools: Record<string, Tool>;\n};\n\n/**\n * Generates additional system instructions for the code agent based on the provided configuration.\n *\n * @param config - Configuration object containing maxSteps and tools.\n * @returns A string containing the additional instructions, to append to the system prompt.\n */\nexport function getAdditionalInstructions(\n config: AdditionalInstructionsConfig,\n): string {\n const { maxSteps, allowSubmit, tools } = config;\n\n const exampleSections: string[] = [\n '# Tool Examples',\n 'You have access to several tools to assist you in completing your task. Here are some examples of how to use them:',\n ];\n for (const [toolName, tool] of Object.entries(tools)) {\n if (\n 'examples' in tool &&\n Array.isArray(tool.examples) &&\n tool.examples.length > 0\n ) {\n let toolSection = `## Tool: \\`${toolName}\\`\\n\\n`;\n for (const example of tool.examples) {\n toolSection += formatExampleForInstructions(toolName, example);\n }\n exampleSections.push(toolSection.trim());\n }\n }\n\n const constraintSections: string[] = ['# Behavioral Guidelines'];\n const constraintsByType = getCodeAgentConstraints({ maxSteps, allowSubmit });\n if (constraintsByType.must && constraintsByType.must.length > 0) {\n let constraintSection = '## You MUST:\\n\\n';\n for (const constraint of constraintsByType.must) {\n constraintSection += `- ${constraint}\\n`;\n }\n constraintSections.push(constraintSection.trim());\n }\n if (constraintsByType.must_not && constraintsByType.must_not.length > 0) {\n let constraintSection = '## You MUST NOT:\\n\\n';\n for (const constraint of constraintsByType.must_not) {\n constraintSection += `- ${constraint}\\n`;\n }\n constraintSections.push(constraintSection.trim());\n }\n if (constraintsByType.should && constraintsByType.should.length > 0) {\n let constraintSection = '## You SHOULD:\\n\\n';\n for (const constraint of constraintsByType.should) {\n constraintSection += `- ${constraint}\\n`;\n }\n constraintSections.push(constraintSection.trim());\n }\n if (constraintsByType.should_not && constraintsByType.should_not.length > 0) {\n let constraintSection = '## You SHOULD NOT:\\n\\n';\n for (const constraint of constraintsByType.should_not) {\n constraintSection += `- ${constraint}\\n`;\n }\n constraintSections.push(constraintSection.trim());\n }\n\n const finalReminder = getCodeAgentFinalReminder();\n\n return [...exampleSections, ...constraintSections, finalReminder].join(\n '\\n\\n',\n );\n}\n\n/**\n * Formats a tool example for inclusion in the code agent system instructions.\n *\n * @param toolName - The name of the tool.\n * @param example - The tool example to format.\n * @returns The formatted tool example string.\n */\nexport function formatExampleForInstructions<ToolInputType, ToolOutputType>(\n toolName: string,\n example: ToolExample<ToolInputType, ToolOutputType>,\n): string {\n const input = formatValueForExample(example.input);\n const output = formatValueForExample(example.output);\n\n if (output === '') {\n return `<example>\n<tool_call>\n${toolName}(${input})\n</tool_call>\n</example>`;\n }\n\n return `<example>\n<tool_call>\n${toolName}(${input})\n</tool_call>\n<tool_response>\n${output}\n</tool_response>\n</example>`;\n}\n\n/**\n * Formats a value for inclusion in a tool example.\n *\n * @param value - The value to format.\n * @returns The formatted value as a string.\n */\nfunction formatValueForExample(value: unknown): string {\n if (typeof value === 'undefined') {\n return '';\n }\n if (typeof value === 'string') {\n return `\"${value}\"`;\n }\n if (typeof value === 'number') {\n return value.toString();\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n return JSON.stringify(value, null, 2);\n}\n\n/**\n * Generates constraints for the code agent system instructions based on the provided configuration.\n *\n * The constraints are formatted in accordance with the PromptSmith framework.\n * You can pass them to the prompt builder's `withConstraints` method.\n *\n * @param config - Configuration object containing maxSteps and allowSubmit.\n * @returns An object containing constraints to include in the system prompt, categorized by type.\n */\nexport function getCodeAgentConstraints(\n config: ConstraintsConfig,\n): ConstraintsByType {\n const { maxSteps, allowSubmit } = config;\n\n return {\n must: [\n 'Always issue tool calls to complete your task',\n ...(allowSubmit\n ? [\n `Call the \\`${SubmitToolName}\\` tool once you think you have completed your task, to submit your results`,\n ]\n : []),\n `Complete your task within ${maxSteps} steps`,\n ],\n must_not: ['Engage with the user directly'],\n };\n}\n\n/**\n * Returns a final reminder message for the code agent system instructions.\n *\n * @returns The reminder string.\n */\nexport function getCodeAgentFinalReminder(): string {\n return \"Remember, you don't get to ask the user any clarifying questions, just use the tools available to complete your task. You're on your own now.\";\n}\n","import {\n isCommandLine,\n type Environment,\n type EnvironmentToolBase,\n} from '@ai-code-agents/environment-utils';\nimport type { Tool } from '@ai-sdk/provider-utils';\nimport { ReadFileTool, ReadFileToolName } from './tools/read-file-tool';\nimport { WriteFileTool, WriteFileToolName } from './tools/write-file-tool';\nimport { DeleteFileTool, DeleteFileToolName } from './tools/delete-file-tool';\nimport { EditFileTool, EditFileToolName } from './tools/edit-file-tool';\nimport { MoveFileTool, MoveFileToolName } from './tools/move-file-tool';\nimport { CopyFileTool, CopyFileToolName } from './tools/copy-file-tool';\nimport {\n ReadManyFilesTool,\n ReadManyFilesToolName,\n} from './tools/read-many-files-tool';\nimport {\n GetProjectFileStructureTool,\n GetProjectFileStructureToolName,\n} from './tools/get-project-file-structure-tool';\nimport { GlobTool, GlobToolName } from './tools/glob-tool';\nimport { GrepTool, GrepToolName } from './tools/grep-tool';\nimport {\n ListDirectoryTool,\n ListDirectoryToolName,\n} from './tools/list-directory-tool';\nimport { RunCommandTool, RunCommandToolName } from './tools/run-command-tool';\n\nconst availableEnvironmentTools = {\n [ReadFileToolName]: ReadFileTool,\n [WriteFileToolName]: WriteFileTool,\n [DeleteFileToolName]: DeleteFileTool,\n [EditFileToolName]: EditFileTool,\n [MoveFileToolName]: MoveFileTool,\n [CopyFileToolName]: CopyFileTool,\n [ReadManyFilesToolName]: ReadManyFilesTool,\n [GetProjectFileStructureToolName]: GetProjectFileStructureTool,\n [GlobToolName]: GlobTool,\n [GrepToolName]: GrepTool,\n [ListDirectoryToolName]: ListDirectoryTool,\n [RunCommandToolName]: RunCommandTool,\n};\n\ntype EnvironmentToolClasses = {\n [ReadFileToolName]: ReadFileTool;\n [WriteFileToolName]: WriteFileTool;\n [DeleteFileToolName]: DeleteFileTool;\n [EditFileToolName]: EditFileTool;\n [MoveFileToolName]: MoveFileTool;\n [CopyFileToolName]: CopyFileTool;\n [ReadManyFilesToolName]: ReadManyFilesTool;\n [GetProjectFileStructureToolName]: GetProjectFileStructureTool;\n [GlobToolName]: GlobTool;\n [GrepToolName]: GrepTool;\n [ListDirectoryToolName]: ListDirectoryTool;\n [RunCommandToolName]: RunCommandTool;\n};\n\nconst cliOnlyTools: EnvironmentToolName[] = [\n GetProjectFileStructureToolName,\n GlobToolName,\n GrepToolName,\n ListDirectoryToolName,\n RunCommandToolName,\n];\n\nconst readonlyTools: EnvironmentToolName[] = [\n ReadFileToolName,\n ReadManyFilesToolName,\n GetProjectFileStructureToolName,\n GlobToolName,\n GrepToolName,\n ListDirectoryToolName,\n];\n\nconst dangerousTools: EnvironmentToolName[] = [\n DeleteFileToolName,\n RunCommandToolName,\n];\n\nexport type EnvironmentToolSafetyLevel = 'readonly' | 'basic' | 'all';\nexport const EnvironmentToolSafetyLevels: EnvironmentToolSafetyLevel[] = [\n 'readonly',\n 'basic',\n 'all',\n];\n\ntype EnvironmentToolGenerics<T> =\n T extends EnvironmentToolBase<\n infer ToolConfig,\n infer ToolInput,\n infer ToolOutput,\n infer ToolEnvironment\n >\n ? {\n ToolConfigType: ToolConfig;\n ToolInputType: ToolInput;\n ToolOutputType: ToolOutput;\n ToolEnvironmentType: ToolEnvironment;\n }\n : never;\n\n/*\n * This workaround using a property is required because, when using generics with a base constraint,\n * TypeScript will always resolve the generic to the base constraint when trying to infer types later on.\n * By introducing a dummy property that uses the generic, TypeScript can correctly infer the actual types.\n */\ntype EnvironmentToolConfigOf<T> = T extends { _toolConfig: infer C }\n ? C\n : never;\ntype EnvironmentToolInputTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolInputType'];\ntype EnvironmentToolOutputTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolOutputType'];\ntype EnvironmentToolEnvironmentTypeOf<T> =\n EnvironmentToolGenerics<T>['ToolEnvironmentType'];\n\nexport type EnvironmentToolName = keyof typeof availableEnvironmentTools;\nexport const EnvironmentToolNames = Object.keys(\n availableEnvironmentTools,\n) as EnvironmentToolName[];\n\n/**\n * Creates an environment tool instance based on the provided name, execution environment, and configuration.\n *\n * @param toolName - The name identifying the type of environment tool to create.\n * @param environment - The execution environment to create the tool for.\n * @param config - The configuration object for the environment tool.\n * @returns An instance of the specified environment tool.\n */\nexport function createEnvironmentTool<T extends EnvironmentToolName>(\n toolName: T,\n environment: EnvironmentToolEnvironmentTypeOf<EnvironmentToolClasses[T]>,\n config?: EnvironmentToolConfigOf<EnvironmentToolClasses[T]>,\n): EnvironmentToolClasses[T] {\n // Extra safe-guard - should not be needed.\n if (!(toolName in availableEnvironmentTools)) {\n throw new Error(`Unsupported environment: ${toolName}`);\n }\n\n const EnvironmentToolClass = availableEnvironmentTools[toolName as T];\n\n return new EnvironmentToolClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n environment as any,\n config,\n ) as EnvironmentToolClasses[T];\n}\n\ntype ToolCreatorConfig = EnvironmentToolName extends infer T\n ? T extends EnvironmentToolName\n ? {\n toolName: T;\n toolConfig?: EnvironmentToolConfigOf<EnvironmentToolClasses[T]>;\n }\n : never\n : never;\n\nexport type ToolsDefinition =\n | Array<EnvironmentToolName | ToolCreatorConfig>\n | EnvironmentToolSafetyLevel;\n\ntype SanitizedToolsDefinition = ToolCreatorConfig[];\n\ntype ToolWithIO = EnvironmentToolName extends infer T\n ? T extends EnvironmentToolName\n ? Tool<\n EnvironmentToolInputTypeOf<EnvironmentToolClasses[T]>,\n EnvironmentToolOutputTypeOf<EnvironmentToolClasses[T]>\n >\n : never\n : never;\n\n/**\n * Creates a map of tools for the given environment.\n *\n * @param environment - The execution environment to create the tools for.\n * @param toolsDefinition - The names of the tools to create, or 'readonly', 'basic', or 'all' as a shortcut for groups of available tools.\n * @returns A record mapping tool names to their corresponding Tool instances.\n */\nexport function createToolsForEnvironment(\n environment: Environment,\n toolsDefinition: ToolsDefinition = 'all',\n): Record<string, ToolWithIO> {\n const sanitizedToolsDefinition = sanitizeToolsDefinition(toolsDefinition);\n\n const isCliEnvironment = isCommandLine(environment);\n\n const tools: Record<string, ToolWithIO> = {};\n for (const toolDefinition of sanitizedToolsDefinition) {\n const actualToolName = toolDefinition.toolName;\n\n // Manual check for CLI-only tools.\n if (!isCliEnvironment && cliOnlyTools.includes(actualToolName)) {\n throw new Error(\n `The \"${actualToolName}\" tool can only be used with command-line environments.`,\n );\n }\n\n const toolNameToUse =\n toolDefinition.toolConfig?.name || toolDefinition.toolName;\n let toolConfig: ToolCreatorConfig['toolConfig'];\n if (toolDefinition.toolConfig) {\n toolConfig = toolDefinition.toolConfig;\n }\n\n if (toolNameToUse in tools) {\n throw new Error(\n `Multiple tools named \"${toolNameToUse}\" are provided - make sure tool names are unique.`,\n );\n }\n\n tools[toolNameToUse] = createEnvironmentTool(\n actualToolName,\n environment,\n toolConfig,\n );\n }\n\n return tools;\n}\n\n/**\n * Creates a map of tools for the given environment, modifying tool names with the environment name to avoid conflicts.\n *\n * For example, if the environment name is \"env1\" and the tool is \"read_file\", the modified tool name will be \"read_file_in_env1\".\n *\n * @param environmentName - The name of the environment. Will be used in tool names to avoid conflicts.\n * @param environment - The execution environment to create the tools for.\n * @param toolsDefinition - The names of the tools to create, or 'readonly', 'basic', or 'all' as a shortcut for groups of available tools.\n * @returns A record mapping tool names to their corresponding Tool instances.\n */\nexport function createToolsForNamedEnvironment(\n environmentName: string,\n environment: Environment,\n toolsDefinition: ToolsDefinition = 'all',\n): Record<string, ToolWithIO> {\n const sanitizedToolsDefinition = sanitizeToolsDefinition(toolsDefinition);\n\n const toolsDefinitionWithEnvironmentName = sanitizedToolsDefinition.map(\n (toolDefinition): ToolCreatorConfig => {\n if (toolDefinition.toolConfig) {\n const toolNameToUse =\n toolDefinition.toolConfig.name || toolDefinition.toolName;\n return {\n toolName: toolDefinition.toolName,\n toolConfig: {\n ...toolDefinition.toolConfig,\n name: `${toolNameToUse}_in_${environmentName}`,\n },\n };\n }\n return {\n toolName: toolDefinition.toolName,\n toolConfig: {\n name: `${toolDefinition.toolName}_in_${environmentName}`,\n },\n };\n },\n );\n\n return createToolsForEnvironment(\n environment,\n toolsDefinitionWithEnvironmentName,\n );\n}\n\n/**\n * Sanitizes a tools definition into a consistent format.\n *\n * @param toolsDefinition - The tools definition to sanitize.\n * @returns A sanitized array of tool definitions.\n */\nfunction sanitizeToolsDefinition(\n toolsDefinition: ToolsDefinition,\n): SanitizedToolsDefinition {\n if (typeof toolsDefinition === 'string') {\n switch (toolsDefinition) {\n case 'readonly':\n toolsDefinition = readonlyTools;\n break;\n case 'basic':\n toolsDefinition = EnvironmentToolNames.filter(\n (toolName) => !dangerousTools.includes(toolName),\n );\n break;\n default:\n toolsDefinition = [...EnvironmentToolNames];\n }\n }\n\n return toolsDefinition.map((tool) => {\n if (typeof tool === 'string') {\n return { toolName: tool };\n }\n return tool;\n });\n}\n","/**\n * Truncates a string based on line count or character limit.\n *\n * For multiline strings (ignoring final blank lines), limits to 5 lines and appends \"(x more lines)\".\n * For single-line strings, limits to 300 characters and appends \"(x more characters)\".\n *\n * @param str - The string to truncate.\n * @returns The truncated string with appropriate suffix if truncation occurred.\n */\nexport function truncateString(str: string): string {\n // Split into lines and remove trailing blank lines\n const lines = str.split('\\n');\n while (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const isMultiline = lines.length > 1;\n\n if (isMultiline) {\n // Multiline: limit to 5 lines\n if (lines.length > 5) {\n const truncatedLines = lines.slice(0, 5).join('\\n');\n const moreLines = lines.length - 5;\n const lineSuffix = moreLines === 1 ? 'line' : 'lines';\n return `${truncatedLines}\\n...(${moreLines} more ${lineSuffix})`;\n }\n return lines.join('\\n');\n }\n\n // Single-line: limit to 300 characters\n const singleLine = lines[0] || '';\n if (singleLine.length > 300) {\n const moreChars = singleLine.length - 300;\n return `${singleLine.slice(0, 300)}...(${moreChars} more characters)`;\n }\n\n return singleLine;\n}\n\n/**\n * Recursively truncates all string values in an object using truncateString.\n *\n * Handles nested objects and arrays by recursively processing their elements.\n * For objects, iterates through all key-value pairs. For arrays, processes each element.\n *\n * @param obj - The object to truncate.\n * @returns A new object with all strings truncated.\n */\nexport function truncateObject(\n obj: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string') {\n result[key] = truncateString(value);\n } else if (Array.isArray(value)) {\n result[key] = value.map((item) => {\n if (typeof item === 'string') {\n return truncateString(item);\n }\n if (typeof item === 'object' && item !== null) {\n return truncateObject(item as Record<string, unknown>);\n }\n return item;\n });\n } else if (typeof value === 'object' && value !== null) {\n result[key] = truncateObject(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n","import type { StepResult, Tool } from 'ai';\nimport { truncateObject, truncateString } from './truncate';\n\n/**\n * Returns a formatted log string for a given step result from an AI agent.\n *\n * @param stepResult - The step result to format.\n * @returns A formatted string representing the step log.\n */\nexport function getStepLog(\n stepResult: StepResult<NoInfer<Record<string, Tool>>>,\n): string {\n const { content } = stepResult;\n\n let logEntry = '';\n content.forEach((part) => {\n logEntry += part.type;\n if ('toolName' in part && 'toolCallId' in part && part.toolCallId) {\n logEntry += ` (${part.toolName}, ID ${part.toolCallId})`;\n } else if ('toolName' in part) {\n logEntry += ` (${part.toolName})`;\n }\n logEntry += ': ';\n if (part.type === 'tool-call' && 'input' in part) {\n logEntry +=\n typeof part.input === 'string'\n ? truncateString(part.input)\n : part.input === null || part.input === undefined\n ? String(part.input)\n : JSON.stringify(\n truncateObject(part.input as Record<string, unknown>),\n );\n } else if (part.type === 'tool-result' && 'output' in part) {\n logEntry +=\n typeof part.output === 'string'\n ? truncateString(part.output)\n : part.output === null || part.output === undefined\n ? String(part.output)\n : JSON.stringify(\n truncateObject(part.output as Record<string, unknown>),\n );\n } else if (part.type === 'tool-error' && 'error' in part) {\n logEntry +=\n typeof part.error === 'object' &&\n part.error !== null &&\n 'message' in part.error\n ? (part.error.message as string)\n : String(part.error);\n } else if (part.type === 'text' && 'text' in part) {\n logEntry += truncateString(part.text);\n }\n logEntry += '\\n';\n });\n\n return logEntry.trim();\n}\n","import type { FilesystemEnvironmentBase } from '@ai-code-agents/environment-utils';\nimport {\n DockerEnvironment,\n DockerEnvironmentName,\n} from './environments/docker-environment';\nimport {\n MockFilesystemEnvironment,\n MockFilesystemEnvironmentName,\n} from './environments/mock-filesystem-environment';\nimport {\n NodeFilesystemEnvironment,\n NodeFilesystemEnvironmentName,\n} from './environments/node-filesystem-environment';\nimport {\n UnsafeLocalEnvironment,\n UnsafeLocalEnvironmentName,\n} from './environments/unsafe-local-environment';\n\nconst availableEnvironments = {\n [UnsafeLocalEnvironmentName]: UnsafeLocalEnvironment,\n [DockerEnvironmentName]: DockerEnvironment,\n [MockFilesystemEnvironmentName]: MockFilesystemEnvironment,\n [NodeFilesystemEnvironmentName]: NodeFilesystemEnvironment,\n};\n\ntype EnvironmentClasses = {\n [UnsafeLocalEnvironmentName]: UnsafeLocalEnvironment;\n [DockerEnvironmentName]: DockerEnvironment;\n [MockFilesystemEnvironmentName]: MockFilesystemEnvironment;\n [NodeFilesystemEnvironmentName]: NodeFilesystemEnvironment;\n};\n\ntype EnvironmentConfigOf<T> =\n T extends FilesystemEnvironmentBase<infer X> ? X : never;\n\nexport type EnvironmentName = keyof typeof availableEnvironments;\nexport const EnvironmentNames = Object.keys(\n availableEnvironments,\n) as EnvironmentName[];\n\n/**\n * Creates an environment instance based on the provided name and configuration.\n *\n * @param environmentName - The name identifying the type of environment to create.\n * @param config - The configuration object for the environment.\n * @returns An instance of the specified environment.\n */\nexport function createEnvironment<T extends EnvironmentName>(\n environmentName: T,\n config: EnvironmentConfigOf<EnvironmentClasses[T]>,\n): EnvironmentClasses[T] {\n // Extra safe-guard - should not be needed.\n if (!(environmentName in availableEnvironments)) {\n throw new Error(`Unsupported environment: ${environmentName}`);\n }\n\n const EnvironmentClass = availableEnvironments[environmentName as T];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new EnvironmentClass(config as any) as EnvironmentClasses[T];\n}\n"],"mapp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,GAAG,cAAc,GAAG,kBAAkB;AAAA,IAChD;AAEA,WAAO,CAAC,GAAG,cAAc,kBAAkB;AAAA,EAC7C;AAEA,MAAI,MAAM,QAAQ,kBAAkB,GAAG;AACrC,WAAO,CAAC,cAAc,GAAG,kBAAkB;AAAA,EAC7C;AAEA,SAAO,CAAC,cAAc,kBAAkB;AAC1C;AAWA,SAAS,wBACP,kBAKA,wBACoD;AACpD,MAAI,kBAAkB;AACpB,QAAI,MAAM,QAAQ,gBAAgB,GAAG;AACnC,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,UACE,MAAM;AAAA,UACN,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO,qBAAqB,UAAU;AACxC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS,GAAG,iBAAiB,QAAQ,QAAQ,CAAC;AAAA;AAAA,EAAO,sBAAsB;AAAA,MAC7E;AAAA,IACF;AACA,WAAO,GAAG,iBAAiB,QAAQ,CAAC;AAAA;AAAA,EAAO,sBAAsB;AAAA,EACnE;AACA,SAAO;AACT;;;AKnSA,IAAM,wBAAwB;AAAA,EAC5B,CAAC,0BAA0B,GAAG;AAAA,EAC9B,CAAC,qBAAqB,GAAG;AAAA,EACzB,CAAC,6BAA6B,GAAG;AAAA,EACjC,CAAC,6BAA6B,GAAG;AACnC;AAaO,IAAM,mBAAmB,OAAO;AAAA,EACrC;AACF;AASO,SAAS,kBACd,iBACA,QACuB;AAEvB,MAAI,EAAE,mBAAmB,wBAAwB;AAC/C,UAAM,IAAI,MAAM,4BAA4B,eAAe,EAAE;AAAA,EAC/D;AAEA,QAAM,mBAAmB,sBAAsB,eAAoB;AAGnE,SAAO,IAAI,iBAAiB,MAAa;AAC3C;","names":["import_environment_utils","path","import_node_path","import_environment_utils","path","fs","import_node_child_process","import_environment_utils","import_environment_utils","import_zod","import_environment_utils","import_zod","import_environment_utils","path","import_zod","import_environment_utils","import_node_path","import_environment_utils","path","path","escapedPath","import_zod","import_environment_utils","path","import_zod","import_environment_utils","import_zod","import_environment_utils","import_zod","import_environment_utils","import_zod","import_environment_utils","import_node_path","path","import_zod","import_environment_utils","formatModelResponse","path","import_zod","import_environment_utils","import_zod","import_environment_utils","import_zod","import_environment_utils","import_environment_utils"]}
|