diff --git a/package-lock.json b/package-lock.json index a26b96da..7391f7bb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "mkstack", "version": "0.0.0", "dependencies": { - "@ai-sdk/openai": "^1.3.23", + "@ai-sdk/openai-compatible": "^1.0.10", "@fontsource-variable/inter": "^5.2.6", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", @@ -46,7 +46,7 @@ "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", "@webcontainer/api": "^1.6.1", - "ai": "^4.3.19", + "ai": "^5.0.19", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -112,26 +112,42 @@ "dev": true, "license": "MIT" }, - "node_modules/@ai-sdk/openai": { - "version": "1.3.23", - "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-1.3.23.tgz", - "integrity": "sha512-86U7rFp8yacUAOE/Jz8WbGcwMCqWvjK33wk5DXkfnAOEn3mx2r7tNSJdjukQFZbAK97VMXGPPHxF+aEARDXRXQ==", + "node_modules/@ai-sdk/gateway": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-1.0.9.tgz", + "integrity": "sha512-kIfwunyUUwyBLg2KQcaRtjRQ1bDuJYPNIs4CNWaWPpMZ4SV5cRL1hLGMuX4bhfCJYDXHMGvJGLtUK6+iAJH2ZQ==", "license": "Apache-2.0", "dependencies": { - "@ai-sdk/provider": "1.1.3", - "@ai-sdk/provider-utils": "2.2.8" + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.4" }, "engines": { "node": ">=18" }, "peerDependencies": { - "zod": "^3.0.0" + "zod": "^3.25.76 || ^4" + } + }, + "node_modules/@ai-sdk/openai-compatible": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-1.0.10.tgz", + "integrity": "sha512-NInkII/DOvrMvO/mS0BxGUGi3r+wuXxbdzAh9k2gFGT+xVoP6OePikhogQu8qZuti8loUZJGYq3GJ/DCftOzhQ==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4" } }, "node_modules/@ai-sdk/provider": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", - "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-2.0.0.tgz", + "integrity": "sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA==", "license": "Apache-2.0", "dependencies": { "json-schema": "^0.4.0" @@ -141,61 +157,21 @@ } }, "node_modules/@ai-sdk/provider-utils": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", - "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-3.0.4.tgz", + "integrity": "sha512-/3Z6lfUp8r+ewFd9yzHkCmPlMOJUXup2Sx3aoUyrdXLhOmAfHRl6Z4lDbIdV0uvw/QYoBcVLJnvXN7ncYeS3uQ==", "license": "Apache-2.0", "dependencies": { - "@ai-sdk/provider": "1.1.3", - "nanoid": "^3.3.8", - "secure-json-parse": "^2.7.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "zod": "^3.23.8" - } - }, - "node_modules/@ai-sdk/react": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@ai-sdk/react/-/react-1.2.12.tgz", - "integrity": "sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/provider-utils": "2.2.8", - "@ai-sdk/ui-utils": "1.2.11", - "swr": "^2.2.5", - "throttleit": "2.1.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "react": "^18 || ^19 || ^19.0.0-rc", - "zod": "^3.23.8" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, - "node_modules/@ai-sdk/ui-utils": { - "version": "1.2.11", - "resolved": "https://registry.npmjs.org/@ai-sdk/ui-utils/-/ui-utils-1.2.11.tgz", - "integrity": "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/provider": "1.1.3", - "@ai-sdk/provider-utils": "2.2.8", + "@ai-sdk/provider": "2.0.0", + "@standard-schema/spec": "^1.0.0", + "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "engines": { "node": ">=18" }, "peerDependencies": { - "zod": "^3.23.8" + "zod": "^3.25.76 || ^4" } }, "node_modules/@alloc/quick-lru": { @@ -3206,6 +3182,12 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@standard-schema/spec": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", + "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==", + "license": "MIT" + }, "node_modules/@std/path": { "name": "@jsr/std__path", "version": "1.1.1", @@ -3676,12 +3658,6 @@ "@types/ms": "*" } }, - "node_modules/@types/diff-match-patch": { - "version": "1.0.36", - "resolved": "https://registry.npmjs.org/@types/diff-match-patch/-/diff-match-patch-1.0.36.tgz", - "integrity": "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==", - "license": "MIT" - }, "node_modules/@types/estree": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", @@ -4221,29 +4197,21 @@ } }, "node_modules/ai": { - "version": "4.3.19", - "resolved": "https://registry.npmjs.org/ai/-/ai-4.3.19.tgz", - "integrity": "sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q==", + "version": "5.0.19", + "resolved": "https://registry.npmjs.org/ai/-/ai-5.0.19.tgz", + "integrity": "sha512-I0yQO68Z1DdvjMc9be5scMYdsuBvpNneQDh6TUuUVlFXdCxAIm7yATnOaomfYTE2KaRDsrO+OSRPjJm4FSKioA==", "license": "Apache-2.0", "dependencies": { - "@ai-sdk/provider": "1.1.3", - "@ai-sdk/provider-utils": "2.2.8", - "@ai-sdk/react": "1.2.12", - "@ai-sdk/ui-utils": "1.2.11", - "@opentelemetry/api": "1.9.0", - "jsondiffpatch": "0.6.0" + "@ai-sdk/gateway": "1.0.9", + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.4", + "@opentelemetry/api": "1.9.0" }, "engines": { "node": ">=18" }, "peerDependencies": { - "react": "^18 || ^19 || ^19.0.0-rc", - "zod": "^3.23.8" - }, - "peerDependenciesMeta": { - "react": { - "optional": true - } + "zod": "^3.25.76 || ^4" } }, "node_modules/ajv": { @@ -5248,12 +5216,6 @@ "node": ">=0.3.1" } }, - "node_modules/diff-match-patch": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz", - "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==", - "license": "Apache-2.0" - }, "node_modules/diff3": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/diff3/-/diff3-0.0.3.tgz", @@ -5681,6 +5643,15 @@ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "license": "MIT" }, + "node_modules/eventsource-parser": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.5.tgz", + "integrity": "sha512-bSRG85ZrMdmWtm7qkF9He9TNRzc/Bm99gEJMaQoHJ9E6Kv9QBbsldh2oMj7iXmYNEAVvNgvv5vPorG6W+XtBhQ==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/expect-type": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.1.tgz", @@ -6760,35 +6731,6 @@ "dev": true, "license": "MIT" }, - "node_modules/jsondiffpatch": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/jsondiffpatch/-/jsondiffpatch-0.6.0.tgz", - "integrity": "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==", - "license": "MIT", - "dependencies": { - "@types/diff-match-patch": "^1.0.36", - "chalk": "^5.3.0", - "diff-match-patch": "^1.0.5" - }, - "bin": { - "jsondiffpatch": "bin/jsondiffpatch.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - } - }, - "node_modules/jsondiffpatch/node_modules/chalk": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz", - "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==", - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, "node_modules/jszip": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", @@ -9399,12 +9341,6 @@ "loose-envify": "^1.1.0" } }, - "node_modules/secure-json-parse": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", - "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", - "license": "BSD-3-Clause" - }, "node_modules/semver": { "version": "7.7.2", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", @@ -9809,19 +9745,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/swr": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.4.tgz", - "integrity": "sha512-bYd2lrhc+VarcpkgWclcUi92wYCpOgMws9Sd1hG1ntAu0NEy+14CbotuFjshBU2kt9rYj9TSmDcybpxpeTU1fg==", - "license": "MIT", - "dependencies": { - "dequal": "^2.0.3", - "use-sync-external-store": "^1.4.0" - }, - "peerDependencies": { - "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", @@ -9919,18 +9842,6 @@ "node": ">=0.8" } }, - "node_modules/throttleit": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz", - "integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/tiny-invariant": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", diff --git a/package.json b/package.json index 0a2dcda2..a81cd049 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" }, "dependencies": { - "@ai-sdk/openai": "^1.3.23", + "@ai-sdk/openai-compatible": "^1.0.10", "@fontsource-variable/inter": "^5.2.6", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", @@ -48,7 +48,7 @@ "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", "@webcontainer/api": "^1.6.1", - "ai": "^4.3.19", + "ai": "^5.0.19", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 0ff3dbf1..3aca36c4 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -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]; diff --git a/src/components/ai/AssistantContent.tsx b/src/components/ai/AssistantContent.tsx index 02c96463..7f46d53c 100644 --- a/src/components/ai/AssistantContent.tsx +++ b/src/components/ai/AssistantContent.tsx @@ -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 {String(item.toolName)} - {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 ? (
-                      {JSON.stringify(item.args, null, 2)}
+                      {JSON.stringify(item.input, null, 2)}
                     
) : null} diff --git a/src/components/ai/ToolResultContent.tsx b/src/components/ai/ToolResultContent.tsx index 604247a3..16806656 100644 --- a/src/components/ai/ToolResultContent.tsx +++ b/src/components/ai/ToolResultContent.tsx @@ -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 ( diff --git a/src/lib/tools/GitCommitTool.test.ts b/src/lib/tools/GitCommitTool.test.ts index 7e1f5ae1..b353f2c1 100644 --- a/src/lib/tools/GitCommitTool.test.ts +++ b/src/lib/tools/GitCommitTool.test.ts @@ -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: 'assistant@shakespeare.diy', }, }); - 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: 'john@example.com', }, }); - 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'); }); }); \ No newline at end of file diff --git a/src/lib/tools/GitCommitTool.ts b/src/lib/tools/GitCommitTool.ts index 9e61c712..20c8256b 100644 --- a/src/lib/tools/GitCommitTool.ts +++ b/src/lib/tools/GitCommitTool.ts @@ -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 { 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 { this.cwd = cwd; } - async execute(args: GitCommitParams): Promise { + async execute(args: GitCommitParams): Promise { const { message } = args; try { @@ -31,24 +31,12 @@ export class GitCommitTool implements Tool { 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 { }); 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 { 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)}`); } } } \ No newline at end of file diff --git a/src/lib/tools/NpmAddPackageTool.test.ts b/src/lib/tools/NpmAddPackageTool.test.ts index 8f97f52f..45e9130e 100644 --- a/src/lib/tools/NpmAddPackageTool.test.ts +++ b/src/lib/tools/NpmAddPackageTool.test.ts @@ -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 lodash@4.17.21'); + expect(result).toContain('✅ Successfully added lodash@4.17.21'); }); 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 lodash@4.17.20'); + expect(result).toContain('✅ Successfully added lodash@4.17.20'); }); 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 lodash@4.17.21 is already installed'); + expect(result).toContain('ℹ️ Package lodash@4.17.21 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'); }); }); \ No newline at end of file diff --git a/src/lib/tools/NpmAddPackageTool.ts b/src/lib/tools/NpmAddPackageTool.ts index d975b2df..7fa5cf14 100644 --- a/src/lib/tools/NpmAddPackageTool.ts +++ b/src/lib/tools/NpmAddPackageTool.ts @@ -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 { 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 { this.cwd = cwd; } - async execute(args: NpmAddPackageParams): Promise { + async execute(args: NpmAddPackageParams): Promise { const { name, version, dev = false } = args; try { @@ -43,13 +43,7 @@ export class NpmAddPackageTool implements Tool { 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 { 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 { 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 { 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 { 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)}`); } } diff --git a/src/lib/tools/NpmRemovePackageTool.test.ts b/src/lib/tools/NpmRemovePackageTool.test.ts index 0b673707..8bd49c62 100644 --- a/src/lib/tools/NpmRemovePackageTool.test.ts +++ b/src/lib/tools/NpmRemovePackageTool.test.ts @@ -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'); }); }); \ No newline at end of file diff --git a/src/lib/tools/NpmRemovePackageTool.ts b/src/lib/tools/NpmRemovePackageTool.ts index 3935fcb1..1b39a397 100644 --- a/src/lib/tools/NpmRemovePackageTool.ts +++ b/src/lib/tools/NpmRemovePackageTool.ts @@ -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 { 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 { this.cwd = cwd; } - async execute(args: NpmRemovePackageParams): Promise { + async execute(args: NpmRemovePackageParams): Promise { const { name } = args; try { @@ -39,13 +39,7 @@ export class NpmRemovePackageTool implements Tool { 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 { 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 { } 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 { 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)}`); } } } \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.test.ts b/src/lib/tools/TextEditorStrReplaceTool.test.ts index c7ceda52..cdabf289 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.test.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.test.ts @@ -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";'); }); }); \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index e0afb259..ded5f1b1 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -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 { + async execute(args: TextEditorStrReplaceParams): Promise { 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 { 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");'); }); }); \ No newline at end of file diff --git a/src/lib/tools/TextEditorViewTool.ts b/src/lib/tools/TextEditorViewTool.ts index 1c0ab5e3..af5386de 100644 --- a/src/lib/tools/TextEditorViewTool.ts +++ b/src/lib/tools/TextEditorViewTool.ts @@ -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 { 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 { this.cwd = cwd; } - async execute(args: TextEditorViewParams): Promise { + async execute(args: TextEditorViewParams): Promise { 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 { // 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 { // 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 { 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)); } } diff --git a/src/lib/tools/TextEditorWriteTool.test.ts b/src/lib/tools/TextEditorWriteTool.test.ts index aafd3d04..e5d065d8 100644 --- a/src/lib/tools/TextEditorWriteTool.test.ts +++ b/src/lib/tools/TextEditorWriteTool.test.ts @@ -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'); }); }); \ No newline at end of file diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index e07c0fed..e094386a 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -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 { 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 { this.cwd = cwd; } - async execute(args: TextEditorWriteParams): Promise { + async execute(args: TextEditorWriteParams): Promise { 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)); } } } \ No newline at end of file diff --git a/src/lib/tools/Tool.ts b/src/lib/tools/Tool.ts index cf70b698..cbb208e5 100644 --- a/src/lib/tools/Tool.ts +++ b/src/lib/tools/Tool.ts @@ -2,11 +2,6 @@ import type z from "zod"; export interface Tool { description: string; - parameters: z.ZodType; - execute(args: TParams): Promise; + inputSchema: z.ZodType; + execute(args: TParams): Promise; } - -export interface CallToolResult { - content: { type: "text"; text: string; }[]; - isError?: boolean; -} \ No newline at end of file