Tool result refactor (return an object instead of a string)

This commit is contained in:
Alex Gleason committed 2025-12-08 15:13:34 -06:00
1 parent 9c86ced552
commit f7b2d754e9
40 files changed
+315 -276

No files matched your search

+3 -1
View File
@@ -374,9 +374,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
]
});
const result = await tool.execute({ filter: 'error' });
await addMessage({
role: 'tool',
content: await tool.execute({ filter: 'error' }),
content: result.content,
tool_call_id: toolCallId,
});
+2 -2
View File
@@ -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);
}
}
}
+18 -6
View File
@@ -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}`);
+6 -6
View File
@@ -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 () => {
+5 -3
View File
@@ -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<void> {
this.esmUrl = esmUrl;
}
async execute(): Promise<string> {
async execute(): Promise<ToolResult> {
try {
// Build and write the project files
const result = await buildProject({
@@ -28,7 +28,9 @@ export class BuildProjectTool implements Tool<void> {
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)}`);
}
@@ -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<ConfigureImageGenerati
private models: ProviderModel[],
) {}
async execute(args: ConfigureImageGenerationParams): Promise<string> {
async execute(args: ConfigureImageGenerationParams): Promise<ToolResult> {
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<ConfigureImageGenerati
response += `\nThe generate_image tool is now available and ready to use. You can generate images by calling the generate_image tool with a detailed text prompt.`;
return response;
return { content: response };
}
}
+5 -3
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { ShakespeareAdapter } from "../deploy";
import type { NostrSigner } from "@nostrify/nostrify";
@@ -28,7 +28,7 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
this.projectId = projectId;
}
async execute(args: DeployProjectParams): Promise<string> {
async execute(args: DeployProjectParams): Promise<ToolResult> {
try {
// Use provided deployServer or default to shakespeare.wtf
const deployServer = args.deployServer || "shakespeare.wtf";
@@ -59,7 +59,9 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
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)}`);
}
+3 -3
View File
@@ -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 () => {
+3 -3
View File
@@ -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<GenerateImageParams> {
private corsProxy?: string,
) {}
async execute(args: GenerateImageParams): Promise<string> {
async execute(args: GenerateImageParams): Promise<ToolResult> {
const { prompt } = args;
try {
@@ -152,7 +152,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
// 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}`);
+12 -12
View File
@@ -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 () => {
+4 -4
View File
@@ -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<GitCommitParams> {
this.cwd = cwd;
}
async execute(args: GitCommitParams): Promise<string> {
async execute(args: GitCommitParams): Promise<ToolResult> {
const { message } = args;
try {
@@ -75,7 +75,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
});
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<GitCommitParams> {
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)}`);
}
+4 -3
View File
@@ -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<Record<string, unknown>> {
this.originalToolName = originalToolName;
}
async execute(args: Record<string, unknown>): Promise<string> {
return await this.client.callTool(this.originalToolName, args);
async execute(args: Record<string, unknown>): Promise<ToolResult> {
const content = await this.client.callTool(this.originalToolName, args);
return { content };
}
}
+8 -8
View File
@@ -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<NostrFetchEventParams> {
});
return;
}
// Reject nsec for security reasons
if (decoded.type === 'nsec') {
ctx.addIssue({
@@ -36,7 +36,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
});
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<NostrFetchEventParams> {
),
});
async execute(args: NostrFetchEventParams): Promise<string> {
async execute(args: NostrFetchEventParams): Promise<ToolResult> {
const { identifier } = args;
const decoded = nip19.decode(identifier);
@@ -169,12 +169,12 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
// 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 {
+5 -3
View File
@@ -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<NostrGenerateKindParams> {
});
}
async execute(args: NostrGenerateKindParams): Promise<string> {
async execute(args: NostrGenerateKindParams): Promise<ToolResult> {
const { range } = args;
try {
@@ -39,7 +39,9 @@ export class NostrGenerateKindTool implements Tool<NostrGenerateKindParams> {
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'}`);
}
+7 -7
View File
@@ -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
+3 -3
View File
@@ -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<NostrPublishEventsParams> {
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<string> {
async execute(args: NostrPublishEventsParams): Promise<ToolResult> {
const { events: partialEvents, relays } = args;
// Default relays if none provided
@@ -114,7 +114,7 @@ export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
})),
};
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 {
+3 -3
View File
@@ -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<NostrReadKindParams> {
});
}
async execute(args: NostrReadKindParams): Promise<string> {
async execute(args: NostrReadKindParams): Promise<ToolResult> {
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(
+3 -3
View File
@@ -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<NostrReadNipParams> {
});
}
async execute(args: NostrReadNipParams): Promise<string> {
async execute(args: NostrReadNipParams): Promise<ToolResult> {
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(
+3 -3
View File
@@ -1,4 +1,4 @@
import type { Tool } from "./Tool";
import type { Tool, ToolResult } from "./Tool";
import { NIPsClient } from "../NIPsClient";
export class NostrReadNipsIndexTool implements Tool<void> {
@@ -12,10 +12,10 @@ export class NostrReadNipsIndexTool implements Tool<void> {
});
}
async execute(): Promise<string> {
async execute(): Promise<ToolResult> {
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'}`);
}
+3 -3
View File
@@ -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<NostrReadProtocolParams> {
});
}
async execute(args: NostrReadProtocolParams): Promise<string> {
async execute(args: NostrReadProtocolParams): Promise<ToolResult> {
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'}`);
}
+3 -3
View File
@@ -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<NostrReadTagParams> {
});
}
async execute(args: NostrReadTagParams): Promise<string> {
async execute(args: NostrReadTagParams): Promise<ToolResult> {
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(
+13 -13
View File
@@ -70,8 +70,8 @@ describe('NpmAddPackageTool', () => {
expect.stringContaining('"lodash": "^4.17.21"'),
'utf8'
);
expect(result).toContain('✅ Successfully added [email protected]');
expect(result).toContain('Updated: package.json');
expect(result.content).toContain('✅ Successfully added [email protected]');
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 [email protected]');
expect(result.content).toContain('✅ Successfully added [email protected]');
});
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 [email protected] is already installed in dependencies.');
expect(result.content).toContain('ℹ️ Package [email protected] 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 [email protected]');
expect(result).toContain('Updated: package.json'); // Should not mention package-lock.json
expect(result.content).toContain('✅ Successfully added [email protected]');
expect(result.content).toContain('Updated: package.json'); // Should not mention package-lock.json
expect(mockFS.writeFile).toHaveBeenCalledTimes(1); // Only package.json should be written
});
});
+7 -5
View File
@@ -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<NpmAddPackageParams> {
this.cwd = cwd;
}
async execute(args: NpmAddPackageParams): Promise<string> {
async execute(args: NpmAddPackageParams): Promise<ToolResult> {
const { name, version, dev = false } = args;
try {
@@ -95,7 +95,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
// 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<NpmAddPackageParams> {
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<NpmAddPackageParams> {
// 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)}`);
}
+8 -8
View File
@@ -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');
});
});
+6 -4
View File
@@ -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<NpmRemovePackageParams> {
this.cwd = cwd;
}
async execute(args: NpmRemovePackageParams): Promise<string> {
async execute(args: NpmRemovePackageParams): Promise<ToolResult> {
const { name } = args;
try {
@@ -75,7 +75,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
}
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<NpmRemovePackageParams> {
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)}`);
}
+25 -25
View File
@@ -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)');
});
});
+6 -4
View File
@@ -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<ReadConsoleMessagesParams>
),
});
async execute(params: ReadConsoleMessagesParams): Promise<string> {
async execute(params: ReadConsoleMessagesParams): Promise<ToolResult> {
const { filter = 'all', limit = 50 } = params;
let messages = getConsoleMessages()
@@ -33,7 +33,7 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
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<ReadConsoleMessagesParams>
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}`
};
}
}
+15 -15
View File
@@ -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 () => {
+3 -3
View File
@@ -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<ReadWebpageParams> {
});
}
async execute(args: ReadWebpageParams): Promise<string> {
async execute(args: ReadWebpageParams): Promise<ToolResult> {
const { url } = args;
try {
@@ -111,7 +111,7 @@ export class ReadWebpageTool implements Tool<ReadWebpageParams> {
markdown,
].filter(Boolean).join("\n");
return result;
return { content: result };
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
+37 -37
View File
@@ -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');
});
});
});
+10 -7
View File
@@ -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<ShellToolParams> {
}
}
async execute(args: ShellToolParams): Promise<string> {
async execute(args: ShellToolParams): Promise<ToolResult> {
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 };
}
/**
+6 -4
View File
@@ -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<SkillParams> {
this.projectPath = projectPath;
}
async execute(args: SkillParams): Promise<string> {
async execute(args: SkillParams): Promise<ToolResult> {
const { name } = args;
try {
@@ -38,7 +38,8 @@ export class SkillTool implements Tool<SkillParams> {
// 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<SkillParams> {
---
${content}`;
${content}`
};
} catch (error) {
if (error instanceof Error) {
throw error;
@@ -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";');
});
});
+3 -3
View File
@@ -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<TextEditorStrReplaceParams
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorStrReplaceParams): Promise<string> {
async execute(args: TextEditorStrReplaceParams): Promise<ToolResult> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check write permissions
@@ -184,7 +184,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
}
return successMessage;
return { content: successMessage };
} catch (error) {
throw new Error(String(error));
}
+42 -42
View File
@@ -192,22 +192,22 @@ describe('TextEditorViewTool', () => {
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('...');
});
});
+8 -6
View File
@@ -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<TextEditorViewParams> {
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(args: TextEditorViewParams): Promise<string> {
async execute(args: TextEditorViewParams): Promise<ToolResult> {
const { path, start_line, end_line } = args;
try {
@@ -58,7 +58,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
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<TextEditorViewParams> {
// 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<TextEditorViewParams> {
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<TextEditorViewParams> {
content = lines.slice(startIdx, endIdx).join('\n');
}
return content;
return { content };
} catch (error) {
throw new Error(String(error));
}
+2 -2
View File
@@ -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');
});
+3 -3
View File
@@ -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<TextEditorWriteParams> {
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorWriteParams): Promise<string> {
async execute(args: TextEditorWriteParams): Promise<ToolResult> {
const { path, file_text } = args;
// Check write permissions
@@ -66,7 +66,7 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
this.onFileChanged(path);
}
return `File successfully written to ${path}`;
return { content: `File successfully written to ${path}` };
} catch (error) {
throw new Error(String(error));
}
+6 -1
View File
@@ -1,7 +1,12 @@
import type z from "zod";
export interface ToolResult {
content: string;
cost?: number;
}
export interface Tool<TParams> {
description: string;
inputSchema?: z.ZodType<TParams>;
execute(args: TParams): Promise<string>;
execute(args: TParams): Promise<ToolResult>;
}
+5 -5
View File
@@ -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<Record<string, never>> {
private currentImageModel?: string,
) {}
async execute(): Promise<string> {
async execute(): Promise<ToolResult> {
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<Record<string, never>> {
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<Record<string, never>> {
output += `Models marked with ⭐ are definite image generation models.\n`;
return output;
return { content: output };
}
}