From f7b2d754e9566a4f19961f5365a754f97eacdd3a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 8 Dec 2025 15:13:34 -0600 Subject: [PATCH] Tool result refactor (return an object instead of a string) --- src/components/Shakespeare/ChatPane.tsx | 4 +- src/components/Terminal.tsx | 4 +- src/lib/SessionManager.ts | 24 ++++-- src/lib/tools/BuildProjectTool.test.ts | 12 +-- src/lib/tools/BuildProjectTool.ts | 8 +- src/lib/tools/ConfigureImageGenerationTool.ts | 8 +- src/lib/tools/DeployProjectTool.ts | 8 +- src/lib/tools/GenerateImageTool.test.ts | 6 +- src/lib/tools/GenerateImageTool.ts | 6 +- src/lib/tools/GitCommitTool.test.ts | 24 +++--- src/lib/tools/GitCommitTool.ts | 8 +- src/lib/tools/MCPTool.ts | 7 +- src/lib/tools/NostrFetchEventTool.ts | 16 ++-- src/lib/tools/NostrGenerateKindTool.ts | 8 +- src/lib/tools/NostrPublishEventsTool.test.ts | 14 ++-- src/lib/tools/NostrPublishEventsTool.ts | 6 +- src/lib/tools/NostrReadKindTool.ts | 6 +- src/lib/tools/NostrReadNipTool.ts | 6 +- src/lib/tools/NostrReadNipsIndexTool.ts | 6 +- src/lib/tools/NostrReadProtocolTool.ts | 6 +- src/lib/tools/NostrReadTagTool.ts | 6 +- src/lib/tools/NpmAddPackageTool.test.ts | 26 +++--- src/lib/tools/NpmAddPackageTool.ts | 12 +-- src/lib/tools/NpmRemovePackageTool.test.ts | 16 ++-- src/lib/tools/NpmRemovePackageTool.ts | 10 ++- src/lib/tools/ReadConsoleMessagesTool.test.ts | 50 +++++------ src/lib/tools/ReadConsoleMessagesTool.ts | 10 ++- src/lib/tools/ReadWebpageTool.test.ts | 30 +++---- src/lib/tools/ReadWebpageTool.ts | 6 +- src/lib/tools/ShellTool.test.ts | 74 ++++++++-------- src/lib/tools/ShellTool.ts | 17 ++-- src/lib/tools/SkillTool.ts | 10 ++- .../tools/TextEditorStrReplaceTool.test.ts | 6 +- src/lib/tools/TextEditorStrReplaceTool.ts | 6 +- src/lib/tools/TextEditorViewTool.test.ts | 84 +++++++++---------- src/lib/tools/TextEditorViewTool.ts | 14 ++-- src/lib/tools/TextEditorWriteTool.test.ts | 4 +- src/lib/tools/TextEditorWriteTool.ts | 6 +- src/lib/tools/Tool.ts | 7 +- src/lib/tools/ViewAvailableModelsTool.ts | 10 +-- 40 files changed, 315 insertions(+), 276 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 41ba757e..8ee21fd2 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -374,9 +374,11 @@ export const ChatPane = forwardRef(({ ] }); + const result = await tool.execute({ filter: 'error' }); + await addMessage({ role: 'tool', - content: await tool.execute({ filter: 'error' }), + content: result.content, tool_call_id: toolCallId, }); diff --git a/src/components/Terminal.tsx b/src/components/Terminal.tsx index a7934fbe..dc4c7a87 100644 --- a/src/components/Terminal.tsx +++ b/src/components/Terminal.tsx @@ -145,8 +145,8 @@ export function Terminal({ cwd, className }: TerminalProps) { const result = await shellToolRef.current.execute({ command }); // Add output - if (result && result.trim()) { - addLine('output', result); + if (result.content && result.content.trim()) { + addLine('output', result.content); } } } diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 7829938c..31a9ad0f 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -241,11 +241,12 @@ export class SessionManager { const maxSteps = session.maxSteps || 50; // Main AI generation loop - while (stepCount < maxSteps && session.isLoading) { - session = this.sessions.get(projectId); - if (!session) { - throw new Error('Session not found'); + while (stepCount < maxSteps) { + const currentSession = this.sessions.get(projectId); + if (!currentSession || !currentSession.isLoading) { + break; } + session = currentSession; stepCount++; @@ -600,8 +601,19 @@ export class SessionManager { const rawArgs = functionToolCall.function.arguments; toolArgs = rawArgs ? JSON.parse(rawArgs) : {}; } - const content = await tool.execute(toolArgs); - await this.addToolMessage(projectId, functionToolCall.id, content); + const result = await tool.execute(toolArgs); + await this.addToolMessage(projectId, functionToolCall.id, result.content); + + // Update session cost if tool returned a cost + if (result.cost !== undefined) { + const updatedSession = this.sessions.get(projectId); + if (updatedSession) { + const currentCost = updatedSession.totalCost || 0; + updatedSession.totalCost = currentCost + result.cost; + this.sessions.set(projectId, updatedSession); + this.emit('costUpdated', projectId, updatedSession.totalCost); + } + } } catch (error) { const errorMsg = error instanceof Error ? error.message : 'Unknown error'; await this.addToolMessage(projectId, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`); diff --git a/src/lib/tools/BuildProjectTool.test.ts b/src/lib/tools/BuildProjectTool.test.ts index f7453c47..36a1caac 100644 --- a/src/lib/tools/BuildProjectTool.test.ts +++ b/src/lib/tools/BuildProjectTool.test.ts @@ -75,12 +75,12 @@ describe('BuildProjectTool', () => { domParser: expect.any(DOMParser), }); - expect(result).toContain('āœ… Successfully built project!'); - expect(result).toContain('šŸ“ Output: /test/project/dist'); - expect(result).toContain('šŸ“¦ Files generated: 3'); - expect(result).toContain('šŸ“„ index.html'); - expect(result).toContain('šŸ“„ main.js'); - expect(result).toContain('šŸ“„ main.css'); + expect(result.content).toContain('āœ… Successfully built project!'); + expect(result.content).toContain('šŸ“ Output: /test/project/dist'); + expect(result.content).toContain('šŸ“¦ Files generated: 3'); + expect(result.content).toContain('šŸ“„ index.html'); + expect(result.content).toContain('šŸ“„ main.js'); + expect(result.content).toContain('šŸ“„ main.css'); }); it('should clean existing dist directory before building', async () => { diff --git a/src/lib/tools/BuildProjectTool.ts b/src/lib/tools/BuildProjectTool.ts index c250d945..c91e6a86 100644 --- a/src/lib/tools/BuildProjectTool.ts +++ b/src/lib/tools/BuildProjectTool.ts @@ -1,4 +1,4 @@ -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; import { buildProject } from "../build"; @@ -15,7 +15,7 @@ export class BuildProjectTool implements Tool { this.esmUrl = esmUrl; } - async execute(): Promise { + async execute(): Promise { try { // Build and write the project files const result = await buildProject({ @@ -28,7 +28,9 @@ export class BuildProjectTool implements Tool { const fileCount = Object.keys(result.files).length; const fileList = Object.keys(result.files).map(file => ` šŸ“„ ${file}`).join('\n'); - return `āœ… Successfully built project!\n\nšŸ“ Output: ${result.outputPath}\nšŸ“¦ Files generated: ${fileCount}\n\n${fileList}\n\nšŸš€ Your project is ready for deployment!`; + return { + content: `āœ… Successfully built project!\n\nšŸ“ Output: ${result.outputPath}\nšŸ“¦ Files generated: ${fileCount}\n\n${fileList}\n\nšŸš€ Your project is ready for deployment!` + }; } catch (error) { throw new Error(`āŒ Build failed: ${String(error)}`); } diff --git a/src/lib/tools/ConfigureImageGenerationTool.ts b/src/lib/tools/ConfigureImageGenerationTool.ts index 894df6d7..97448478 100644 --- a/src/lib/tools/ConfigureImageGenerationTool.ts +++ b/src/lib/tools/ConfigureImageGenerationTool.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import type { Tool } from './Tool'; +import type { Tool, ToolResult } from './Tool'; import type { AISettingsContextType } from '@/contexts/AISettingsContext'; interface ConfigureImageGenerationParams { @@ -28,12 +28,12 @@ export class ConfigureImageGenerationTool implements Tool { + async execute(args: ConfigureImageGenerationParams): Promise { const { modelId } = args; // Validate model ID format if (!modelId.includes('/')) { - return 'ERROR: Invalid model ID format. The modelId must be in "provider/model" format (e.g., "openrouter/openai/gpt-image-1" or "openai/dall-e-3").'; + return { content: 'ERROR: Invalid model ID format. The modelId must be in "provider/model" format (e.g., "openrouter/openai/gpt-image-1" or "openai/dall-e-3").' }; } // Check if model exists in available models (optional - provides helpful info if available) @@ -55,6 +55,6 @@ export class ConfigureImageGenerationTool implements Tool { this.projectId = projectId; } - async execute(args: DeployProjectParams): Promise { + async execute(args: DeployProjectParams): Promise { try { // Use provided deployServer or default to shakespeare.wtf const deployServer = args.deployServer || "shakespeare.wtf"; @@ -59,7 +59,9 @@ export class DeployProjectTool implements Tool { projectPath: this.cwd, }); - return `āœ… Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\nšŸš€ Your project is now live and accessible to anyone with the URL!`; + return { + content: `āœ… Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\nšŸš€ Your project is now live and accessible to anyone with the URL!` + }; } catch (error) { throw new Error(`āŒ Deployment failed: ${String(error)}`); } diff --git a/src/lib/tools/GenerateImageTool.test.ts b/src/lib/tools/GenerateImageTool.test.ts index 5bdb7777..e9262e7c 100644 --- a/src/lib/tools/GenerateImageTool.test.ts +++ b/src/lib/tools/GenerateImageTool.test.ts @@ -115,7 +115,7 @@ describe('GenerateImageTool', () => { const result = await tool.execute({ prompt: 'a beautiful sunset' }); - expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/); + expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/); expect(mockFS.writeFile).toHaveBeenCalledWith( expect.stringMatching(/^\/tmp\/generated-\d+\.png$/), expect.any(Uint8Array) @@ -162,7 +162,7 @@ describe('GenerateImageTool', () => { const result = await tool.execute({ prompt: 'a beautiful sunset' }); - expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/); + expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/); expect(mockFS.writeFile).toHaveBeenCalledWith( expect.stringMatching(/^\/tmp\/generated-\d+\.png$/), expect.any(Uint8Array) @@ -262,7 +262,7 @@ describe('GenerateImageTool', () => { const result = await tool.execute({ prompt: 'a beautiful sunset' }); - expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.jpeg$/); + expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.jpeg$/); }); it('should throw error when chat mode returns invalid data URI', async () => { diff --git a/src/lib/tools/GenerateImageTool.ts b/src/lib/tools/GenerateImageTool.ts index ee6e94f2..30412e2e 100644 --- a/src/lib/tools/GenerateImageTool.ts +++ b/src/lib/tools/GenerateImageTool.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import type { Tool } from './Tool'; +import type { Tool, ToolResult } from './Tool'; import type { AIProvider } from '@/contexts/AISettingsContext'; import type { NUser } from '@nostrify/react/login'; import { createAIClient } from '@/lib/ai-client'; @@ -29,7 +29,7 @@ export class GenerateImageTool implements Tool { private corsProxy?: string, ) {} - async execute(args: GenerateImageParams): Promise { + async execute(args: GenerateImageParams): Promise { const { prompt } = args; try { @@ -152,7 +152,7 @@ export class GenerateImageTool implements Tool { // Write image to VFS await this.fs.writeFile(filepath, imageData); - return `Generated image: ${filepath}`; + return { content: `Generated image: ${filepath}` }; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); throw new Error(`Failed to generate image: ${errorMessage}`); diff --git a/src/lib/tools/GitCommitTool.test.ts b/src/lib/tools/GitCommitTool.test.ts index f5d72117..d83513ff 100644 --- a/src/lib/tools/GitCommitTool.test.ts +++ b/src/lib/tools/GitCommitTool.test.ts @@ -76,8 +76,8 @@ describe('GitCommitTool', () => { dir: '/test/project', message: 'Add new feature', }); - expect(result).toContain('āœ… Successfully committed 2 files (abcd123)'); - expect(result).toContain('Add new feature'); + expect(result.content).toContain('āœ… Successfully committed 2 files (abcd123)'); + expect(result.content).toContain('Add new feature'); }); it('should handle empty commit message', async () => { @@ -121,8 +121,8 @@ describe('GitCommitTool', () => { expect(mockGitInstance.commit).toHaveBeenCalledWith(expect.objectContaining({ message: specialMessage, })); - expect(result).toContain('āœ… Successfully committed'); - expect(result).toContain(specialMessage); + expect(result.content).toContain('āœ… Successfully committed'); + expect(result.content).toContain(specialMessage); }); it('should handle multiline commit message', async () => { @@ -136,8 +136,8 @@ describe('GitCommitTool', () => { const result = await tool.execute({ message: multilineMessage }); expect(mockGitInstance.commit).toHaveBeenCalled(); - expect(result).toContain('āœ… Successfully committed'); - expect(result).toContain('Add new feature'); + expect(result.content).toContain('āœ… Successfully committed'); + expect(result.content).toContain('Add new feature'); }); it('should handle no changes to commit', async () => { @@ -152,7 +152,7 @@ describe('GitCommitTool', () => { const result = await tool.execute({ message: 'Update documentation' }); - expect(result).toContain('ā„¹ļø No changes to commit. Working tree is clean.'); + expect(result.content).toContain('ā„¹ļø No changes to commit. Working tree is clean.'); expect(mockGitInstance.commit).not.toHaveBeenCalled(); }); @@ -165,10 +165,10 @@ describe('GitCommitTool', () => { const result = await tool.execute({ message: 'Update documentation' }); - expect(result).toContain('šŸ“ Commit: "Update documentation"'); - expect(result).toContain('šŸ”— Hash:'); - expect(result).toContain('🌿 Branch:'); - expect(result).toContain('šŸ“Š Changes:'); + expect(result.content).toContain('šŸ“ Commit: "Update documentation"'); + expect(result.content).toContain('šŸ”— Hash:'); + expect(result.content).toContain('🌿 Branch:'); + expect(result.content).toContain('šŸ“Š Changes:'); }); @@ -183,7 +183,7 @@ describe('GitCommitTool', () => { const longMessage = 'A'.repeat(1000); // Very long commit message const result = await tool.execute({ message: longMessage }); - expect(result).toContain('āœ… Successfully committed'); + expect(result.content).toContain('āœ… Successfully committed'); }); it('should error when HEAD is detached (currentBranch returns null)', async () => { diff --git a/src/lib/tools/GitCommitTool.ts b/src/lib/tools/GitCommitTool.ts index c75fe817..21145302 100644 --- a/src/lib/tools/GitCommitTool.ts +++ b/src/lib/tools/GitCommitTool.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { Git } from "../git"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; interface GitCommitParams { @@ -25,7 +25,7 @@ export class GitCommitTool implements Tool { this.cwd = cwd; } - async execute(args: GitCommitParams): Promise { + async execute(args: GitCommitParams): Promise { const { message } = args; try { @@ -75,7 +75,7 @@ export class GitCommitTool implements Tool { }); if (changedFiles.length === 0) { - return `ā„¹ļø No changes to commit. Working tree is clean.`; + return { content: `ā„¹ļø No changes to commit. Working tree is clean.` }; } // Add all changed files to staging @@ -133,7 +133,7 @@ export class GitCommitTool implements Tool { if (modifiedFiles > 0) details += ` • ${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} modified\n`; if (deletedFiles > 0) details += ` • ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted\n`; - return `${summary}\n\n${details}`; + return { content: `${summary}\n\n${details}` }; } catch (error) { throw new Error(`āŒ Error committing changes: ${String(error)}`); } diff --git a/src/lib/tools/MCPTool.ts b/src/lib/tools/MCPTool.ts index 8cf3fb37..c04dadd8 100644 --- a/src/lib/tools/MCPTool.ts +++ b/src/lib/tools/MCPTool.ts @@ -1,4 +1,4 @@ -import type { Tool } from './Tool'; +import type { Tool, ToolResult } from './Tool'; import type { MCPClient } from '@/lib/MCPClient'; /** @@ -19,8 +19,9 @@ export class MCPTool implements Tool> { this.originalToolName = originalToolName; } - async execute(args: Record): Promise { - return await this.client.callTool(this.originalToolName, args); + async execute(args: Record): Promise { + const content = await this.client.callTool(this.originalToolName, args); + return { content }; } } diff --git a/src/lib/tools/NostrFetchEventTool.ts b/src/lib/tools/NostrFetchEventTool.ts index cac06be6..86f26a12 100644 --- a/src/lib/tools/NostrFetchEventTool.ts +++ b/src/lib/tools/NostrFetchEventTool.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; interface NostrFetchEventParams { identifier: string; @@ -26,7 +26,7 @@ export class NostrFetchEventTool implements Tool { }); return; } - + // Reject nsec for security reasons if (decoded.type === 'nsec') { ctx.addIssue({ @@ -36,7 +36,7 @@ export class NostrFetchEventTool implements Tool { }); return; } - + // Accept npub, nprofile, naddr, note, nevent if (!['npub', 'nprofile', 'naddr', 'note', 'nevent'].includes(decoded.type)) { ctx.addIssue({ @@ -52,7 +52,7 @@ export class NostrFetchEventTool implements Tool { ), }); - async execute(args: NostrFetchEventParams): Promise { + async execute(args: NostrFetchEventParams): Promise { const { identifier } = args; const decoded = nip19.decode(identifier); @@ -169,12 +169,12 @@ export class NostrFetchEventTool implements Tool { // Special handling for specific kinds if (event.kind === 30817) { // Kind 30817 is a NIP document, return just the content - return event.content; + return { content: event.content }; } - + // For other kinds, return the full event JSON - return JSON.stringify(event, null, 2); - + return { content: JSON.stringify(event, null, 2) }; + } catch (error) { throw new Error(`Error fetching event: ${error instanceof Error ? error.message : 'Unknown error'}`); } finally { diff --git a/src/lib/tools/NostrGenerateKindTool.ts b/src/lib/tools/NostrGenerateKindTool.ts index 37e3918e..eef82d32 100644 --- a/src/lib/tools/NostrGenerateKindTool.ts +++ b/src/lib/tools/NostrGenerateKindTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { KindGenerator, type KindRange } from "../KindGenerator"; import { NIPsClient } from "../NIPsClient"; @@ -26,7 +26,7 @@ export class NostrGenerateKindTool implements Tool { }); } - async execute(args: NostrGenerateKindParams): Promise { + async execute(args: NostrGenerateKindParams): Promise { const { range } = args; try { @@ -39,7 +39,9 @@ export class NostrGenerateKindTool implements Tool { const rangeInfo = KindGenerator.getKindRangeInfo(range); - return `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.`; + return { + content: `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.` + }; } catch (error) { throw new Error(`Error generating kind: ${error instanceof Error ? error.message : 'Unknown error'}`); } diff --git a/src/lib/tools/NostrPublishEventsTool.test.ts b/src/lib/tools/NostrPublishEventsTool.test.ts index 09db4ef0..d42a0caa 100644 --- a/src/lib/tools/NostrPublishEventsTool.test.ts +++ b/src/lib/tools/NostrPublishEventsTool.test.ts @@ -78,7 +78,7 @@ describe('NostrPublishEventsTool', () => { events: [{}], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.success).toBe(true); expect(parsed.pubkey).toBeDefined(); expect(parsed.events_published).toBe(2); // kind 0 + 1 user event @@ -95,7 +95,7 @@ describe('NostrPublishEventsTool', () => { ], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.success).toBe(true); expect(parsed.events_published).toBe(3); // kind 0 + 2 user events expect(parsed.events[1].kind).toBe(1); @@ -110,7 +110,7 @@ describe('NostrPublishEventsTool', () => { relays: customRelays, }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.relays).toEqual(customRelays); }); @@ -120,7 +120,7 @@ describe('NostrPublishEventsTool', () => { events: [{ kind: 1, content: longContent }], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.events[1].content).toHaveLength(103); // 100 chars + '...' expect(parsed.events[1].content).toMatch(/^a+\.\.\.$/); }); @@ -143,7 +143,7 @@ describe('NostrPublishEventsTool', () => { events: [{ kind: 1, content: 'test', created_at: customTime }], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.success).toBe(true); }); @@ -155,7 +155,7 @@ describe('NostrPublishEventsTool', () => { ], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.success).toBe(true); expect(parsed.events_published).toBe(2); // Only the 2 user events, no fallback expect(parsed.events[0].kind).toBe(0); // User's kind 0 @@ -170,7 +170,7 @@ describe('NostrPublishEventsTool', () => { ], }); - const parsed = JSON.parse(result); + const parsed = JSON.parse(result.content); expect(parsed.success).toBe(true); expect(parsed.events_published).toBe(3); // Fallback kind 0 + 2 user events expect(parsed.events[0].kind).toBe(0); // Fallback profile event diff --git a/src/lib/tools/NostrPublishEventsTool.ts b/src/lib/tools/NostrPublishEventsTool.ts index e7e491e6..9e3508c8 100644 --- a/src/lib/tools/NostrPublishEventsTool.ts +++ b/src/lib/tools/NostrPublishEventsTool.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify'; import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools'; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; interface NostrPublishEventsParams { events: Array<{ @@ -29,7 +29,7 @@ export class NostrPublishEventsTool implements Tool { relays: z.array(z.string().url()).optional().describe('Optional array of relay URLs to publish to (default: hardcoded relay list)'), }); - async execute(args: NostrPublishEventsParams): Promise { + async execute(args: NostrPublishEventsParams): Promise { const { events: partialEvents, relays } = args; // Default relays if none provided @@ -114,7 +114,7 @@ export class NostrPublishEventsTool implements Tool { })), }; - return JSON.stringify(summary, null, 2); + return { content: JSON.stringify(summary, null, 2) }; } catch (error) { throw new Error(`Error publishing events: ${error instanceof Error ? error.message : 'Unknown error'}`); } finally { diff --git a/src/lib/tools/NostrReadKindTool.ts b/src/lib/tools/NostrReadKindTool.ts index 597f5de4..52d27bc9 100644 --- a/src/lib/tools/NostrReadKindTool.ts +++ b/src/lib/tools/NostrReadKindTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { NostrbookClient } from "../NostrbookClient"; import { HTTPError } from "../HTTPError"; @@ -23,12 +23,12 @@ export class NostrReadKindTool implements Tool { }); } - async execute(args: NostrReadKindParams): Promise { + async execute(args: NostrReadKindParams): Promise { const { kind } = args; try { const text = await this.nostrbookClient.readKind(kind); - return text; + return { content: text }; } catch (error) { if (error instanceof HTTPError && error.response.status === 404) { throw new Error( diff --git a/src/lib/tools/NostrReadNipTool.ts b/src/lib/tools/NostrReadNipTool.ts index 71f0be32..b061d171 100644 --- a/src/lib/tools/NostrReadNipTool.ts +++ b/src/lib/tools/NostrReadNipTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { NIPsClient } from "../NIPsClient"; import { HTTPError } from "../HTTPError"; @@ -30,12 +30,12 @@ export class NostrReadNipTool implements Tool { }); } - async execute(args: NostrReadNipParams): Promise { + async execute(args: NostrReadNipParams): Promise { const { nip } = args; try { const text = await this.nipsClient.readNip(nip); - return text; + return { content: text }; } catch (error) { if (error instanceof HTTPError && error.response.status === 404) { throw new Error( diff --git a/src/lib/tools/NostrReadNipsIndexTool.ts b/src/lib/tools/NostrReadNipsIndexTool.ts index 4f0a3d6a..7d4ac2fc 100644 --- a/src/lib/tools/NostrReadNipsIndexTool.ts +++ b/src/lib/tools/NostrReadNipsIndexTool.ts @@ -1,4 +1,4 @@ -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { NIPsClient } from "../NIPsClient"; export class NostrReadNipsIndexTool implements Tool { @@ -12,10 +12,10 @@ export class NostrReadNipsIndexTool implements Tool { }); } - async execute(): Promise { + async execute(): Promise { try { const text = await this.nipsClient.readIndex(); - return text; + return { content: text }; } catch (error) { throw new Error(`Error reading NIPs index: ${error instanceof Error ? error.message : 'Unknown error'}`); } diff --git a/src/lib/tools/NostrReadProtocolTool.ts b/src/lib/tools/NostrReadProtocolTool.ts index 74cb8725..c1b18605 100644 --- a/src/lib/tools/NostrReadProtocolTool.ts +++ b/src/lib/tools/NostrReadProtocolTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { NostrbookClient } from "../NostrbookClient"; interface NostrReadProtocolParams { @@ -22,12 +22,12 @@ export class NostrReadProtocolTool implements Tool { }); } - async execute(args: NostrReadProtocolParams): Promise { + async execute(args: NostrReadProtocolParams): Promise { const { doc } = args; try { const text = await this.nostrbookClient.readProtocol(doc); - return text; + return { content: text }; } catch (error) { throw new Error(`Error reading protocol doc "${doc}": ${error instanceof Error ? error.message : 'Unknown error'}`); } diff --git a/src/lib/tools/NostrReadTagTool.ts b/src/lib/tools/NostrReadTagTool.ts index b7ba59e2..2b25558b 100644 --- a/src/lib/tools/NostrReadTagTool.ts +++ b/src/lib/tools/NostrReadTagTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import { NostrbookClient } from "../NostrbookClient"; import { HTTPError } from "../HTTPError"; @@ -23,12 +23,12 @@ export class NostrReadTagTool implements Tool { }); } - async execute(args: NostrReadTagParams): Promise { + async execute(args: NostrReadTagParams): Promise { const { tag } = args; try { const text = await this.nostrbookClient.readTag(tag); - return text; + return { content: text }; } catch (error) { if (error instanceof HTTPError && error.response.status === 404) { throw new Error( diff --git a/src/lib/tools/NpmAddPackageTool.test.ts b/src/lib/tools/NpmAddPackageTool.test.ts index 0e4a8917..c04798b5 100644 --- a/src/lib/tools/NpmAddPackageTool.test.ts +++ b/src/lib/tools/NpmAddPackageTool.test.ts @@ -70,8 +70,8 @@ describe('NpmAddPackageTool', () => { expect.stringContaining('"lodash": "^4.17.21"'), 'utf8' ); - expect(result).toContain('āœ… Successfully added lodash@4.17.21'); - expect(result).toContain('Updated: package.json'); + expect(result.content).toContain('āœ… Successfully added lodash@4.17.21'); + expect(result.content).toContain('Updated: package.json'); }); it('should add package with specific version', async () => { @@ -105,7 +105,7 @@ describe('NpmAddPackageTool', () => { expect.stringContaining('"lodash": "^4.17.20"'), 'utf8' ); - expect(result).toContain('āœ… Successfully added lodash@4.17.20'); + expect(result.content).toContain('āœ… Successfully added lodash@4.17.20'); }); it('should add dev dependency', async () => { @@ -146,7 +146,7 @@ describe('NpmAddPackageTool', () => { expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0'); expect(writtenPackageJson.dependencies?.typescript).toBeUndefined(); - expect(result).toContain('Development dependency'); + expect(result.content).toContain('Development dependency'); }); it('should move package from dependencies to devDependencies', async () => { @@ -183,7 +183,7 @@ describe('NpmAddPackageTool', () => { expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0'); // dependencies object should be empty or not contain typescript expect(writtenPackageJson.dependencies?.typescript).toBeUndefined(); - expect(result).toContain('āœ… Successfully added'); + expect(result.content).toContain('āœ… Successfully added'); }); it('should handle package already installed', async () => { @@ -202,7 +202,7 @@ describe('NpmAddPackageTool', () => { // Should not fetch from registry when no version specified and package already installed expect(mockFetch).not.toHaveBeenCalled(); expect(mockFS.writeFile).not.toHaveBeenCalled(); - expect(result).toContain('ā„¹ļø Package lodash is already installed in dependencies with version ^4.17.21.'); + expect(result.content).toContain('ā„¹ļø Package lodash is already installed in dependencies with version ^4.17.21.'); }); it('should handle package already installed with specific version', async () => { @@ -230,7 +230,7 @@ describe('NpmAddPackageTool', () => { const result = await tool.execute({ name: 'lodash', version: '4.17.21' }); expect(mockFS.writeFile).not.toHaveBeenCalled(); - expect(result).toContain('ā„¹ļø Package lodash@4.17.21 is already installed in dependencies.'); + expect(result.content).toContain('ā„¹ļø Package lodash@4.17.21 is already installed in dependencies.'); }); it('should handle missing package.json', async () => { @@ -295,7 +295,7 @@ describe('NpmAddPackageTool', () => { const dependencyKeys = Object.keys(writtenPackageJson.dependencies); expect(dependencyKeys).toEqual(['axios', 'lodash', 'zlib']); - expect(result).toContain('āœ… Successfully added'); + expect(result.content).toContain('āœ… Successfully added'); }); it('should update package-lock.json when it exists', async () => { @@ -354,7 +354,7 @@ describe('NpmAddPackageTool', () => { license: 'MIT' }); - expect(result).toContain('Updated: package.json, package-lock.json'); + expect(result.content).toContain('Updated: package.json, package-lock.json'); }); it('should update package-lock.json for dev dependencies', async () => { @@ -413,7 +413,7 @@ describe('NpmAddPackageTool', () => { engines: { node: '>=14.17' } }); - expect(result).toContain('Updated: package.json, package-lock.json'); + expect(result.content).toContain('Updated: package.json, package-lock.json'); }); it('should move package between dependency types in package-lock.json', async () => { @@ -487,7 +487,7 @@ describe('NpmAddPackageTool', () => { dev: true }); - expect(result).toContain('āœ… Successfully added'); + expect(result.content).toContain('āœ… Successfully added'); }); it('should handle corrupted package-lock.json gracefully', async () => { @@ -516,8 +516,8 @@ describe('NpmAddPackageTool', () => { // Should not throw error, just log warning and continue const result = await tool.execute({ name: 'lodash' }); - expect(result).toContain('āœ… Successfully added lodash@4.17.21'); - expect(result).toContain('Updated: package.json'); // Should not mention package-lock.json + expect(result.content).toContain('āœ… Successfully added lodash@4.17.21'); + expect(result.content).toContain('Updated: package.json'); // Should not mention package-lock.json expect(mockFS.writeFile).toHaveBeenCalledTimes(1); // Only package.json should be written }); }); \ No newline at end of file diff --git a/src/lib/tools/NpmAddPackageTool.ts b/src/lib/tools/NpmAddPackageTool.ts index a911d657..650aa3b6 100644 --- a/src/lib/tools/NpmAddPackageTool.ts +++ b/src/lib/tools/NpmAddPackageTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; interface NpmAddPackageParams { @@ -66,7 +66,7 @@ export class NpmAddPackageTool implements Tool { this.cwd = cwd; } - async execute(args: NpmAddPackageParams): Promise { + async execute(args: NpmAddPackageParams): Promise { const { name, version, dev = false } = args; try { @@ -95,7 +95,7 @@ export class NpmAddPackageTool implements Tool { // If no version is specified and package is already installed, it's a no-op if (!version && packageJson[dependencyKey]?.[name]) { const currentVersion = packageJson[dependencyKey][name]; - return `ā„¹ļø Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`; + return { content: `ā„¹ļø Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.` }; } // Determine version to use and fetch package metadata @@ -121,7 +121,7 @@ export class NpmAddPackageTool implements Tool { if (packageJson[dependencyKey]?.[name]) { const currentVersion = packageJson[dependencyKey][name]; if (currentVersion === `^${targetVersion}`) { - return `ā„¹ļø Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`; + return { content: `ā„¹ļø Package ${name}@${targetVersion} is already installed in ${dependencyKey}.` }; } } @@ -164,7 +164,9 @@ export class NpmAddPackageTool implements Tool { // Update package-lock.json if it exists await this.updatePackageLock(name, targetVersion, packageMetadata, dev); - return `āœ… Successfully added ${name}@${targetVersion} to ${dependencyKey}\n\nšŸ“¦ Package: ${name}\nšŸ·ļø Version: ^${targetVersion}\nšŸ“ Type: ${dev ? 'Development dependency' : 'Production dependency'}\nšŸ“„ Updated: package.json${await this.packageLockExists() ? ', package-lock.json' : ''}`; + return { + content: `āœ… Successfully added ${name}@${targetVersion} to ${dependencyKey}\n\nšŸ“¦ Package: ${name}\nšŸ·ļø Version: ^${targetVersion}\nšŸ“ Type: ${dev ? 'Development dependency' : 'Production dependency'}\nšŸ“„ Updated: package.json${await this.packageLockExists() ? ', package-lock.json' : ''}` + }; } catch (error) { throw new Error(`āŒ Error adding package ${name}: ${String(error)}`); } diff --git a/src/lib/tools/NpmRemovePackageTool.test.ts b/src/lib/tools/NpmRemovePackageTool.test.ts index 8bd49c62..99e27780 100644 --- a/src/lib/tools/NpmRemovePackageTool.test.ts +++ b/src/lib/tools/NpmRemovePackageTool.test.ts @@ -51,7 +51,7 @@ describe('NpmRemovePackageTool', () => { expect(writtenPackageJson.dependencies.lodash).toBeUndefined(); expect(writtenPackageJson.dependencies.axios).toBe('^1.0.0'); - expect(result).toContain('āœ… Successfully removed lodash from dependencies'); + expect(result.content).toContain('āœ… Successfully removed lodash from dependencies'); }); it('should successfully remove package from devDependencies', async () => { @@ -77,7 +77,7 @@ describe('NpmRemovePackageTool', () => { expect(writtenPackageJson.devDependencies.typescript).toBeUndefined(); expect(writtenPackageJson.devDependencies.eslint).toBe('^8.0.0'); expect(writtenPackageJson.dependencies.react).toBe('^18.0.0'); - expect(result).toContain('āœ… Successfully removed typescript from devDependencies'); + expect(result.content).toContain('āœ… Successfully removed typescript from devDependencies'); }); it('should remove empty dependencies object', async () => { @@ -97,7 +97,7 @@ describe('NpmRemovePackageTool', () => { const writtenPackageJson = JSON.parse(writtenContent); expect(writtenPackageJson.dependencies).toBeUndefined(); - expect(result).toContain('āœ… Successfully removed'); + expect(result.content).toContain('āœ… Successfully removed'); }); it('should remove empty devDependencies object', async () => { @@ -121,7 +121,7 @@ describe('NpmRemovePackageTool', () => { expect(writtenPackageJson.devDependencies).toBeUndefined(); expect(writtenPackageJson.dependencies.react).toBe('^18.0.0'); - expect(result).toContain('āœ… Successfully removed'); + expect(result.content).toContain('āœ… Successfully removed'); }); it('should handle package not found', async () => { @@ -138,7 +138,7 @@ describe('NpmRemovePackageTool', () => { const result = await tool.execute({ name: 'nonexistent-package' }); expect(mockFS.writeFile).not.toHaveBeenCalled(); - expect(result).toContain('ā„¹ļø Package nonexistent-package was not found'); + expect(result.content).toContain('ā„¹ļø Package nonexistent-package was not found'); }); it('should handle missing package.json', async () => { @@ -173,7 +173,7 @@ describe('NpmRemovePackageTool', () => { const dependencyKeys = Object.keys(writtenPackageJson.dependencies); expect(dependencyKeys).toEqual(['axios', 'zlib']); - expect(result).toContain('āœ… Successfully removed'); + expect(result.content).toContain('āœ… Successfully removed'); }); it('should include version information in success message', async () => { @@ -189,7 +189,7 @@ describe('NpmRemovePackageTool', () => { const result = await tool.execute({ name: 'lodash' }); - expect(result).toContain('šŸ·ļø Version: ^4.17.21'); - expect(result).toContain('šŸ“ Removed from: dependencies'); + expect(result.content).toContain('šŸ·ļø Version: ^4.17.21'); + expect(result.content).toContain('šŸ“ Removed from: dependencies'); }); }); \ No newline at end of file diff --git a/src/lib/tools/NpmRemovePackageTool.ts b/src/lib/tools/NpmRemovePackageTool.ts index 1b39a397..95b60945 100644 --- a/src/lib/tools/NpmRemovePackageTool.ts +++ b/src/lib/tools/NpmRemovePackageTool.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; interface NpmRemovePackageParams { @@ -28,7 +28,7 @@ export class NpmRemovePackageTool implements Tool { this.cwd = cwd; } - async execute(args: NpmRemovePackageParams): Promise { + async execute(args: NpmRemovePackageParams): Promise { const { name } = args; try { @@ -75,7 +75,7 @@ export class NpmRemovePackageTool implements Tool { } if (!foundIn) { - return `ā„¹ļø Package ${name} was not found in package.json dependencies or devDependencies.`; + return { content: `ā„¹ļø Package ${name} was not found in package.json dependencies or devDependencies.` }; } // Sort remaining dependencies alphabetically @@ -99,7 +99,9 @@ export class NpmRemovePackageTool implements Tool { const updatedContent = JSON.stringify(packageJson, null, 2) + '\n'; await this.fs.writeFile(packageJsonPath, updatedContent, "utf8"); - return `āœ… Successfully removed ${name} from ${foundIn} in package.json\n\nšŸ“¦ Package: ${name}\nšŸ·ļø Version: ${removedVersion}\nšŸ“ Removed from: ${foundIn}\n\nāš ļø **Next step**: Run \`npm install\` to update node_modules and package-lock.json`; + return { + content: `āœ… Successfully removed ${name} from ${foundIn} in package.json\n\nšŸ“¦ Package: ${name}\nšŸ·ļø Version: ${removedVersion}\nšŸ“ Removed from: ${foundIn}\n\nāš ļø **Next step**: Run \`npm install\` to update node_modules and package-lock.json` + }; } catch (error) { throw new Error(`āŒ Error removing package ${name}: ${String(error)}`); } diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 82da491b..a7bdb8d5 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -16,31 +16,31 @@ describe('ReadConsoleMessagesTool', () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({}); - expect(result).toContain('Found 4 console messages'); - expect(result).toContain('[LOG] App started'); - expect(result).toContain('[WARN] Deprecated API used'); - expect(result).toContain('[ERROR] Network request failed'); - expect(result).toContain('[INFO] User logged in'); + expect(result.content).toContain('Found 4 console messages'); + expect(result.content).toContain('[LOG] App started'); + expect(result.content).toContain('[WARN] Deprecated API used'); + expect(result.content).toContain('[ERROR] Network request failed'); + expect(result.content).toContain('[INFO] User logged in'); }); it('should filter messages by level', async () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({ filter: 'error' }); - expect(result).toContain('Found 1 console message (level: error)'); - expect(result).toContain('[ERROR] Network request failed'); - expect(result).not.toContain('[LOG] App started'); + expect(result.content).toContain('Found 1 console message (level: error)'); + expect(result.content).toContain('[ERROR] Network request failed'); + expect(result.content).not.toContain('[LOG] App started'); }); it('should limit number of messages', async () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({ limit: 2 }); - expect(result).toContain('Found 2 console messages'); + expect(result.content).toContain('Found 2 console messages'); // Should get the last 2 messages - expect(result).toContain('[ERROR] Network request failed'); - expect(result).toContain('[INFO] User logged in'); - expect(result).not.toContain('[LOG] App started'); + expect(result.content).toContain('[ERROR] Network request failed'); + expect(result.content).toContain('[INFO] User logged in'); + expect(result.content).not.toContain('[LOG] App started'); }); it('should handle no messages found', async () => { @@ -48,14 +48,14 @@ describe('ReadConsoleMessagesTool', () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({}); - expect(result).toBe('No console messages found.'); + expect(result.content).toBe('No console messages found.'); }); it('should handle no messages found with filter', async () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({ filter: 'debug' }); - expect(result).toBe('No console messages found for level: debug.'); + expect(result.content).toBe('No console messages found for level: debug.'); }); it('should handle all filter levels', async () => { @@ -63,16 +63,16 @@ describe('ReadConsoleMessagesTool', () => { // Test each filter level const errorResult = await tool.execute({ filter: 'error' }); - expect(errorResult).toContain('[ERROR] Network request failed'); + expect(errorResult.content).toContain('[ERROR] Network request failed'); const warnResult = await tool.execute({ filter: 'warn' }); - expect(warnResult).toContain('[WARN] Deprecated API used'); + expect(warnResult.content).toContain('[WARN] Deprecated API used'); const logResult = await tool.execute({ filter: 'log' }); - expect(logResult).toContain('[LOG] App started'); + expect(logResult.content).toContain('[LOG] App started'); const infoResult = await tool.execute({ filter: 'info' }); - expect(infoResult).toContain('[INFO] User logged in'); + expect(infoResult.content).toContain('[INFO] User logged in'); }); it('should format messages correctly', async () => { @@ -82,7 +82,7 @@ describe('ReadConsoleMessagesTool', () => { const tool = new ReadConsoleMessagesTool(); const result = await tool.execute({}); - expect(result).toContain('[ERROR] Test error with special chars: <>&"'); + expect(result.content).toContain('[ERROR] Test error with special chars: <>&"'); }); it('should handle limit correctly', async () => { @@ -90,11 +90,11 @@ describe('ReadConsoleMessagesTool', () => { // Limit should return only the most recent messages const limitedResult = await tool.execute({ limit: 2 }); - expect(limitedResult).toContain('Found 2 console messages'); + expect(limitedResult.content).toContain('Found 2 console messages'); // Default limit (50) should return all messages when total is less than 50 const allResult = await tool.execute({}); - expect(allResult).toContain('Found 4 console messages'); + expect(allResult.content).toContain('Found 4 console messages'); }); it('should show truncation note when messages exceed limit', async () => { @@ -108,12 +108,12 @@ describe('ReadConsoleMessagesTool', () => { // Default limit is 50 const result = await tool.execute({}); - expect(result).toContain('(showing last 50 of 60)'); - expect(result).toContain('Message 60'); // Most recent - expect(result).not.toContain('Message 10'); // Too old + expect(result.content).toContain('(showing last 50 of 60)'); + expect(result.content).toContain('Message 60'); // Most recent + expect(result.content).not.toContain('Message 10'); // Too old // Custom limit const limitedResult = await tool.execute({ limit: 10 }); - expect(limitedResult).toContain('(showing last 10 of 60)'); + expect(limitedResult.content).toContain('(showing last 10 of 60)'); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index f2a5abea..6d3c3c87 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { Tool } from './Tool'; +import { Tool, ToolResult } from './Tool'; import { getConsoleMessages } from '@/lib/consoleMessages'; export interface ReadConsoleMessagesParams { @@ -23,7 +23,7 @@ export class ReadConsoleMessagesTool implements Tool ), }); - async execute(params: ReadConsoleMessagesParams): Promise { + async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit = 50 } = params; let messages = getConsoleMessages() @@ -33,7 +33,7 @@ export class ReadConsoleMessagesTool implements Tool messages = messages.slice(-limit); if (messages.length === 0) { - return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`; + return { content: `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.` }; } const formatted = messages @@ -44,6 +44,8 @@ export class ReadConsoleMessagesTool implements Tool const totalAvailable = getConsoleMessages().filter(msg => filter === 'all' || msg.level === filter).length; const truncatedNote = totalAvailable > messages.length ? ` (showing last ${messages.length} of ${totalAvailable})` : ''; - return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}`; + return { + content: `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}` + }; } } \ No newline at end of file diff --git a/src/lib/tools/ReadWebpageTool.test.ts b/src/lib/tools/ReadWebpageTool.test.ts index de61edf7..bab209e1 100644 --- a/src/lib/tools/ReadWebpageTool.test.ts +++ b/src/lib/tools/ReadWebpageTool.test.ts @@ -77,14 +77,14 @@ describe("ReadWebpageTool", () => { url: "https://example.com/article", }); - expect(result).toContain("# Test Article"); - expect(result).toContain("**Source:** https://example.com/article"); - expect(result).toContain("Main Article Title"); - expect(result).toContain("**bold text**"); - expect(result).toContain("*italic text*"); - expect(result).toContain("## Subsection"); - expect(result).toContain("* First item"); - expect(result).toContain("* Second item"); + expect(result.content).toContain("# Test Article"); + expect(result.content).toContain("**Source:** https://example.com/article"); + expect(result.content).toContain("Main Article Title"); + expect(result.content).toContain("**bold text**"); + expect(result.content).toContain("*italic text*"); + expect(result.content).toContain("## Subsection"); + expect(result.content).toContain("* First item"); + expect(result.content).toContain("* Second item"); }); it("should handle articles with metadata", async () => { @@ -122,8 +122,8 @@ describe("ReadWebpageTool", () => { url: "https://example.com/article-with-metadata", }); - expect(result).toContain("# Article with Metadata"); - expect(result).toContain("**Source:** https://example.com/article-with-metadata"); + expect(result.content).toContain("# Article with Metadata"); + expect(result.content).toContain("**Source:** https://example.com/article-with-metadata"); }); it("should handle code blocks properly", async () => { @@ -158,9 +158,9 @@ function hello() { url: "https://example.com/code-example", }); - expect(result).toContain("```"); - expect(result).toContain("function hello()"); - expect(result).toContain("`code`"); + expect(result.content).toContain("```"); + expect(result.content).toContain("function hello()"); + expect(result.content).toContain("`code`"); }); it("should handle HTTP errors", async () => { @@ -223,8 +223,8 @@ function hello() { url: "https://example.com/minimal-content", }); - expect(result).toContain("# Untitled"); - expect(result).toContain("**Source:** https://example.com/minimal-content"); + expect(result.content).toContain("# Untitled"); + expect(result.content).toContain("**Source:** https://example.com/minimal-content"); }); it("should handle invalid URLs", async () => { diff --git a/src/lib/tools/ReadWebpageTool.ts b/src/lib/tools/ReadWebpageTool.ts index 02e8225e..8be096b2 100644 --- a/src/lib/tools/ReadWebpageTool.ts +++ b/src/lib/tools/ReadWebpageTool.ts @@ -2,7 +2,7 @@ import { Readability } from "@mozilla/readability"; import TurndownService from "turndown"; import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; interface ReadWebpageParams { url: string; @@ -54,7 +54,7 @@ export class ReadWebpageTool implements Tool { }); } - async execute(args: ReadWebpageParams): Promise { + async execute(args: ReadWebpageParams): Promise { const { url } = args; try { @@ -111,7 +111,7 @@ export class ReadWebpageTool implements Tool { markdown, ].filter(Boolean).join("\n"); - return result; + return { content: result }; } catch (error) { if (error instanceof TypeError && error.message.includes("fetch")) { diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 64f3dae1..ef7a0872 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -51,19 +51,19 @@ describe('ShellTool', () => { it('should return error for empty command', async () => { const result = await shellTool.execute({ command: '' }); - expect(result).toBe('Error: Empty command'); + expect(result.content).toBe('Error: Empty command'); }); it('should return error for whitespace-only command', async () => { const result = await shellTool.execute({ command: ' ' }); - expect(result).toBe('Error: Empty command'); + expect(result.content).toBe('Error: Empty command'); }); it('should return error for unknown command', async () => { const result = await shellTool.execute({ command: 'unknowncommand' }); - expect(result).toContain("Command 'unknowncommand' not found"); - expect(result).toContain('Available commands:'); - expect(result).toContain('cat'); + expect(result.content).toContain("Command 'unknowncommand' not found"); + expect(result.content).toContain('Available commands:'); + expect(result.content).toContain('cat'); }); it('should execute cat command successfully', async () => { @@ -76,7 +76,7 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cat test.txt' }); - expect(result).toBe(fileContent); + expect(result.content).toBe(fileContent); }); it('should parse commands with arguments correctly', async () => { @@ -90,7 +90,7 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cat file1.txt file2.txt' }); - expect(result).toBe('File 1\nFile 2\n'); + expect(result.content).toBe('File 1\nFile 2\n'); }); it('should handle quoted arguments', async () => { @@ -143,27 +143,27 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cat nonexistent.txt' }); - expect(result).toContain('No such file or directory'); - expect(result).toContain('Exit code: 1'); + expect(result.content).toContain('No such file or directory'); + expect(result.content).toContain('Exit code: 1'); }); it('should show stderr output', async () => { const result = await shellTool.execute({ command: 'cat' }); - expect(result).toContain('missing file operand'); - expect(result).toContain('Exit code: 1'); + expect(result.content).toContain('missing file operand'); + expect(result.content).toContain('Exit code: 1'); }); it('should execute echo command', async () => { const result = await shellTool.execute({ command: 'echo hello world' }); - expect(result).toBe('hello world\n'); + expect(result.content).toBe('hello world\n'); }); it('should execute pwd command', async () => { const result = await shellTool.execute({ command: 'pwd' }); - expect(result).toBe(testCwd); + expect(result.content).toBe(testCwd); }); it('should handle cd command and update working directory', async () => { @@ -174,7 +174,7 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cd subdir' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(shellTool.getCurrentWorkingDirectory()).toBe('/test/dir/subdir'); }); @@ -182,7 +182,7 @@ describe('ShellTool', () => { it('should redirect output to file with > operator', async () => { const result = await shellTool.execute({ command: 'echo "hello world" > test.txt' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'hello world\n', 'utf8'); }); @@ -191,7 +191,7 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'echo "new line" >> test.txt' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8'); expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'existing content\nnew line\n', 'utf8'); }); @@ -201,21 +201,21 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'echo "first line" >> newfile.txt' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/newfile.txt', 'first line\n', 'utf8'); }); it('should handle quoted filenames in redirection', async () => { const result = await shellTool.execute({ command: 'echo test > "file with spaces.txt"' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/file with spaces.txt', 'test\n', 'utf8'); }); it('should handle absolute paths in redirection', async () => { const result = await shellTool.execute({ command: 'echo test > /tmp/absolute.txt' }); - expect(result).toBe('(no output)'); + expect(result.content).toBe('(no output)'); expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/absolute.txt', 'test\n', 'utf8'); }); @@ -224,8 +224,8 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'echo test > /readonly/file.txt' }); - expect(result).toContain('Redirection error: Permission denied'); - expect(result).toContain('Exit code: 1'); + expect(result.content).toContain('Redirection error: Permission denied'); + expect(result.content).toContain('Exit code: 1'); }); }); @@ -233,8 +233,8 @@ describe('ShellTool', () => { it('should execute commands with && operator (success case)', async () => { const result = await shellTool.execute({ command: 'pwd && echo hello' }); - expect(result).toContain(testCwd); - expect(result).toContain('hello'); + expect(result.content).toContain(testCwd); + expect(result.content).toContain('hello'); }); it('should execute commands with && operator (failure case)', async () => { @@ -242,15 +242,15 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cat nonexistent.txt && echo should not run' }); - expect(result).toContain('No such file or directory'); - expect(result).not.toContain('should not run'); + expect(result.content).toContain('No such file or directory'); + expect(result.content).not.toContain('should not run'); }); it('should execute commands with || operator (success case)', async () => { const result = await shellTool.execute({ command: 'pwd || echo fallback' }); - expect(result).toContain(testCwd); - expect(result).not.toContain('fallback'); + expect(result.content).toContain(testCwd); + expect(result.content).not.toContain('fallback'); }); it('should execute commands with || operator (failure case)', async () => { @@ -258,36 +258,36 @@ describe('ShellTool', () => { const result = await shellTool.execute({ command: 'cat nonexistent.txt || echo fallback' }); - expect(result).toContain('No such file or directory'); - expect(result).toContain('fallback'); + expect(result.content).toContain('No such file or directory'); + expect(result.content).toContain('fallback'); }); it('should execute commands with ; operator', async () => { const result = await shellTool.execute({ command: 'echo first; echo second' }); - expect(result).toContain('first'); - expect(result).toContain('second'); + expect(result.content).toContain('first'); + expect(result.content).toContain('second'); }); it('should execute commands with pipe operator', async () => { const result = await shellTool.execute({ command: 'echo "hello world" | cat' }); - expect(result).toContain('hello world'); + expect(result.content).toContain('hello world'); }); it('should handle complex compound commands', async () => { const result = await shellTool.execute({ command: 'echo "line1\nline2\nline3" | head -n 2' }); - expect(result).toContain('line1'); - expect(result).toContain('line2'); - expect(result).not.toContain('line3'); + expect(result.content).toContain('line1'); + expect(result.content).toContain('line2'); + expect(result.content).not.toContain('line3'); }); it('should parse quoted strings in compound commands', async () => { const result = await shellTool.execute({ command: 'echo "hello && world" && echo success' }); - expect(result).toContain('hello && world'); - expect(result).toContain('success'); + expect(result.content).toContain('hello && world'); + expect(result.content).toContain('success'); }); }); }); \ No newline at end of file diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 8679bb36..c3e4c339 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand } from "../commands/ShellCommand"; import { Git } from "../git"; @@ -323,32 +323,35 @@ export class ShellTool implements Tool { } } - async execute(args: ShellToolParams): Promise { + async execute(args: ShellToolParams): Promise { const { command: commandStr } = args; if (!commandStr.trim()) { - return "Error: Empty command"; + return { content: "Error: Empty command" }; } // Check if running in Electron - if so, use real shell execution if (window.electron?.shell) { - return this.executeRealShell(commandStr); + const content = await this.executeRealShell(commandStr); + return { content }; } // Parse compound commands const commands = this.parseCompoundCommand(commandStr); if (commands.length === 0) { - return "Error: No command specified"; + return { content: "Error: No command specified" }; } // If it's a simple command (no operators), use the optimized single command execution if (commands.length === 1) { - return this.executeSimpleCommand(commands[0].command); + const content = await this.executeSimpleCommand(commands[0].command); + return { content }; } // Execute compound commands - return this.executeCompoundCommands(commands); + const content = await this.executeCompoundCommands(commands); + return { content }; } /** diff --git a/src/lib/tools/SkillTool.ts b/src/lib/tools/SkillTool.ts index a24ac6fb..f84870e0 100644 --- a/src/lib/tools/SkillTool.ts +++ b/src/lib/tools/SkillTool.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import type { Tool } from './Tool'; +import type { Tool, ToolResult } from './Tool'; import type { JSRuntimeFS } from '../JSRuntime'; import { findSkill, readSkillContent } from '../plugins'; @@ -24,7 +24,7 @@ export class SkillTool implements Tool { this.projectPath = projectPath; } - async execute(args: SkillParams): Promise { + async execute(args: SkillParams): Promise { const { name } = args; try { @@ -38,7 +38,8 @@ export class SkillTool implements Tool { // Read and return the skill content const content = await readSkillContent(this.fs, skill); - return `# Skill: ${skill.name} + return { + content: `# Skill: ${skill.name} **Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`} **Description**: ${skill.description} @@ -46,7 +47,8 @@ export class SkillTool implements Tool { --- -${content}`; +${content}` + }; } catch (error) { if (error instanceof Error) { throw error; diff --git a/src/lib/tools/TextEditorStrReplaceTool.test.ts b/src/lib/tools/TextEditorStrReplaceTool.test.ts index b439282d..f4f869ce 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.test.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.test.ts @@ -119,7 +119,7 @@ describe('TextEditorStrReplaceTool', () => { new_str: 'hello universe' }); - expect(result).toContain('String successfully replaced in src/test.ts'); + expect(result.content).toContain('String successfully replaced in src/test.ts'); expect(mockFS.getFileContent('/project/src/test.ts')).toContain('hello universe'); expect(mockFS.getFileContent('/project/src/test.ts')).not.toContain('hello world'); }); @@ -150,7 +150,7 @@ describe('TextEditorStrReplaceTool', () => { new_str: 'modified' }); - expect(result).toContain('String successfully replaced'); + expect(result.content).toContain('String successfully replaced'); expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content'); }); @@ -162,7 +162,7 @@ describe('TextEditorStrReplaceTool', () => { normalize_whitespace: true }); - expect(result).toContain('String successfully replaced'); + expect(result.content).toContain('String successfully replaced'); expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";'); }); }); \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index f8e312b4..1622ebeb 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -1,7 +1,7 @@ import { join } from "path-browserify"; import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; @@ -38,7 +38,7 @@ export class TextEditorStrReplaceTool implements Tool { + async execute(args: TextEditorStrReplaceParams): Promise { const { path, old_str, new_str, normalize_whitespace = true } = args; // Check write permissions @@ -184,7 +184,7 @@ export class TextEditorStrReplaceTool implements Tool { it('should handle viewing current directory', async () => { const result = await tool.execute({ path: '.' }); - expect(result).toContain('src/'); - expect(result).toContain('package.json'); - expect(result).toContain('.gitignore'); - expect(result).toContain('.git/'); // .git directory should now be visible + expect(result.content).toContain('src/'); + expect(result.content).toContain('package.json'); + expect(result.content).toContain('.gitignore'); + expect(result.content).toContain('.git/'); // .git directory should now be visible }); it('should handle viewing subdirectory', async () => { const result = await tool.execute({ path: 'src' }); - expect(result).toContain('index.ts'); + expect(result.content).toContain('index.ts'); }); it('should handle viewing a file', async () => { const result = await tool.execute({ path: 'src/index.ts' }); - expect(result).toBe('console.log("hello");'); + expect(result.content).toBe('console.log("hello");'); }); it('should handle line filtering', async () => { @@ -217,19 +217,19 @@ describe('TextEditorViewTool', () => { end_line: 1 }); - expect(result).toBe('console.log("hello");'); + expect(result.content).toBe('console.log("hello");'); }); it('should handle absolute paths', async () => { const result = await tool.execute({ path: '/tmp/uploaded-file.txt' }); - expect(result).toBe('This is an uploaded file'); + expect(result.content).toBe('This is an uploaded file'); }); it('should handle absolute directory paths', async () => { const result = await tool.execute({ path: '/tmp' }); - expect(result).toContain('uploaded-file.txt'); + expect(result.content).toContain('uploaded-file.txt'); }); it('should handle absolute paths with line filtering', async () => { @@ -239,97 +239,97 @@ describe('TextEditorViewTool', () => { end_line: 1 }); - expect(result).toBe('This is an uploaded file'); + expect(result.content).toBe('This is an uploaded file'); }); it('should detect binary files by extension and show placeholder', async () => { const result = await tool.execute({ path: 'logo.png' }); - expect(result).toContain('[Binary file: PNG file'); - expect(result).toContain('This appears to be a binary file and cannot be displayed as text.'); - expect(result).not.toContain('BINARY_CONTENT_PNG'); + expect(result.content).toContain('[Binary file: PNG file'); + expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); + expect(result.content).not.toContain('BINARY_CONTENT_PNG'); }); it('should detect PDF files as binary', async () => { const result = await tool.execute({ path: 'document.pdf' }); - expect(result).toContain('[Binary file: PDF file'); - expect(result).toContain('This appears to be a binary file and cannot be displayed as text.'); + expect(result.content).toContain('[Binary file: PDF file'); + expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); }); it('should detect binary files with absolute paths', async () => { const result = await tool.execute({ path: '/tmp/image.jpg' }); - expect(result).toContain('[Binary file: JPG file'); - expect(result).toContain('This appears to be a binary file and cannot be displayed as text.'); + expect(result.content).toContain('[Binary file: JPG file'); + expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); }); it('should show only project directories when viewing /projects', async () => { const result = await tool.execute({ path: '/projects' }); // Should show the project directories - expect(result).toContain('project1/'); - expect(result).toContain('project2/'); + expect(result.content).toContain('project1/'); + expect(result.content).toContain('project2/'); // Should NOT show the contents of the project directories (depth 1 only) - expect(result).not.toContain('package.json'); - expect(result).not.toContain('src/'); - expect(result).not.toContain('index.ts'); - expect(result).not.toContain('main.ts'); + expect(result.content).not.toContain('package.json'); + expect(result.content).not.toContain('src/'); + expect(result.content).not.toContain('index.ts'); + expect(result.content).not.toContain('main.ts'); }); it('should show only project directories when viewing /projects/', async () => { const result = await tool.execute({ path: '/projects/' }); // Should show the project directories - expect(result).toContain('project1/'); - expect(result).toContain('project2/'); + expect(result.content).toContain('project1/'); + expect(result.content).toContain('project2/'); // Should NOT show the contents of the project directories (depth 1 only) - expect(result).not.toContain('package.json'); - expect(result).not.toContain('src/'); - expect(result).not.toContain('index.ts'); - expect(result).not.toContain('main.ts'); + expect(result.content).not.toContain('package.json'); + expect(result.content).not.toContain('src/'); + expect(result.content).not.toContain('index.ts'); + expect(result.content).not.toContain('main.ts'); }); it('should show .git directory but not traverse its contents when viewing project root', async () => { const result = await tool.execute({ path: '/project' }); // Should show the .git directory - expect(result).toContain('.git/'); + expect(result.content).toContain('.git/'); // Should show "..." under .git instead of its contents - expect(result).toContain('...'); + expect(result.content).toContain('...'); // Should NOT show .git file contents - expect(result).not.toContain('config'); - expect(result).not.toContain('HEAD'); - expect(result).not.toContain('repositoryformatversion'); + expect(result.content).not.toContain('config'); + expect(result.content).not.toContain('HEAD'); + expect(result.content).not.toContain('repositoryformatversion'); // Should still show other directory contents normally - expect(result).toContain('src/'); - expect(result).toContain('package.json'); + expect(result.content).toContain('src/'); + expect(result.content).toContain('package.json'); }); it('should show .git contents when explicitly viewing .git directory', async () => { const result = await tool.execute({ path: '/project/.git' }); // Should show the .git file contents when explicitly requested - expect(result).toContain('config'); - expect(result).toContain('HEAD'); + expect(result.content).toContain('config'); + expect(result.content).toContain('HEAD'); // Should NOT show "..." when explicitly viewing .git - expect(result).not.toContain('...'); + expect(result.content).not.toContain('...'); }); it('should show .git contents when explicitly viewing .git with relative path', async () => { const result = await tool.execute({ path: '.git' }); // Should show the .git file contents when explicitly requested - expect(result).toContain('config'); - expect(result).toContain('HEAD'); + expect(result.content).toContain('config'); + expect(result.content).toContain('HEAD'); // Should NOT show "..." when explicitly viewing .git - expect(result).not.toContain('...'); + expect(result.content).not.toContain('...'); }); }); \ No newline at end of file diff --git a/src/lib/tools/TextEditorViewTool.ts b/src/lib/tools/TextEditorViewTool.ts index 9e9df058..4f55c36f 100644 --- a/src/lib/tools/TextEditorViewTool.ts +++ b/src/lib/tools/TextEditorViewTool.ts @@ -1,7 +1,7 @@ import { join } from "path-browserify"; import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; interface TextEditorViewParams { @@ -35,7 +35,7 @@ export class TextEditorViewTool implements Tool { this.projectsPath = options?.projectsPath || '/projects'; } - async execute(args: TextEditorViewParams): Promise { + async execute(args: TextEditorViewParams): Promise { const { path, start_line, end_line } = args; try { @@ -58,7 +58,7 @@ export class TextEditorViewTool implements Tool { const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash if (normalizedPath === this.projectsPath) { const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children - return tree; + return { content: tree }; } // Check if we're starting from a .git directory @@ -67,7 +67,7 @@ export class TextEditorViewTool implements Tool { // If it's a directory, generate a tree-like listing // Note: start_line and end_line are ignored for directories const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot); - return tree; + return { content: tree }; } // If it's a file, check if it's binary first @@ -75,7 +75,9 @@ export class TextEditorViewTool implements Tool { const stats = await this.fs.stat(absolutePath); const fileSize = this.formatFileSize(stats.size || 0); const fileExtension = this.getFileExtension(absolutePath); - return `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`; + return { + content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.` + }; } // If it's a text file, read and return its contents @@ -108,7 +110,7 @@ export class TextEditorViewTool implements Tool { content = lines.slice(startIdx, endIdx).join('\n'); } - return content; + return { content }; } catch (error) { throw new Error(String(error)); } diff --git a/src/lib/tools/TextEditorWriteTool.test.ts b/src/lib/tools/TextEditorWriteTool.test.ts index 17169b4f..a4b7c198 100644 --- a/src/lib/tools/TextEditorWriteTool.test.ts +++ b/src/lib/tools/TextEditorWriteTool.test.ts @@ -122,7 +122,7 @@ describe('TextEditorWriteTool', () => { file_text: 'console.log("test");' }); - expect(result).toContain('File successfully written to src/test.ts'); + expect(result.content).toContain('File successfully written to src/test.ts'); expect(mockFS.hasFile('/project/src/test.ts')).toBe(true); expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");'); }); @@ -140,7 +140,7 @@ describe('TextEditorWriteTool', () => { file_text: 'temporary content' }); - expect(result).toContain('File successfully written to /tmp/temp-file.txt'); + expect(result.content).toContain('File successfully written to /tmp/temp-file.txt'); expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true); expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content'); }); diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index 81a23ba5..48e2e8d3 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -1,7 +1,7 @@ import { join, dirname } from "path-browserify"; import { z } from "zod"; -import type { Tool } from "./Tool"; +import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; @@ -34,7 +34,7 @@ export class TextEditorWriteTool implements Tool { this.onFileChanged = options?.onFileChanged; } - async execute(args: TextEditorWriteParams): Promise { + async execute(args: TextEditorWriteParams): Promise { const { path, file_text } = args; // Check write permissions @@ -66,7 +66,7 @@ export class TextEditorWriteTool implements Tool { this.onFileChanged(path); } - return `File successfully written to ${path}`; + return { content: `File successfully written to ${path}` }; } catch (error) { throw new Error(String(error)); } diff --git a/src/lib/tools/Tool.ts b/src/lib/tools/Tool.ts index c0da6080..fa700cd0 100644 --- a/src/lib/tools/Tool.ts +++ b/src/lib/tools/Tool.ts @@ -1,7 +1,12 @@ import type z from "zod"; +export interface ToolResult { + content: string; + cost?: number; +} + export interface Tool { description: string; inputSchema?: z.ZodType; - execute(args: TParams): Promise; + execute(args: TParams): Promise; } diff --git a/src/lib/tools/ViewAvailableModelsTool.ts b/src/lib/tools/ViewAvailableModelsTool.ts index d7461d26..95b6edd2 100644 --- a/src/lib/tools/ViewAvailableModelsTool.ts +++ b/src/lib/tools/ViewAvailableModelsTool.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import type { Tool } from './Tool'; +import type { Tool, ToolResult } from './Tool'; interface ProviderModel { id: string; @@ -22,9 +22,9 @@ export class ViewAvailableModelsTool implements Tool> { private currentImageModel?: string, ) {} - async execute(): Promise { + async execute(): Promise { if (this.models.length === 0) { - return 'No AI models are currently available. Please configure at least one AI provider in Settings > AI.'; + return { content: 'No AI models are currently available. Please configure at least one AI provider in Settings > AI.' }; } // Filter image-capable models @@ -63,7 +63,7 @@ export class ViewAvailableModelsTool implements Tool> { if (filteredModels.length === 0) { output += 'No models found in configured providers.\n'; output += `Total models available: ${this.models.length} (none support image generation)\n`; - return output; + return { content: output }; } output += `Found ${filteredModels.length} models:\n\n`; @@ -82,6 +82,6 @@ export class ViewAvailableModelsTool implements Tool> { output += `Models marked with ⭐ are definite image generation models.\n`; - return output; + return { content: output }; } }