From 8662b73adb2be39f4dfcd5d040d2e284ecd8f3ae Mon Sep 17 00:00:00 2001 From: Juergen Kunz Date: Mon, 15 Dec 2025 14:49:26 +0000 Subject: [PATCH] update --- readme.md | 182 +++++++++++++++--- ts/smartagent.classes.driveragent.ts | 39 +++- ts/smartagent.classes.dualagent.ts | 29 ++- ts/smartagent.interfaces.ts | 6 + ts/smartagent.tools.filesystem.ts | 276 ++++++++++++++++++++++++++- 5 files changed, 489 insertions(+), 43 deletions(-) diff --git a/readme.md b/readme.md index d9cd610..9349b8a 100644 --- a/readme.md +++ b/readme.md @@ -1,21 +1,31 @@ # @push.rocks/smartagent -A dual-agent agentic framework with Driver and Guardian agents for safe, policy-controlled AI task execution. + +A dual-agent agentic framework with **Driver** and **Guardian** agents for safe, policy-controlled AI task execution. πŸ€–πŸ›‘οΈ ## Install + ```bash npm install @push.rocks/smartagent # or pnpm install @push.rocks/smartagent ``` +## Issue Reporting and Security + +For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly. + ## Overview -SmartAgent implements a dual-agent architecture: +SmartAgent implements a **dual-agent architecture** where AI safety isn't just an afterthoughtβ€”it's baked into the core design: -- **Driver Agent**: Executes tasks, reasons about goals, and proposes tool calls -- **Guardian Agent**: Evaluates tool call proposals against a policy prompt, approving or rejecting with feedback +- **🎯 Driver Agent**: The executor. Reasons about goals, plans steps, and proposes tool calls +- **πŸ›‘οΈ Guardian Agent**: The gatekeeper. Evaluates every tool call against your policy, approving or rejecting with feedback -This design ensures safe tool use through AI-based policy evaluation rather than rigid programmatic rules. +This design ensures safe tool use through **AI-based policy evaluation** rather than rigid programmatic rules. The Guardian can understand context, nuance, and intentβ€”catching dangerous operations that simple regex or allowlists would miss. + +### Why Dual-Agent? + +Traditional AI agents have a fundamental problem: they're given tools and expected to use them responsibly. SmartAgent adds a second AI specifically trained to evaluate whether each action is safe and appropriate. Think of it as separation of concerns, but for AI safety. ## Architecture @@ -89,8 +99,11 @@ await orchestrator.stop(); ## Standard Tools -### FilesystemTool -File and directory operations using `@push.rocks/smartfs`. +SmartAgent comes with five battle-tested tools out of the box: + +### πŸ—‚οΈ FilesystemTool + +File and directory operations powered by `@push.rocks/smartfs`. **Actions**: `read`, `write`, `append`, `list`, `delete`, `exists`, `stat`, `copy`, `move`, `mkdir` @@ -104,7 +117,15 @@ File and directory operations using `@push.rocks/smartfs`. ``` -### HttpTool +**Scoped Filesystem**: Lock file operations to a specific directory: + +```typescript +// Only allow access within a specific directory +orchestrator.registerScopedFilesystemTool('/home/user/workspace'); +``` + +### 🌐 HttpTool + HTTP requests using `@push.rocks/smartrequest`. **Actions**: `get`, `post`, `put`, `patch`, `delete` @@ -113,13 +134,14 @@ HTTP requests using `@push.rocks/smartrequest`. http get - {"url": "https://api.example.com/data"} + {"url": "https://api.example.com/data", "headers": {"Authorization": "Bearer token"}} Fetching data from the API endpoint ``` -### ShellTool -Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` (no shell injection). +### πŸ’» ShellTool + +Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` (no shell injection possible). **Actions**: `execute`, `which` @@ -132,7 +154,10 @@ Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` ( ``` -### BrowserTool +> πŸ”’ **Security Note**: The shell tool uses `execSpawn` with `shell: false`, meaning command and arguments are passed separately. This makes shell injection attacks impossible. + +### 🌍 BrowserTool + Web page interaction using `@push.rocks/smartbrowser` (Puppeteer-based). **Actions**: `screenshot`, `pdf`, `evaluate`, `getPageContent` @@ -146,17 +171,18 @@ Web page interaction using `@push.rocks/smartbrowser` (Puppeteer-based). ``` -### DenoTool -Execute TypeScript/JavaScript code in a sandboxed Deno environment using `@push.rocks/smartdeno`. +### πŸ¦• DenoTool + +Execute TypeScript/JavaScript code in a **sandboxed Deno environment** with fine-grained permission control. **Actions**: `execute`, `executeWithResult` **Permissions**: `all`, `env`, `ffi`, `hrtime`, `net`, `read`, `run`, `sys`, `write` -By default, code runs fully sandboxed with no permissions. Permissions must be explicitly requested. +By default, code runs **fully sandboxed with no permissions**. Permissions must be explicitly requested and are subject to Guardian approval. ```typescript -// Simple code execution +// Simple code execution (sandboxed, no permissions) deno execute @@ -188,7 +214,10 @@ By default, code runs fully sandboxed with no permissions. Permissions must be e ## Guardian Policy Examples -### Strict Security Policy +The Guardian's power comes from your policy. Here are battle-tested examples: + +### πŸ” Strict Security Policy + ```typescript const securityPolicy = ` SECURITY POLICY: @@ -204,7 +233,8 @@ When rejecting, always explain: `; ``` -### Development Environment Policy +### πŸ› οΈ Development Environment Policy + ```typescript const devPolicy = ` DEVELOPMENT POLICY: @@ -221,7 +251,8 @@ Always verify: `; ``` -### Deno Code Execution Policy +### πŸ¦• Deno Code Execution Policy + ```typescript const denoPolicy = ` DENO CODE EXECUTION POLICY: @@ -253,6 +284,9 @@ interface IDualAgentOptions { groqToken?: string; xaiToken?: string; + // Use existing SmartAi instance (optional - avoids duplicate providers) + smartAiInstance?: SmartAi; + // Provider selection defaultProvider?: TProvider; // For both Driver and Guardian guardianProvider?: TProvider; // Optional: separate provider for Guardian @@ -278,6 +312,14 @@ interface IDualAgentRunResult { history: IAgentMessage[]; // Full conversation history status: TDualAgentRunStatus; // 'completed' | 'max_iterations_reached' | etc. } + +type TDualAgentRunStatus = + | 'completed' + | 'in_progress' + | 'max_iterations_reached' + | 'max_rejections_reached' + | 'clarification_needed' + | 'error'; ``` ## Custom Tools @@ -306,10 +348,12 @@ class MyCustomTool extends BaseToolWrapper { ]; public async initialize(): Promise { + // Setup your tool (called when orchestrator.start() runs) this.isInitialized = true; } public async cleanup(): Promise { + // Cleanup resources (called when orchestrator.stop() runs) this.isInitialized = false; } @@ -327,6 +371,7 @@ class MyCustomTool extends BaseToolWrapper { return { success: false, error: 'Unknown action' }; } + // Human-readable summary for Guardian evaluation public getCallSummary(action: string, params: Record): string { return `Custom action "${action}" with input "${params.input}"`; } @@ -336,32 +381,111 @@ class MyCustomTool extends BaseToolWrapper { orchestrator.registerTool(new MyCustomTool()); ``` +## Reusing SmartAi Instances + +If you already have a `@push.rocks/smartai` instance, you can share it: + +```typescript +import { SmartAi } from '@push.rocks/smartai'; +import { DualAgentOrchestrator } from '@push.rocks/smartagent'; + +const smartai = new SmartAi({ openaiToken: 'sk-...' }); +await smartai.start(); + +const orchestrator = new DualAgentOrchestrator({ + smartAiInstance: smartai, // Reuse existing instance + guardianPolicyPrompt: '...', +}); + +await orchestrator.start(); +// ... use orchestrator ... +await orchestrator.stop(); + +// SmartAi instance lifecycle is managed separately +await smartai.stop(); +``` + ## Supported Providers +SmartAgent supports all providers from `@push.rocks/smartai`: + | Provider | Driver | Guardian | |----------|:------:|:--------:| -| OpenAI | Yes | Yes | -| Anthropic | Yes | Yes | -| Perplexity | Yes | Yes | -| Groq | Yes | Yes | -| Ollama | Yes | Yes | -| XAI | Yes | Yes | +| OpenAI | βœ… | βœ… | +| Anthropic | βœ… | βœ… | +| Perplexity | βœ… | βœ… | +| Groq | βœ… | βœ… | +| Ollama | βœ… | βœ… | +| XAI | βœ… | βœ… | +| Exo | βœ… | βœ… | + +**πŸ’‘ Pro tip**: Use a faster/cheaper model for Guardian (like Groq) and a more capable model for Driver: + +```typescript +const orchestrator = new DualAgentOrchestrator({ + openaiToken: 'sk-...', + groqToken: 'gsk-...', + defaultProvider: 'openai', // Driver uses OpenAI + guardianProvider: 'groq', // Guardian uses Groq (faster, cheaper) + guardianPolicyPrompt: '...', +}); +``` + +## API Reference + +### DualAgentOrchestrator + +| Method | Description | +|--------|-------------| +| `start()` | Initialize all tools and AI providers | +| `stop()` | Cleanup all tools and resources | +| `run(task: string)` | Execute a task and return result | +| `continueTask(input: string)` | Continue a task with user input | +| `registerTool(tool)` | Register a custom tool | +| `registerStandardTools()` | Register all built-in tools | +| `registerScopedFilesystemTool(basePath)` | Register filesystem tool with path restriction | +| `setGuardianPolicy(policy)` | Update Guardian policy at runtime | +| `getHistory()` | Get conversation history | +| `getToolNames()` | Get list of registered tool names | +| `isActive()` | Check if orchestrator is running | + +### Exports + +```typescript +// Main classes +export { DualAgentOrchestrator } from '@push.rocks/smartagent'; +export { DriverAgent } from '@push.rocks/smartagent'; +export { GuardianAgent } from '@push.rocks/smartagent'; + +// Tools +export { BaseToolWrapper } from '@push.rocks/smartagent'; +export { FilesystemTool } from '@push.rocks/smartagent'; +export { HttpTool } from '@push.rocks/smartagent'; +export { ShellTool } from '@push.rocks/smartagent'; +export { BrowserTool } from '@push.rocks/smartagent'; +export { DenoTool } from '@push.rocks/smartagent'; + +// Types and interfaces +export * from '@push.rocks/smartagent'; // All interfaces +``` ## License and Legal Information -This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. +This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. ### Trademarks -This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. +This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein. + +Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar. ### Company Information Task Venture Capital GmbH -Registered at District court Bremen HRB 35230 HB, Germany +Registered at District Court Bremen HRB 35230 HB, Germany -For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. +For any legal inquiries or further information, please contact us via email at hello@task.vc. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. diff --git a/ts/smartagent.classes.driveragent.ts b/ts/smartagent.classes.driveragent.ts index 5c6c5cf..d51a7dc 100644 --- a/ts/smartagent.classes.driveragent.ts +++ b/ts/smartagent.classes.driveragent.ts @@ -2,6 +2,16 @@ import * as plugins from './plugins.js'; import * as interfaces from './smartagent.interfaces.js'; import type { BaseToolWrapper } from './smartagent.tools.base.js'; +/** + * Options for configuring the DriverAgent + */ +export interface IDriverAgentOptions { + /** Custom system message for the driver */ + systemMessage?: string; + /** Maximum history messages to pass to API (default: 20). Set to 0 for unlimited. */ + maxHistoryMessages?: number; +} + /** * DriverAgent - Executes tasks by reasoning and proposing tool calls * Works in conjunction with GuardianAgent for approval @@ -9,15 +19,24 @@ import type { BaseToolWrapper } from './smartagent.tools.base.js'; export class DriverAgent { private provider: plugins.smartai.MultiModalModel; private systemMessage: string; + private maxHistoryMessages: number; private messageHistory: plugins.smartai.ChatMessage[] = []; private tools: Map = new Map(); constructor( provider: plugins.smartai.MultiModalModel, - systemMessage?: string + options?: IDriverAgentOptions | string ) { this.provider = provider; - this.systemMessage = systemMessage || this.getDefaultSystemMessage(); + + // Support both legacy string systemMessage and new options object + if (typeof options === 'string') { + this.systemMessage = options || this.getDefaultSystemMessage(); + this.maxHistoryMessages = 20; + } else { + this.systemMessage = options?.systemMessage || this.getDefaultSystemMessage(); + this.maxHistoryMessages = options?.maxHistoryMessages ?? 20; + } } /** @@ -105,8 +124,20 @@ export class DriverAgent { fullSystemMessage = this.getNoToolsSystemMessage(); } - // Get response from provider (pass all but last user message as history) - const historyForChat = this.messageHistory.slice(0, -1); + // Get response from provider with history windowing + // Keep original task and most recent messages to avoid token explosion + let historyForChat: plugins.smartai.ChatMessage[]; + const fullHistory = this.messageHistory.slice(0, -1); // Exclude the just-added message + + if (this.maxHistoryMessages > 0 && fullHistory.length > this.maxHistoryMessages) { + // Keep the original task (first message) and most recent messages + historyForChat = [ + fullHistory[0], // Original task + ...fullHistory.slice(-(this.maxHistoryMessages - 1)), // Recent messages + ]; + } else { + historyForChat = fullHistory; + } const response = await this.provider.chat({ systemMessage: fullSystemMessage, diff --git a/ts/smartagent.classes.dualagent.ts b/ts/smartagent.classes.dualagent.ts index a41f5e5..b121648 100644 --- a/ts/smartagent.classes.dualagent.ts +++ b/ts/smartagent.classes.dualagent.ts @@ -30,6 +30,8 @@ export class DualAgentOrchestrator { maxIterations: 20, maxConsecutiveRejections: 3, defaultProvider: 'openai', + maxResultChars: 15000, + maxHistoryMessages: 20, ...options, }; @@ -260,10 +262,29 @@ export class DualAgentOrchestrator { try { const result = await tool.execute(proposal.action, proposal.params); - // Send result to driver - const resultMessage = result.success - ? `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${JSON.stringify(result.result, null, 2)}` - : `TOOL ERROR (${proposal.toolName}.${proposal.action}):\n${result.error}`; + // Build result message (prefer summary if provided, otherwise stringify result) + let resultMessage: string; + if (result.success) { + if (result.summary) { + // Use tool-provided summary + resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${result.summary}`; + } else { + // Stringify and potentially truncate + const resultStr = JSON.stringify(result.result, null, 2); + const maxChars = this.options.maxResultChars ?? 15000; + + if (maxChars > 0 && resultStr.length > maxChars) { + // Truncate the result + const truncated = resultStr.substring(0, maxChars); + const omittedTokens = Math.round((resultStr.length - maxChars) / 4); + resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${truncated}\n\n[... output truncated, ~${omittedTokens} tokens omitted. Use more specific parameters to reduce output size.]`; + } else { + resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${resultStr}`; + } + } + } else { + resultMessage = `TOOL ERROR (${proposal.toolName}.${proposal.action}):\n${result.error}`; + } this.conversationHistory.push({ role: 'system', diff --git a/ts/smartagent.interfaces.ts b/ts/smartagent.interfaces.ts index c705573..6a32f5e 100644 --- a/ts/smartagent.interfaces.ts +++ b/ts/smartagent.interfaces.ts @@ -26,6 +26,10 @@ export interface IDualAgentOptions extends plugins.smartai.ISmartAiOptions { maxConsecutiveRejections?: number; /** Enable verbose logging */ verbose?: boolean; + /** Maximum characters for tool result output before truncation (default: 15000). Set to 0 to disable. */ + maxResultChars?: number; + /** Maximum history messages to pass to API (default: 20). Set to 0 for unlimited. */ + maxHistoryMessages?: number; } // ================================ @@ -84,6 +88,8 @@ export interface IToolExecutionResult { success: boolean; result?: unknown; error?: string; + /** Optional human-readable summary for history (if provided, used instead of full result) */ + summary?: string; } /** diff --git a/ts/smartagent.tools.filesystem.ts b/ts/smartagent.tools.filesystem.ts index a286461..a381684 100644 --- a/ts/smartagent.tools.filesystem.ts +++ b/ts/smartagent.tools.filesystem.ts @@ -46,17 +46,25 @@ export class FilesystemTool extends BaseToolWrapper { public actions: interfaces.IToolAction[] = [ { name: 'read', - description: 'Read the contents of a file', + description: 'Read file contents (full or specific line range)', parameters: { type: 'object', properties: { - path: { type: 'string', description: 'Absolute path to the file' }, + path: { type: 'string', description: 'Path to the file' }, encoding: { type: 'string', enum: ['utf8', 'binary', 'base64'], default: 'utf8', description: 'File encoding', }, + startLine: { + type: 'number', + description: 'First line to read (1-indexed, inclusive). If omitted, reads from beginning.', + }, + endLine: { + type: 'number', + description: 'Last line to read (1-indexed, inclusive). If omitted, reads to end.', + }, }, required: ['path'], }, @@ -182,6 +190,55 @@ export class FilesystemTool extends BaseToolWrapper { required: ['path'], }, }, + { + name: 'tree', + description: 'Show directory structure as a tree (no file contents)', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Root directory path' }, + maxDepth: { + type: 'number', + default: 3, + description: 'Maximum depth to traverse (default: 3)', + }, + filter: { + type: 'string', + description: 'Glob pattern to filter files (e.g., "*.ts")', + }, + showSizes: { + type: 'boolean', + default: false, + description: 'Include file sizes in output', + }, + format: { + type: 'string', + enum: ['string', 'json'], + default: 'string', + description: 'Output format: "string" for human-readable tree, "json" for structured array', + }, + }, + required: ['path'], + }, + }, + { + name: 'glob', + description: 'Find files matching a glob pattern', + parameters: { + type: 'object', + properties: { + pattern: { + type: 'string', + description: 'Glob pattern (e.g., "**/*.ts", "src/**/*.js")', + }, + path: { + type: 'string', + description: 'Base path to search from (defaults to current directory)', + }, + }, + required: ['pattern'], + }, + }, ]; private smartfs!: plugins.smartfs.SmartFs; @@ -207,16 +264,61 @@ export class FilesystemTool extends BaseToolWrapper { case 'read': { const validatedPath = this.validatePath(params.path as string); const encoding = (params.encoding as string) || 'utf8'; - const content = await this.smartfs + const startLine = params.startLine as number | undefined; + const endLine = params.endLine as number | undefined; + + const fullContent = await this.smartfs .file(validatedPath) .encoding(encoding as 'utf8' | 'binary' | 'base64') .read(); + + const contentStr = fullContent.toString(); + const lines = contentStr.split('\n'); + const totalLines = lines.length; + + // Apply line range if specified + let resultContent: string; + let resultStartLine = 1; + let resultEndLine = totalLines; + + if (startLine !== undefined || endLine !== undefined) { + const start = Math.max(1, startLine ?? 1); + const end = Math.min(totalLines, endLine ?? totalLines); + resultStartLine = start; + resultEndLine = end; + + // Convert to 0-indexed for array slicing + const selectedLines = lines.slice(start - 1, end); + + // Add line numbers to output for context + resultContent = selectedLines + .map((line, idx) => `${String(start + idx).padStart(5)}β”‚ ${line}`) + .join('\n'); + } else { + // No range specified - return full content but warn if large + const MAX_LINES_WITHOUT_RANGE = 500; + if (totalLines > MAX_LINES_WITHOUT_RANGE) { + // Return first portion with warning + const selectedLines = lines.slice(0, MAX_LINES_WITHOUT_RANGE); + resultContent = selectedLines + .map((line, idx) => `${String(idx + 1).padStart(5)}β”‚ ${line}`) + .join('\n'); + resultContent += `\n\n[... ${totalLines - MAX_LINES_WITHOUT_RANGE} more lines. Use startLine/endLine to read specific ranges.]`; + resultEndLine = MAX_LINES_WITHOUT_RANGE; + } else { + resultContent = contentStr; + } + } + return { success: true, result: { path: params.path, - content: content.toString(), + content: resultContent, encoding, + totalLines, + startLine: resultStartLine, + endLine: resultEndLine, }, }; } @@ -364,6 +466,158 @@ export class FilesystemTool extends BaseToolWrapper { }; } + case 'tree': { + const validatedPath = this.validatePath(params.path as string); + const maxDepth = (params.maxDepth as number) ?? 3; + const filter = params.filter as string | undefined; + const showSizes = (params.showSizes as boolean) ?? false; + const format = (params.format as 'string' | 'json') ?? 'string'; + + // Collect all entries recursively up to maxDepth + interface ITreeEntry { + path: string; + relativePath: string; + isDir: boolean; + depth: number; + size?: number; + } + + const entries: ITreeEntry[] = []; + + const collectEntries = async (dirPath: string, depth: number, relativePath: string) => { + if (depth > maxDepth) return; + + let dir = this.smartfs.directory(dirPath); + if (filter) { + dir = dir.filter(filter); + } + const items = await dir.list(); + + for (const item of items) { + const itemPath = plugins.path.join(dirPath, item); + const itemRelPath = relativePath ? `${relativePath}/${item}` : item; + + try { + const stats = await this.smartfs.file(itemPath).stat(); + const isDir = stats.isDirectory; + + const entry: ITreeEntry = { + path: itemPath, + relativePath: itemRelPath, + isDir, + depth, + }; + + if (showSizes && !isDir) { + entry.size = stats.size; + } + + entries.push(entry); + + // Recurse into directories + if (isDir && depth < maxDepth) { + await collectEntries(itemPath, depth + 1, itemRelPath); + } + } catch { + // Skip items we can't stat + } + } + }; + + await collectEntries(validatedPath, 0, ''); + + // Sort entries by path for consistent output + entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath)); + + if (format === 'json') { + return { + success: true, + result: { + path: params.path, + entries: entries.map((e) => ({ + path: e.relativePath, + isDir: e.isDir, + depth: e.depth, + ...(e.size !== undefined ? { size: e.size } : {}), + })), + count: entries.length, + }, + }; + } + + // Format as string tree + const formatSize = (bytes: number): string => { + if (bytes < 1024) return `${bytes}B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; + }; + + // Build tree string with proper indentation + let treeStr = `${params.path}/\n`; + const pathParts = new Map(); // Track which paths are last in their parent + + // Group by parent to determine last child + const parentChildCount = new Map(); + const parentCurrentChild = new Map(); + + for (const entry of entries) { + const parentPath = entry.relativePath.includes('/') + ? entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/')) + : ''; + parentChildCount.set(parentPath, (parentChildCount.get(parentPath) || 0) + 1); + } + + for (const entry of entries) { + const parentPath = entry.relativePath.includes('/') + ? entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/')) + : ''; + parentCurrentChild.set(parentPath, (parentCurrentChild.get(parentPath) || 0) + 1); + const isLast = parentCurrentChild.get(parentPath) === parentChildCount.get(parentPath); + + // Build prefix based on depth + let prefix = ''; + const parts = entry.relativePath.split('/'); + for (let i = 0; i < parts.length - 1; i++) { + prefix += 'β”‚ '; + } + prefix += isLast ? '└── ' : 'β”œβ”€β”€ '; + + const name = parts[parts.length - 1]; + const suffix = entry.isDir ? '/' : ''; + const sizeStr = showSizes && entry.size !== undefined ? ` (${formatSize(entry.size)})` : ''; + + treeStr += `${prefix}${name}${suffix}${sizeStr}\n`; + } + + return { + success: true, + result: { + path: params.path, + tree: treeStr, + count: entries.length, + }, + }; + } + + case 'glob': { + const pattern = params.pattern as string; + const basePath = params.path ? this.validatePath(params.path as string) : (this.basePath || process.cwd()); + + // Use smartfs to list with filter + const dir = this.smartfs.directory(basePath).recursive().filter(pattern); + const matches = await dir.list(); + + return { + success: true, + result: { + pattern, + basePath, + matches, + count: matches.length, + }, + }; + } + default: return { success: false, @@ -380,8 +634,12 @@ export class FilesystemTool extends BaseToolWrapper { public getCallSummary(action: string, params: Record): string { switch (action) { - case 'read': - return `Read file "${params.path}" with encoding ${params.encoding || 'utf8'}`; + case 'read': { + const lineRange = params.startLine || params.endLine + ? ` lines ${params.startLine || 1}-${params.endLine || 'end'}` + : ''; + return `Read file "${params.path}"${lineRange}`; + } case 'write': { const content = params.content as string; @@ -416,6 +674,12 @@ export class FilesystemTool extends BaseToolWrapper { case 'mkdir': return `Create directory "${params.path}"${params.recursive !== false ? ' (with parents)' : ''}`; + case 'tree': + return `Show tree of "${params.path}" (depth: ${params.maxDepth ?? 3}, format: ${params.format ?? 'string'})`; + + case 'glob': + return `Find files matching "${params.pattern}"${params.path ? ` in "${params.path}"` : ''}`; + default: return `Unknown action: ${action}`; }