mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Upgrade ai-sdk to the latest version
This commit is contained in:
18 files changed
+211
-585
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
|
||||
import { ModelMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react';
|
||||
@@ -175,28 +176,16 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
}
|
||||
}, [messages, isLoading]);
|
||||
|
||||
const createAIChat = async (projectId: string, messages: CoreMessage[]) => {
|
||||
const createAIChat = async (projectId: string, messages: ModelMessage[]) => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
|
||||
// Create a custom fetch function for the AI provider
|
||||
const customFetch = async (url: string, options: RequestInit) => {
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...options.headers,
|
||||
'Authorization': `Bearer ${settings.apiKey}`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Import the appropriate provider based on the base URL
|
||||
const { createOpenAI } = await import('@ai-sdk/openai');
|
||||
const openai = createOpenAI({
|
||||
const openai = createOpenAICompatible({
|
||||
name: 'custom',
|
||||
baseURL: settings.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
fetch: settings.baseUrl.includes('openrouter.ai') ? customFetch : undefined,
|
||||
});
|
||||
|
||||
const provider = openai(settings.model);
|
||||
@@ -205,10 +194,9 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
return generateText({
|
||||
model: provider,
|
||||
messages,
|
||||
maxSteps: 100,
|
||||
onStepFinish(stepResult) {
|
||||
console.log(stepResult);
|
||||
addMessages(stepResult.response.messages);
|
||||
addMessages(stepResult.response.messages.map(msg => ({ ...msg, id: generateId() })));
|
||||
|
||||
// Update media session with current step info
|
||||
const lastMessage = stepResult.response.messages[stepResult.response.messages.length - 1];
|
||||
|
||||
@@ -41,28 +41,14 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Handle direct string results
|
||||
if (typeof toolResult.result === 'string') {
|
||||
if (toolResult.output.type === 'text') {
|
||||
return {
|
||||
result: toolResult.result,
|
||||
isError: toolResult.isError || false
|
||||
result: toolResult.output.value,
|
||||
isError: false
|
||||
};
|
||||
}
|
||||
|
||||
// Handle CallToolResult structure
|
||||
if (toolResult.result && typeof toolResult.result === 'object') {
|
||||
const callResult = toolResult.result as {
|
||||
content?: Array<{ type: string; text: string }>;
|
||||
isError?: boolean;
|
||||
};
|
||||
if (callResult.content && Array.isArray(callResult.content) && callResult.content[0]?.text) {
|
||||
return {
|
||||
result: callResult.content[0].text,
|
||||
isError: callResult.isError || false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { isError: toolResult.isError || false };
|
||||
return { isError: true };
|
||||
};
|
||||
// Handle string content (simple text messages)
|
||||
if (typeof content === 'string') {
|
||||
@@ -164,8 +150,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
);
|
||||
} else if (item.type === 'tool-call') {
|
||||
// Special rendering for text_editor_str_replace tool
|
||||
if (item.toolName === 'text_editor_str_replace' && item.args) {
|
||||
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
|
||||
if (item.toolName === 'text_editor_str_replace' && item.input) {
|
||||
const { path, old_str, new_str } = item.input as { path: string; old_str: string; new_str: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -181,8 +167,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for run_script tool
|
||||
if (item.toolName === 'run_script' && item.args) {
|
||||
const { script } = item.args as { script: string };
|
||||
if (item.toolName === 'run_script' && item.input) {
|
||||
const { script } = item.input as { script: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -196,8 +182,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_view tool
|
||||
if (item.toolName === 'text_editor_view' && item.args) {
|
||||
const { path } = item.args as { path: string };
|
||||
if (item.toolName === 'text_editor_view' && item.input) {
|
||||
const { path } = item.input as { path: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -211,8 +197,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_write tool
|
||||
if (item.toolName === 'text_editor_write' && item.args) {
|
||||
const { path, file_text } = item.args as { path: string; file_text: string };
|
||||
if (item.toolName === 'text_editor_write' && item.input) {
|
||||
const { path, file_text } = item.input as { path: string; file_text: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -227,8 +213,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for shell tool
|
||||
if (item.toolName === 'shell' && item.args) {
|
||||
const { command } = item.args as { command: string };
|
||||
if (item.toolName === 'shell' && item.input) {
|
||||
const { command } = item.input as { command: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -242,8 +228,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for npm_add_package tool
|
||||
if (item.toolName === 'npm_add_package' && item.args) {
|
||||
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
|
||||
if (item.toolName === 'npm_add_package' && item.input) {
|
||||
const { name, version, dev } = item.input as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -261,8 +247,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for npm_remove_package tool
|
||||
if (item.toolName === 'npm_remove_package' && item.args) {
|
||||
const { name } = item.args as { name: string };
|
||||
if (item.toolName === 'npm_remove_package' && item.input) {
|
||||
const { name } = item.input as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -278,8 +264,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for jsr_add_package tool
|
||||
if (item.toolName === 'jsr_add_package' && item.args) {
|
||||
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
|
||||
if (item.toolName === 'jsr_add_package' && item.input) {
|
||||
const { name, version, dev } = item.input as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -297,8 +283,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for jsr_remove_package tool
|
||||
if (item.toolName === 'jsr_remove_package' && item.args) {
|
||||
const { name } = item.args as { name: string };
|
||||
if (item.toolName === 'jsr_remove_package' && item.input) {
|
||||
const { name } = item.input as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -314,8 +300,8 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
}
|
||||
|
||||
// Special rendering for git_commit tool
|
||||
if (item.toolName === 'git_commit' && item.args) {
|
||||
const { message } = item.args as { message: string };
|
||||
if (item.toolName === 'git_commit' && item.input) {
|
||||
const { message } = item.input as { message: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
@@ -336,10 +322,10 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
<Code className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-mono text-sm break-all">{String(item.toolName)}</span>
|
||||
</div>
|
||||
{item.args && typeof item.args === 'object' && item.args !== null && Object.keys(item.args).length > 0 ? (
|
||||
{item.input && typeof item.input === 'object' && item.input !== null && Object.keys(item.input).length > 0 ? (
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
<pre className="overflow-hidden text-ellipsis">
|
||||
{JSON.stringify(item.args, null, 2)}
|
||||
{JSON.stringify(item.input, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -29,8 +29,13 @@ export const ToolResultContent = memo(({ content }: ToolResultContentProps) => {
|
||||
<>
|
||||
{content.map((item, index) => {
|
||||
if (item.type === 'tool-result') {
|
||||
const isError = item.isError || false;
|
||||
const result = typeof item.result === 'string' ? item.result : JSON.stringify(item.result);
|
||||
const isError = item.output.type === 'error-text' || item.output.type === 'error-json';
|
||||
const result = item.output.type === 'content'
|
||||
? item.output.value
|
||||
.map((part) => part.type === 'text' ? part.text : undefined)
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
: JSON.stringify(item.output);
|
||||
|
||||
return (
|
||||
<Card key={index} className="mt-2 bg-muted/50">
|
||||
|
||||
@@ -49,9 +49,9 @@ describe('GitCommitTool', () => {
|
||||
vi.mocked(git.getConfig).mockRejectedValue(new Error('Config not found'));
|
||||
});
|
||||
|
||||
it('should have correct description and parameters', () => {
|
||||
it('should have correct description and inputSchema', () => {
|
||||
expect(tool.description).toBe('Commit changes to git with a commit message. Automatically adds all unstaged files.');
|
||||
expect(tool.parameters).toBeDefined();
|
||||
expect(tool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
it('should successfully commit changes', async () => {
|
||||
@@ -82,9 +82,8 @@ describe('GitCommitTool', () => {
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully committed 2 files (abcd123)');
|
||||
expect(result.content[0].text).toContain('Add new feature');
|
||||
expect(result).toContain('✅ Successfully committed 2 files (abcd123)');
|
||||
expect(result).toContain('Add new feature');
|
||||
});
|
||||
|
||||
it('should handle empty commit message', async () => {
|
||||
@@ -94,10 +93,7 @@ describe('GitCommitTool', () => {
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await tool.execute({ message: '' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Commit message cannot be empty');
|
||||
await expect(tool.execute({ message: '' })).rejects.toThrow('❌ Commit message cannot be empty');
|
||||
});
|
||||
|
||||
it('should handle whitespace-only commit message', async () => {
|
||||
@@ -107,22 +103,15 @@ describe('GitCommitTool', () => {
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await tool.execute({ message: ' ' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Commit message cannot be empty');
|
||||
await expect(tool.execute({ message: ' ' })).rejects.toThrow('❌ Commit message cannot be empty');
|
||||
});
|
||||
|
||||
it('should handle not being in a git repository', async () => {
|
||||
// Mock .git directory does not exist
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await tool.execute({ message: 'Test commit' });
|
||||
|
||||
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Not a git repository');
|
||||
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git');
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Not a git repository');
|
||||
expect(result.content[0].text).toContain('git init');
|
||||
});
|
||||
|
||||
it('should handle commit with special characters in message', async () => {
|
||||
@@ -138,9 +127,8 @@ describe('GitCommitTool', () => {
|
||||
expect(git.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
message: specialMessage,
|
||||
}));
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully committed');
|
||||
expect(result.content[0].text).toContain(specialMessage);
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
expect(result).toContain(specialMessage);
|
||||
});
|
||||
|
||||
it('should handle multiline commit message', async () => {
|
||||
@@ -154,9 +142,8 @@ describe('GitCommitTool', () => {
|
||||
const result = await tool.execute({ message: multilineMessage });
|
||||
|
||||
expect(git.commit).toHaveBeenCalled();
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully committed');
|
||||
expect(result.content[0].text).toContain('Add new feature');
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
expect(result).toContain('Add new feature');
|
||||
});
|
||||
|
||||
it('should handle no changes to commit', async () => {
|
||||
@@ -171,8 +158,7 @@ describe('GitCommitTool', () => {
|
||||
|
||||
const result = await tool.execute({ message: 'Update documentation' });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('ℹ️ No changes to commit. Working tree is clean.');
|
||||
expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.');
|
||||
expect(git.commit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -185,11 +171,10 @@ describe('GitCommitTool', () => {
|
||||
|
||||
const result = await tool.execute({ message: 'Update documentation' });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('📝 Commit: "Update documentation"');
|
||||
expect(result.content[0].text).toContain('🔗 Hash:');
|
||||
expect(result.content[0].text).toContain('🌿 Branch:');
|
||||
expect(result.content[0].text).toContain('📊 Changes:');
|
||||
expect(result).toContain('📝 Commit: "Update documentation"');
|
||||
expect(result).toContain('🔗 Hash:');
|
||||
expect(result).toContain('🌿 Branch:');
|
||||
expect(result).toContain('📊 Changes:');
|
||||
});
|
||||
|
||||
it('should use git config when available', async () => {
|
||||
@@ -219,7 +204,7 @@ describe('GitCommitTool', () => {
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
});
|
||||
|
||||
it('should handle very long commit message', async () => {
|
||||
@@ -232,7 +217,6 @@ describe('GitCommitTool', () => {
|
||||
const longMessage = 'A'.repeat(1000); // Very long commit message
|
||||
const result = await tool.execute({ message: longMessage });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully committed');
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import git from 'isomorphic-git';
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface GitCommitParams {
|
||||
@@ -14,7 +14,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
|
||||
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files.";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
message: z.string().describe('Commit message text'),
|
||||
});
|
||||
|
||||
@@ -23,7 +23,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: GitCommitParams): Promise<CallToolResult> {
|
||||
async execute(args: GitCommitParams): Promise<string> {
|
||||
const { message } = args;
|
||||
|
||||
try {
|
||||
@@ -31,24 +31,12 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
try {
|
||||
await this.fs.stat(`${this.cwd}/.git`);
|
||||
} catch {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Not a git repository. Initialize git first with 'git init'.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Not a git repository. Initialize git first with 'git init'.`);
|
||||
}
|
||||
|
||||
// Validate commit message
|
||||
if (!message.trim()) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Commit message cannot be empty.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Commit message cannot be empty.`);
|
||||
}
|
||||
|
||||
// Get git status to see what files have changed
|
||||
@@ -66,13 +54,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
});
|
||||
|
||||
if (changedFiles.length === 0) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `ℹ️ No changes to commit. Working tree is clean.`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `ℹ️ No changes to commit. Working tree is clean.`;
|
||||
}
|
||||
|
||||
// Add all changed files to staging
|
||||
@@ -170,21 +152,9 @@ 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 {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `${summary}\n\n${details}`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `${summary}\n\n${details}`;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Error committing changes: ${String(error)}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Error committing changes: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,9 @@ describe('NpmAddPackageTool', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should have correct description and parameters', () => {
|
||||
it('should have correct description and inputSchema', () => {
|
||||
expect(tool.description).toBe('Safely add an npm package to the project in the current directory.');
|
||||
expect(tool.parameters).toBeDefined();
|
||||
expect(tool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
it('should successfully add a new package', async () => {
|
||||
@@ -60,8 +60,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect.stringContaining('"lodash": "^4.17.21"'),
|
||||
'utf8'
|
||||
);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully added [email protected]');
|
||||
expect(result).toContain('✅ Successfully added [email protected]');
|
||||
});
|
||||
|
||||
it('should add package with specific version', async () => {
|
||||
@@ -81,8 +80,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect.stringContaining('"lodash": "^4.17.20"'),
|
||||
'utf8'
|
||||
);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully added [email protected]');
|
||||
expect(result).toContain('✅ Successfully added [email protected]');
|
||||
});
|
||||
|
||||
it('should add dev dependency', async () => {
|
||||
@@ -113,8 +111,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0');
|
||||
expect(writtenPackageJson.dependencies?.typescript).toBeUndefined();
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('Development dependency');
|
||||
expect(result).toContain('Development dependency');
|
||||
});
|
||||
|
||||
it('should move package from dependencies to devDependencies', async () => {
|
||||
@@ -141,7 +138,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.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully added');
|
||||
});
|
||||
|
||||
it('should handle package already installed', async () => {
|
||||
@@ -162,26 +159,19 @@ describe('NpmAddPackageTool', () => {
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('ℹ️ Package [email protected] is already installed');
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Could not read package.json');
|
||||
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Could not read package.json');
|
||||
});
|
||||
|
||||
it('should handle invalid package.json', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Invalid package.json format');
|
||||
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Invalid package.json format');
|
||||
});
|
||||
|
||||
it('should handle npm registry errors', async () => {
|
||||
@@ -198,11 +188,7 @@ describe('NpmAddPackageTool', () => {
|
||||
statusText: 'Not Found'
|
||||
});
|
||||
|
||||
const result = await tool.execute({ name: 'nonexistent-package' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Could not fetch latest version');
|
||||
expect(result.content[0].text).toContain('HTTP 404: Not Found');
|
||||
await expect(tool.execute({ name: 'nonexistent-package' })).rejects.toThrow('❌ Could not fetch latest version');
|
||||
});
|
||||
|
||||
it('should sort dependencies alphabetically', async () => {
|
||||
@@ -228,6 +214,6 @@ describe('NpmAddPackageTool', () => {
|
||||
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
|
||||
|
||||
expect(dependencyKeys).toEqual(['axios', 'lodash', 'zlib']);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully added');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface NpmAddPackageParams {
|
||||
@@ -21,7 +21,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
|
||||
readonly description = "Safely add an npm package to the project in the current directory.";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
name: z.string().describe('Name of the npm package to add, eg "lodash"'),
|
||||
version: z.string().optional().describe("Version (optional)"),
|
||||
dev: z.boolean().optional().describe("If true, add to devDependencies (default: false)"),
|
||||
@@ -32,7 +32,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: NpmAddPackageParams): Promise<CallToolResult> {
|
||||
async execute(args: NpmAddPackageParams): Promise<string> {
|
||||
const { name, version, dev = false } = args;
|
||||
|
||||
try {
|
||||
@@ -43,13 +43,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
try {
|
||||
packageJsonContent = await this.fs.readFile(packageJsonPath, "utf8");
|
||||
} catch {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`);
|
||||
}
|
||||
|
||||
// Parse package.json
|
||||
@@ -57,13 +51,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
try {
|
||||
packageJson = JSON.parse(packageJsonContent);
|
||||
} catch {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Invalid package.json format. Could not parse JSON.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
|
||||
}
|
||||
|
||||
// Determine version to use
|
||||
@@ -72,13 +60,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
try {
|
||||
targetVersion = await this.fetchLatestVersion(name);
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Could not fetch latest version for ${name}. Package may not exist or npm registry is unavailable.\n\nError: ${String(error)}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Could not fetch latest version for ${name}. Package may not exist or npm registry is unavailable.\n\nError: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +71,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
if (packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
if (currentVersion === `^${targetVersion}`) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,21 +111,9 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
const updatedContent = JSON.stringify(packageJson, null, 2) + '\n';
|
||||
await this.fs.writeFile(packageJsonPath, updatedContent, "utf8");
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}`;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Error adding package ${name}: ${String(error)}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Error adding package ${name}: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,9 +25,9 @@ describe('NpmRemovePackageTool', () => {
|
||||
tool = new NpmRemovePackageTool(mockFS, '/test/project');
|
||||
});
|
||||
|
||||
it('should have correct description and parameters', () => {
|
||||
it('should have correct description and inputSchema', () => {
|
||||
expect(tool.description).toBe('Safely remove an npm package from the project in the current directory.');
|
||||
expect(tool.parameters).toBeDefined();
|
||||
expect(tool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
it('should successfully remove package from dependencies', async () => {
|
||||
@@ -51,8 +51,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
expect(writtenPackageJson.dependencies.lodash).toBeUndefined();
|
||||
expect(writtenPackageJson.dependencies.axios).toBe('^1.0.0');
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully removed lodash from dependencies');
|
||||
expect(result).toContain('✅ Successfully removed lodash from dependencies');
|
||||
});
|
||||
|
||||
it('should successfully remove package from devDependencies', async () => {
|
||||
@@ -78,8 +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.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('✅ Successfully removed typescript from devDependencies');
|
||||
expect(result).toContain('✅ Successfully removed typescript from devDependencies');
|
||||
});
|
||||
|
||||
it('should remove empty dependencies object', async () => {
|
||||
@@ -99,7 +97,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
const writtenPackageJson = JSON.parse(writtenContent);
|
||||
|
||||
expect(writtenPackageJson.dependencies).toBeUndefined();
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should remove empty devDependencies object', async () => {
|
||||
@@ -123,7 +121,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
expect(writtenPackageJson.devDependencies).toBeUndefined();
|
||||
expect(writtenPackageJson.dependencies.react).toBe('^18.0.0');
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should handle package not found', async () => {
|
||||
@@ -140,26 +138,19 @@ describe('NpmRemovePackageTool', () => {
|
||||
const result = await tool.execute({ name: 'nonexistent-package' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('ℹ️ Package nonexistent-package was not found');
|
||||
expect(result).toContain('ℹ️ Package nonexistent-package was not found');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Could not read package.json');
|
||||
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Could not read package.json');
|
||||
});
|
||||
|
||||
it('should handle invalid package.json', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Invalid package.json format');
|
||||
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Invalid package.json format');
|
||||
});
|
||||
|
||||
it('should sort remaining dependencies alphabetically', async () => {
|
||||
@@ -182,7 +173,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
|
||||
|
||||
expect(dependencyKeys).toEqual(['axios', 'zlib']);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should include version information in success message', async () => {
|
||||
@@ -198,7 +189,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result.content[0].text).toContain('🏷️ Version: ^4.17.21');
|
||||
expect(result.content[0].text).toContain('📁 Removed from: dependencies');
|
||||
expect(result).toContain('🏷️ Version: ^4.17.21');
|
||||
expect(result).toContain('📁 Removed from: dependencies');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface NpmRemovePackageParams {
|
||||
@@ -19,7 +19,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
|
||||
readonly description = "Safely remove an npm package from the project in the current directory.";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
name: z.string().describe("Name of the npm package to remove"),
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: NpmRemovePackageParams): Promise<CallToolResult> {
|
||||
async execute(args: NpmRemovePackageParams): Promise<string> {
|
||||
const { name } = args;
|
||||
|
||||
try {
|
||||
@@ -39,13 +39,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
try {
|
||||
packageJsonContent = await this.fs.readFile(packageJsonPath, "utf8");
|
||||
} catch {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`);
|
||||
}
|
||||
|
||||
// Parse package.json
|
||||
@@ -53,13 +47,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
try {
|
||||
packageJson = JSON.parse(packageJsonContent);
|
||||
} catch {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Invalid package.json format. Could not parse JSON.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
|
||||
}
|
||||
|
||||
// Check if package exists in dependencies or devDependencies
|
||||
@@ -87,13 +75,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
}
|
||||
|
||||
if (!foundIn) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.`;
|
||||
}
|
||||
|
||||
// Sort remaining dependencies alphabetically
|
||||
@@ -117,21 +99,9 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
const updatedContent = JSON.stringify(packageJson, null, 2) + '\n';
|
||||
await this.fs.writeFile(packageJsonPath, updatedContent, "utf8");
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `✅ 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`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
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`;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Error removing package ${name}: ${String(error)}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Error removing package ${name}: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,33 +116,25 @@ describe('TextEditorStrReplaceTool', () => {
|
||||
new_str: 'hello universe'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('String successfully replaced in src/test.ts');
|
||||
expect(result).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');
|
||||
});
|
||||
|
||||
it('should handle string not found', async () => {
|
||||
const result = await tool.execute({
|
||||
await expect(tool.execute({
|
||||
path: 'src/test.ts',
|
||||
old_str: 'nonexistent string',
|
||||
new_str: 'replacement'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('The string to replace was not found in src/test.ts');
|
||||
})).rejects.toThrow('The string to replace was not found in src/test.ts');
|
||||
});
|
||||
|
||||
it('should reject absolute paths with helpful error message', async () => {
|
||||
const result = await tool.execute({
|
||||
await expect(tool.execute({
|
||||
path: '/absolute/path/test.ts',
|
||||
old_str: 'old',
|
||||
new_str: 'new'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Absolute paths are not supported');
|
||||
expect(result.content[0].text).toContain('Current working directory: /project');
|
||||
})).rejects.toThrow('❌ Absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should handle whitespace normalization', async () => {
|
||||
@@ -153,7 +145,7 @@ describe('TextEditorStrReplaceTool', () => {
|
||||
normalize_whitespace: true
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result).toContain('String successfully replaced');
|
||||
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { join } from "@std/path";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface TextEditorStrReplaceParams {
|
||||
@@ -17,7 +17,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
|
||||
readonly description = "Replace a string in a file with a new string";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
path: z.string().describe('Path to the file, eg "src/index.ts"'),
|
||||
old_str: z.string().describe("The string to replace"),
|
||||
new_str: z.string().describe("The new string to insert"),
|
||||
@@ -31,18 +31,12 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: TextEditorStrReplaceParams): Promise<CallToolResult> {
|
||||
async execute(args: TextEditorStrReplaceParams): Promise<string> {
|
||||
const { path, old_str, new_str, normalize_whitespace = true } = args;
|
||||
|
||||
// Check for absolute paths and provide helpful error
|
||||
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`);
|
||||
}
|
||||
|
||||
// Ban editing dependencies in package.json
|
||||
@@ -61,14 +55,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
old_str.includes(key) || new_str.includes(key)
|
||||
)
|
||||
) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text:
|
||||
`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,13 +123,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
errorMessage += `\n\nNote: Whitespace normalization was applied. Try setting normalize_whitespace to false if the replacement still fails.`;
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: errorMessage,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Count occurrences (simple string counting)
|
||||
@@ -184,21 +165,9 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: successMessage,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return successMessage;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: String(error),
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,26 +145,23 @@ describe('TextEditorViewTool', () => {
|
||||
it('should handle viewing current directory without ignore library errors', async () => {
|
||||
const result = await tool.execute({ path: '.' });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('src/');
|
||||
expect(result.content[0].text).toContain('package.json');
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
// .git should be filtered out by gitignore, but .gitignore should be present
|
||||
expect(result.content[0].text).toContain('.gitignore');
|
||||
expect(result.content[0].text).not.toContain('.git/'); // Check for .git directory specifically
|
||||
expect(result).toContain('.gitignore');
|
||||
expect(result).not.toContain('.git/'); // Check for .git directory specifically
|
||||
});
|
||||
|
||||
it('should handle viewing subdirectory', async () => {
|
||||
const result = await tool.execute({ path: 'src' });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('index.ts');
|
||||
expect(result).toContain('index.ts');
|
||||
});
|
||||
|
||||
it('should handle viewing a file', async () => {
|
||||
const result = await tool.execute({ path: 'src/index.ts' });
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toBe('console.log("hello");');
|
||||
expect(result).toBe('console.log("hello");');
|
||||
});
|
||||
|
||||
it('should handle line filtering', async () => {
|
||||
@@ -174,7 +171,6 @@ describe('TextEditorViewTool', () => {
|
||||
end_line: 1
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toBe('console.log("hello");');
|
||||
expect(result).toBe('console.log("hello");');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { join } from "@std/path";
|
||||
import ignore from "ignore";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface TextEditorViewParams {
|
||||
@@ -17,7 +17,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
|
||||
readonly description = "View the contents of a text file or directory";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
path: z.string().describe(
|
||||
'Path of the file or directory to view, eg "src/index.ts" or "src/"',
|
||||
),
|
||||
@@ -34,19 +34,13 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: TextEditorViewParams): Promise<CallToolResult> {
|
||||
async execute(args: TextEditorViewParams): Promise<string> {
|
||||
const { path, start_line, end_line } = args;
|
||||
|
||||
try {
|
||||
// Check for absolute paths and provide helpful error
|
||||
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`);
|
||||
}
|
||||
|
||||
const absolutePath = join(this.cwd, path);
|
||||
@@ -58,13 +52,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);
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: tree,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return tree;
|
||||
}
|
||||
|
||||
// If it's a file, read and return its contents
|
||||
@@ -76,43 +64,19 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
|
||||
// Validate line numbers first
|
||||
if (start_line !== undefined && start_line < 1) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: "Error: start_line must be >= 1",
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error("Error: start_line must be >= 1");
|
||||
}
|
||||
|
||||
if (end_line !== undefined && end_line < 1) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: "Error: end_line must be >= 1",
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error("Error: end_line must be >= 1");
|
||||
}
|
||||
|
||||
if (start_line !== undefined && end_line !== undefined && start_line > end_line) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: "Error: start_line cannot be greater than end_line",
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error("Error: start_line cannot be greater than end_line");
|
||||
}
|
||||
|
||||
if (start_line !== undefined && start_line > lines.length) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `Error: start_line ${start_line} is beyond the end of the file (${lines.length} lines)`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`Error: start_line ${start_line} is beyond the end of the file (${lines.length} lines)`);
|
||||
}
|
||||
|
||||
const startIdx = start_line !== undefined ? start_line - 1 : 0;
|
||||
@@ -121,21 +85,9 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
content = lines.slice(startIdx, endIdx).join('\n');
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: content,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return content;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: String(error),
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(String(error));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -119,30 +119,22 @@ describe('TextEditorWriteTool', () => {
|
||||
file_text: 'console.log("test");'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.content[0].text).toContain('File successfully written to src/test.ts');
|
||||
expect(result).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");');
|
||||
});
|
||||
|
||||
it('should reject absolute paths with helpful error message', async () => {
|
||||
const result = await tool.execute({
|
||||
await expect(tool.execute({
|
||||
path: '/absolute/path/test.ts',
|
||||
file_text: 'test content'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('❌ Absolute paths are not supported');
|
||||
expect(result.content[0].text).toContain('Current working directory: /project');
|
||||
})).rejects.toThrow('❌ Absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should reject package.json writes', async () => {
|
||||
const result = await tool.execute({
|
||||
await expect(tool.execute({
|
||||
path: 'package.json',
|
||||
file_text: '{"name": "test"}'
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('🔒 Direct writes to package.json are disallowed');
|
||||
})).rejects.toThrow('🔒 Direct writes to package.json are disallowed');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { join, dirname } from "@std/path";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool, CallToolResult } from "./Tool";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface TextEditorWriteParams {
|
||||
@@ -15,7 +15,7 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
|
||||
|
||||
readonly description = "Create or overwrite a file with new content";
|
||||
|
||||
readonly parameters = z.object({
|
||||
readonly inputSchema = z.object({
|
||||
path: z.string().describe(
|
||||
'Path of the file to write, eg "src/index.ts"',
|
||||
),
|
||||
@@ -27,53 +27,28 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: TextEditorWriteParams): Promise<CallToolResult> {
|
||||
async execute(args: TextEditorWriteParams): Promise<string> {
|
||||
const { path, file_text } = args;
|
||||
|
||||
// Check for absolute paths and provide helpful error
|
||||
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`);
|
||||
}
|
||||
|
||||
if (
|
||||
path === "package.json" || path.endsWith("/package.json") ||
|
||||
path.endsWith("\\package.json")
|
||||
) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text:
|
||||
`🔒 Direct writes to package.json are disallowed.\n👉 Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`,
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(`🔒 Direct writes to package.json are disallowed.\n👉 Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`);
|
||||
}
|
||||
|
||||
try {
|
||||
const absolutePath = join(this.cwd, path);
|
||||
await this.fs.mkdir(dirname(absolutePath), { recursive: true });
|
||||
await this.fs.writeFile(absolutePath, file_text, "utf8");
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `File successfully written to ${path}`,
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
return `File successfully written to ${path}`;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: String(error),
|
||||
}],
|
||||
isError: true,
|
||||
};
|
||||
throw new Error(String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,6 @@ import type z from "zod";
|
||||
|
||||
export interface Tool<TParams> {
|
||||
description: string;
|
||||
parameters: z.ZodType<TParams>;
|
||||
execute(args: TParams): Promise<CallToolResult>;
|
||||
inputSchema: z.ZodType<TParams>;
|
||||
execute(args: TParams): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface CallToolResult {
|
||||
content: { type: "text"; text: string; }[];
|
||||
isError?: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user