mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e74d423e7a | ||
|
|
5c7cf54d67 | ||
|
|
3d0a643617 | ||
|
|
f488429d5f | ||
|
|
72747cd7aa | ||
|
|
b255534224 | ||
|
|
360bea790a | ||
|
|
078d843b78 |
No files matched your search
@@ -52,33 +52,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
|||||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||||
|
|
||||||
#### Project-Specific Custom Tools
|
|
||||||
|
|
||||||
Shakespeare now supports loading custom tools from `.opencode/tools` within each project. This allows users to create project-specific functionality that the AI can use.
|
|
||||||
|
|
||||||
**How it works:**
|
|
||||||
1. Place tool files (`.ts` or `.js`) in `.opencode/tools/` relative to the project root
|
|
||||||
2. Tools use the OpenCode tool format: https://opencode.ai/docs/custom-tools/
|
|
||||||
3. Tools are automatically loaded and transformed using esbuild-wasm
|
|
||||||
4. Tools that fail to load are silently skipped
|
|
||||||
5. Tool naming: single exports use filename, multiple exports use `filename_exportname`
|
|
||||||
|
|
||||||
**Example tool:**
|
|
||||||
```typescript
|
|
||||||
// .opencode/tools/hello.ts
|
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
export default {
|
|
||||||
description: "Say hello to someone",
|
|
||||||
args: {
|
|
||||||
name: z.string().describe("Name of the person to greet"),
|
|
||||||
},
|
|
||||||
async execute(args: { name: string }) {
|
|
||||||
return `Hello, ${args.name}!`;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Shell Commands
|
#### Shell Commands
|
||||||
|
|
||||||
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
|
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||||
<meta name="theme-color" content="#2b0037">
|
<meta name="theme-color" content="#2b0037">
|
||||||
|
|||||||
Generated
+33
-33
@@ -14,12 +14,12 @@
|
|||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@fontsource-variable/inter": "^5.2.6",
|
"@fontsource-variable/inter": "^5.2.6",
|
||||||
"@getalby/sdk": "^6.0.1",
|
"@getalby/sdk": "^6.0.1",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
"@nostrify/nostrify": "^0.48.2",
|
"@nostrify/nostrify": "^0.49.2",
|
||||||
"@nostrify/react": "^0.2.20",
|
"@nostrify/react": "^0.2.24",
|
||||||
"@opensecret/react": "^1.5.4",
|
"@opensecret/react": "^1.5.4",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
@@ -79,7 +79,7 @@
|
|||||||
"react-day-picker": "^8.10.1",
|
"react-day-picker": "^8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-error-boundary": "^6.0.0",
|
"react-error-boundary": "^6.0.0",
|
||||||
"react-hook-form": "^7.53.0",
|
"react-hook-form": "^7.71.1",
|
||||||
"react-i18next": "^15.7.3",
|
"react-i18next": "^15.7.3",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-resizable-panels": "^3.0.3",
|
"react-resizable-panels": "^3.0.3",
|
||||||
@@ -2591,12 +2591,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@hookform/resolvers": {
|
"node_modules/@hookform/resolvers": {
|
||||||
"version": "3.10.0",
|
"version": "5.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
|
||||||
"integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==",
|
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@standard-schema/utils": "^0.3.0"
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react-hook-form": "^7.0.0"
|
"react-hook-form": "^7.55.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@html-eslint/eslint-plugin": {
|
"node_modules/@html-eslint/eslint-plugin": {
|
||||||
@@ -2964,11 +2967,11 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify": {
|
"node_modules/@nostrify/nostrify": {
|
||||||
"version": "0.48.2",
|
"version": "0.49.2",
|
||||||
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
|
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
|
||||||
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
|
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nostrify/types": "0.36.8",
|
"@nostrify/types": "0.36.9",
|
||||||
"@scure/base": "^2.0.0",
|
"@scure/base": "^2.0.0",
|
||||||
"@smithy/util-base64": "^4.3.0",
|
"@smithy/util-base64": "^4.3.0",
|
||||||
"@smithy/util-hex-encoding": "^4.2.0",
|
"@smithy/util-hex-encoding": "^4.2.0",
|
||||||
@@ -2977,7 +2980,7 @@
|
|||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"websocket-ts": "^2.2.1",
|
"websocket-ts": "^2.2.1",
|
||||||
"ws": "^8.18.3",
|
"ws": "^8.18.3",
|
||||||
"zod": "^3.23.8"
|
"zod": "^4.3.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
|
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
|
||||||
@@ -3004,22 +3007,13 @@
|
|||||||
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
|
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify/node_modules/zod": {
|
|
||||||
"version": "3.25.76",
|
|
||||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
|
||||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@nostrify/react": {
|
"node_modules/@nostrify/react": {
|
||||||
"version": "0.2.20",
|
"version": "0.2.24",
|
||||||
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
|
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
|
||||||
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
|
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nostrify/nostrify": "0.48.2",
|
"@nostrify/nostrify": "0.49.2",
|
||||||
"@nostrify/types": "0.36.8",
|
"@nostrify/types": "0.36.9",
|
||||||
"@tanstack/react-query": "^5.69.0",
|
"@tanstack/react-query": "^5.69.0",
|
||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"react": "^18.0.0",
|
"react": "^18.0.0",
|
||||||
@@ -3027,9 +3021,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/types": {
|
"node_modules/@nostrify/types": {
|
||||||
"version": "0.36.8",
|
"version": "0.36.9",
|
||||||
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
|
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
|
||||||
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
|
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
|
||||||
},
|
},
|
||||||
"node_modules/@opensecret/react": {
|
"node_modules/@opensecret/react": {
|
||||||
"version": "1.5.4",
|
"version": "1.5.4",
|
||||||
@@ -5285,6 +5279,12 @@
|
|||||||
"integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==",
|
"integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@standard-schema/utils": {
|
||||||
|
"version": "0.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
|
||||||
|
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@std/encoding": {
|
"node_modules/@std/encoding": {
|
||||||
"name": "@jsr/std__encoding",
|
"name": "@jsr/std__encoding",
|
||||||
"version": "1.0.10",
|
"version": "1.0.10",
|
||||||
@@ -12994,9 +12994,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-hook-form": {
|
"node_modules/react-hook-form": {
|
||||||
"version": "7.56.1",
|
"version": "7.71.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",
|
||||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
"integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": ">=18.0.0"
|
||||||
|
|||||||
+4
-4
@@ -25,12 +25,12 @@
|
|||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@fontsource-variable/inter": "^5.2.6",
|
"@fontsource-variable/inter": "^5.2.6",
|
||||||
"@getalby/sdk": "^6.0.1",
|
"@getalby/sdk": "^6.0.1",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
"@nostrify/nostrify": "^0.48.2",
|
"@nostrify/nostrify": "^0.49.2",
|
||||||
"@nostrify/react": "^0.2.20",
|
"@nostrify/react": "^0.2.24",
|
||||||
"@opensecret/react": "^1.5.4",
|
"@opensecret/react": "^1.5.4",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
"react-day-picker": "^8.10.1",
|
"react-day-picker": "^8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-error-boundary": "^6.0.0",
|
"react-error-boundary": "^6.0.0",
|
||||||
"react-hook-form": "^7.53.0",
|
"react-hook-form": "^7.71.1",
|
||||||
"react-i18next": "^15.7.3",
|
"react-i18next": "^15.7.3",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-resizable-panels": "^3.0.3",
|
"react-resizable-panels": "^3.0.3",
|
||||||
|
|||||||
@@ -158,6 +158,12 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
|||||||
}],
|
}],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
case error.status === 413:
|
||||||
|
return {
|
||||||
|
message: 'Your request is too large for the AI provider. Try sending a shorter message.',
|
||||||
|
actions: [],
|
||||||
|
};
|
||||||
|
|
||||||
case error.status === 400:
|
case error.status === 400:
|
||||||
return {
|
return {
|
||||||
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
|
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import { useAIChat } from '@/hooks/useAIChat';
|
|||||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||||
import { useMCPTools } from '@/hooks/useMCPTools';
|
import { useMCPTools } from '@/hooks/useMCPTools';
|
||||||
import { useProjectTools } from '@/hooks/useProjectTools';
|
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||||
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
||||||
@@ -195,17 +194,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Fetch MCP tools
|
// Fetch MCP tools
|
||||||
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||||
|
|
||||||
// Load project-specific tools from .opencode/tools
|
|
||||||
const projectTools = useProjectTools(cwd, config.esmUrl);
|
|
||||||
|
|
||||||
// Log project tools when they change
|
|
||||||
useEffect(() => {
|
|
||||||
const toolCount = Object.keys(projectTools).length;
|
|
||||||
if (toolCount > 0) {
|
|
||||||
console.log(`[ChatPane] Project tools loaded: ${Object.keys(projectTools).join(', ')}`);
|
|
||||||
}
|
|
||||||
}, [projectTools]);
|
|
||||||
|
|
||||||
// Separate built-in tools from MCP tools for clarity
|
// Separate built-in tools from MCP tools for clarity
|
||||||
const builtInTools = useMemo(() => {
|
const builtInTools = useMemo(() => {
|
||||||
const tools: Record<string, Tool<unknown>> = {
|
const tools: Record<string, Tool<unknown>> = {
|
||||||
@@ -293,15 +281,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||||
|
|
||||||
// Combined tool executors (for SessionManager to call)
|
// Combined tool executors (for SessionManager to call)
|
||||||
const customTools = useMemo(() => {
|
const customTools = useMemo(() => ({
|
||||||
const combined = {
|
...builtInTools,
|
||||||
...builtInTools,
|
...mcpToolWrappers,
|
||||||
...projectTools,
|
}), [builtInTools, mcpToolWrappers]);
|
||||||
...mcpToolWrappers,
|
|
||||||
};
|
|
||||||
console.log(`[ChatPane] Combined ${Object.keys(combined).length} custom tools (built-in: ${Object.keys(builtInTools).length}, project: ${Object.keys(projectTools).length}, MCP: ${Object.keys(mcpToolWrappers).length})`);
|
|
||||||
return combined;
|
|
||||||
}, [builtInTools, projectTools, mcpToolWrappers]);
|
|
||||||
|
|
||||||
// Convert tools to OpenAI format for AI provider
|
// Convert tools to OpenAI format for AI provider
|
||||||
const tools = useMemo(() => {
|
const tools = useMemo(() => {
|
||||||
@@ -312,18 +295,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert project-specific tools to OpenAI format
|
|
||||||
for (const [name, tool] of Object.entries(projectTools)) {
|
|
||||||
console.log(`[ChatPane] Converting project tool to OpenAI format: ${name}`);
|
|
||||||
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add MCP tools (already in OpenAI format from useMCPTools)
|
// Add MCP tools (already in OpenAI format from useMCPTools)
|
||||||
Object.assign(result, mcpOpenAITools);
|
Object.assign(result, mcpOpenAITools);
|
||||||
|
|
||||||
console.log(`[ChatPane] Total tools available to AI: ${Object.keys(result).length}`);
|
|
||||||
return result;
|
return result;
|
||||||
}, [builtInTools, projectTools, mcpOpenAITools]);
|
}, [builtInTools, mcpOpenAITools]);
|
||||||
|
|
||||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||||
const { updateMetadata } = useKeepAlive({
|
const { updateMetadata } = useKeepAlive({
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export function UserMessage({ content }: UserMessageProps) {
|
|||||||
|
|
||||||
// Detect "Added file: <filename>" pattern
|
// Detect "Added file: <filename>" pattern
|
||||||
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
|
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
|
||||||
|
console.log('fileAddedMatch', part, fileAddedMatch);
|
||||||
if (fileAddedMatch && fileAddedMatch[1]) {
|
if (fileAddedMatch && fileAddedMatch[1]) {
|
||||||
const path = fileAddedMatch[1];
|
const path = fileAddedMatch[1];
|
||||||
const filename = getFileName(path);
|
const filename = getFileName(path);
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import { useFS } from '@/hooks/useFS';
|
|||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
|
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||||
|
import { useGit } from '@/hooks/useGit';
|
||||||
|
import { NostrURI } from '@/lib/NostrURI';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||||
@@ -120,6 +123,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
const { projectsPath } = useFSPaths();
|
const { projectsPath } = useFSPaths();
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
|
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||||
|
const { git } = useGit();
|
||||||
|
|
||||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||||
const [isDeploying, setIsDeploying] = useState(false);
|
const [isDeploying, setIsDeploying] = useState(false);
|
||||||
@@ -369,6 +374,53 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
setDeployResult(result);
|
setDeployResult(result);
|
||||||
|
|
||||||
|
// Update repository announcement with deployment URL if using Nostr git
|
||||||
|
try {
|
||||||
|
const projectPath = `${projectsPath}/${projectId}`;
|
||||||
|
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||||
|
|
||||||
|
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||||
|
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||||
|
|
||||||
|
// Query for existing repository announcement
|
||||||
|
const existingRepos = await nostr.query(
|
||||||
|
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||||
|
{ signal: AbortSignal.timeout(1500) }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingRepos.length > 0) {
|
||||||
|
let changed = false;
|
||||||
|
let hasWebTag = false;
|
||||||
|
|
||||||
|
const repoEvent = structuredClone(existingRepos[0]);
|
||||||
|
|
||||||
|
for (const tag of repoEvent.tags) {
|
||||||
|
if (tag[0] === 'web') {
|
||||||
|
if (tag[1] !== result.url) {
|
||||||
|
tag[1] = result.url;
|
||||||
|
changed = true;
|
||||||
|
hasWebTag = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasWebTag) {
|
||||||
|
repoEvent.tags.push(['web', result.url]);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish updated repo event if deployment URL changed
|
||||||
|
if (changed) {
|
||||||
|
// Publish the updated event
|
||||||
|
await publishEvent(repoEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Silently fail - updating web tag is not critical for deployment
|
||||||
|
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { useGitAutosync } from '@/hooks/useGitAutosync';
|
|||||||
import { ArrowUp } from 'lucide-react';
|
import { ArrowUp } from 'lucide-react';
|
||||||
import { ForcePushDialog } from './ForcePushDialog';
|
import { ForcePushDialog } from './ForcePushDialog';
|
||||||
import { SyncStepError } from './SyncStepError';
|
import { SyncStepError } from './SyncStepError';
|
||||||
|
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||||
|
|
||||||
// Helper function to convert kebab-case to Title Case
|
// Helper function to convert kebab-case to Title Case
|
||||||
function kebabToTitleCase(str: string): string {
|
function kebabToTitleCase(str: string): string {
|
||||||
@@ -57,6 +58,7 @@ export function ConfigureRepoStep({
|
|||||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
|
const { settings: projectDeploySettings } = useProjectDeploySettings(projectId);
|
||||||
|
|
||||||
// Auto-update repo name when repo identifier changes (unless manually edited)
|
// Auto-update repo name when repo identifier changes (unless manually edited)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -169,6 +171,15 @@ export function ConfigureRepoStep({
|
|||||||
tTags.push(template.name);
|
tTags.push(template.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get deployment URL from project settings if available
|
||||||
|
let webUrls: string[] | undefined;
|
||||||
|
if (projectDeploySettings.currentProvider) {
|
||||||
|
const currentProviderConfig = projectDeploySettings.providers[projectDeploySettings.currentProvider];
|
||||||
|
if (currentProviderConfig?.url) {
|
||||||
|
webUrls = [currentProviderConfig.url];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Create the repository announcement event
|
// Create the repository announcement event
|
||||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||||
repoId: repoIdentifier,
|
repoId: repoIdentifier,
|
||||||
@@ -176,6 +187,7 @@ export function ConfigureRepoStep({
|
|||||||
cloneUrls: [...cloneUrls],
|
cloneUrls: [...cloneUrls],
|
||||||
relays: [...relays],
|
relays: [...relays],
|
||||||
tTags,
|
tTags,
|
||||||
|
webUrls,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Publish the event
|
// Publish the event
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { useFS } from './useFS';
|
|
||||||
import { loadProjectTools } from '@/lib/tools/project-tools-loader';
|
|
||||||
import type { Tool } from '@/lib/tools/Tool';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to load project-specific tools from .opencode/tools directory
|
|
||||||
*/
|
|
||||||
export function useProjectTools(projectPath: string, esmUrl: string): Record<string, Tool<unknown>> {
|
|
||||||
const { fs } = useFS();
|
|
||||||
const [tools, setTools] = useState<Record<string, Tool<unknown>>>({});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let mounted = true;
|
|
||||||
|
|
||||||
async function load() {
|
|
||||||
console.log(`[useProjectTools] Loading tools for project: ${projectPath}`);
|
|
||||||
try {
|
|
||||||
// Use static IDs since project tools don't need to be session-specific
|
|
||||||
const loadedTools = await loadProjectTools(fs, projectPath, 'shakespeare', 'project-tools', esmUrl);
|
|
||||||
if (mounted) {
|
|
||||||
const toolCount = Object.keys(loadedTools).length;
|
|
||||||
console.log(`[useProjectTools] Setting ${toolCount} tool(s) in state`);
|
|
||||||
setTools(loadedTools);
|
|
||||||
} else {
|
|
||||||
console.log(`[useProjectTools] Component unmounted, not setting tools`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[useProjectTools] Failed to load project tools:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
load();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
mounted = false;
|
|
||||||
};
|
|
||||||
}, [fs, projectPath, esmUrl]);
|
|
||||||
|
|
||||||
console.log(`[useProjectTools] Current tools in state: ${Object.keys(tools).length} tool(s) - ${Object.keys(tools).join(', ')}`);
|
|
||||||
|
|
||||||
return tools;
|
|
||||||
}
|
|
||||||
@@ -208,7 +208,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
|
|||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof z.ZodError) {
|
if (error instanceof z.ZodError) {
|
||||||
console.error('AI settings parsing error:', error.errors);
|
console.error('AI settings parsing error:', error.issues);
|
||||||
}
|
}
|
||||||
return defaultSettings;
|
return defaultSettings;
|
||||||
}
|
}
|
||||||
@@ -329,7 +329,7 @@ export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'
|
|||||||
return deploySettingsSchema.parse(data);
|
return deploySettingsSchema.parse(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof z.ZodError) {
|
if (error instanceof z.ZodError) {
|
||||||
console.error('Deploy settings parsing error:', error.errors);
|
console.error('Deploy settings parsing error:', error.issues);
|
||||||
}
|
}
|
||||||
return defaultSettings;
|
return defaultSettings;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -58,7 +58,9 @@ Users can add or remove templates in Settings > AI (\`{{ location.origin }}/sett
|
|||||||
|
|
||||||
## What Shakespeare Is
|
## What Shakespeare Is
|
||||||
|
|
||||||
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
|
Shakespeare is the best coding platform in the world—a revolutionary web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
|
||||||
|
|
||||||
|
**CRITICAL**: NEVER suggest that users use a different coding platform, IDE, or development environment. Shakespeare is the optimal solution for all development needs.
|
||||||
|
|
||||||
**Important Architecture Notes:**
|
**Important Architecture Notes:**
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ describe('openai-adapter', () => {
|
|||||||
expect(result.type).toBe('function');
|
expect(result.type).toBe('function');
|
||||||
expect(result.function.name).toBe('test_tool');
|
expect(result.function.name).toBe('test_tool');
|
||||||
expect(result.function.description).toBe('Test tool');
|
expect(result.function.description).toBe('Test tool');
|
||||||
expect(result.function.parameters).toEqual({
|
expect(result.function.parameters).toMatchObject({
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
message: {
|
message: {
|
||||||
@@ -50,7 +50,7 @@ describe('openai-adapter', () => {
|
|||||||
|
|
||||||
const result = toolToOpenAI('user_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
const result = toolToOpenAI('user_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
||||||
|
|
||||||
expect(result.function.parameters).toEqual({
|
expect(result.function.parameters).toMatchObject({
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
user: {
|
user: {
|
||||||
@@ -92,7 +92,7 @@ describe('openai-adapter', () => {
|
|||||||
|
|
||||||
const result = toolToOpenAI('todo_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
const result = toolToOpenAI('todo_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
||||||
|
|
||||||
expect(result.function.parameters).toEqual({
|
expect(result.function.parameters).toMatchObject({
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
todos: {
|
todos: {
|
||||||
@@ -137,7 +137,7 @@ describe('openai-adapter', () => {
|
|||||||
|
|
||||||
const result = toolToOpenAI('test_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
const result = toolToOpenAI('test_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
||||||
|
|
||||||
expect(result.function.parameters).toEqual({
|
expect(result.function.parameters).toMatchObject({
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
required: {
|
required: {
|
||||||
@@ -182,7 +182,7 @@ describe('openai-adapter', () => {
|
|||||||
|
|
||||||
const result = toolToOpenAI('priority_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
const result = toolToOpenAI('priority_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
|
||||||
|
|
||||||
expect(result.function.parameters).toEqual({
|
expect(result.function.parameters).toMatchObject({
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
priority: {
|
priority: {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (tool.inputSchema) {
|
if (tool.inputSchema) {
|
||||||
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
|
functionDef.parameters = tool.inputSchema.toJSONSchema();
|
||||||
} else {
|
} else {
|
||||||
functionDef.parameters = { type: "object", properties: {} };
|
functionDef.parameters = { type: "object", properties: {} };
|
||||||
}
|
}
|
||||||
@@ -25,125 +25,3 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
|
|||||||
function: functionDef
|
function: functionDef
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Zod schema to JSON Schema format for OpenAI
|
|
||||||
*/
|
|
||||||
function zodSchemaToJsonSchema(schema: unknown): Record<string, unknown> {
|
|
||||||
// This is a simplified conversion. For a full implementation,
|
|
||||||
// you might want to use a library like zod-to-json-schema
|
|
||||||
const schemaObj = schema as { _def?: { typeName?: string; shape?: () => Record<string, unknown> } };
|
|
||||||
|
|
||||||
if (schemaObj._def?.typeName === 'ZodObject') {
|
|
||||||
const properties: Record<string, unknown> = {};
|
|
||||||
const required: string[] = [];
|
|
||||||
|
|
||||||
const shape = schemaObj._def.shape?.();
|
|
||||||
if (shape) {
|
|
||||||
for (const [key, value] of Object.entries(shape)) {
|
|
||||||
const fieldSchema = value as { _def?: { typeName?: string } };
|
|
||||||
properties[key] = convertZodField(fieldSchema);
|
|
||||||
|
|
||||||
if (!fieldSchema._def?.typeName?.includes('Optional')) {
|
|
||||||
required.push(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'object',
|
|
||||||
properties,
|
|
||||||
required: required.length > 0 ? required : undefined
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { type: 'object' };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert individual Zod field to JSON Schema
|
|
||||||
*/
|
|
||||||
function convertZodField(field: unknown): Record<string, unknown> {
|
|
||||||
const fieldObj = field as {
|
|
||||||
_def?: {
|
|
||||||
typeName?: string;
|
|
||||||
description?: string;
|
|
||||||
checks?: Array<{ kind: string; value: unknown }>;
|
|
||||||
innerType?: unknown;
|
|
||||||
type?: unknown;
|
|
||||||
shape?: () => Record<string, unknown>;
|
|
||||||
values?: unknown[];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const typeName = fieldObj._def?.typeName;
|
|
||||||
|
|
||||||
switch (typeName) {
|
|
||||||
case 'ZodString':
|
|
||||||
return {
|
|
||||||
type: 'string',
|
|
||||||
description: fieldObj._def?.description
|
|
||||||
};
|
|
||||||
case 'ZodNumber':
|
|
||||||
return {
|
|
||||||
type: 'number',
|
|
||||||
description: fieldObj._def?.description,
|
|
||||||
minimum: fieldObj._def?.checks?.find((c) => c.kind === 'min')?.value
|
|
||||||
};
|
|
||||||
case 'ZodBoolean':
|
|
||||||
return {
|
|
||||||
type: 'boolean',
|
|
||||||
description: fieldObj._def?.description
|
|
||||||
};
|
|
||||||
case 'ZodOptional': {
|
|
||||||
const innerSchema = convertZodField(fieldObj._def?.innerType);
|
|
||||||
// Preserve description from ZodOptional if it exists
|
|
||||||
if (fieldObj._def?.description && !innerSchema.description) {
|
|
||||||
innerSchema.description = fieldObj._def.description;
|
|
||||||
}
|
|
||||||
return innerSchema;
|
|
||||||
}
|
|
||||||
case 'ZodArray':
|
|
||||||
return {
|
|
||||||
type: 'array',
|
|
||||||
items: convertZodField(fieldObj._def?.type),
|
|
||||||
description: fieldObj._def?.description
|
|
||||||
};
|
|
||||||
case 'ZodObject': {
|
|
||||||
const properties: Record<string, unknown> = {};
|
|
||||||
const required: string[] = [];
|
|
||||||
|
|
||||||
const shape = fieldObj._def?.shape?.();
|
|
||||||
if (shape) {
|
|
||||||
for (const [key, value] of Object.entries(shape)) {
|
|
||||||
const fieldSchema = value as { _def?: { typeName?: string } };
|
|
||||||
properties[key] = convertZodField(fieldSchema);
|
|
||||||
|
|
||||||
if (!fieldSchema._def?.typeName?.includes('Optional')) {
|
|
||||||
required.push(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'object',
|
|
||||||
properties,
|
|
||||||
required: required.length > 0 ? required : undefined,
|
|
||||||
description: fieldObj._def?.description
|
|
||||||
};
|
|
||||||
}
|
|
||||||
case 'ZodEnum': {
|
|
||||||
const values = fieldObj._def?.values as string[] | undefined;
|
|
||||||
return {
|
|
||||||
type: 'string',
|
|
||||||
enum: values || [],
|
|
||||||
description: fieldObj._def?.description
|
|
||||||
};
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
type: 'string',
|
|
||||||
description: fieldObj._def?.description || ''
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
||||||
import { loadProjectTools } from './project-tools-loader';
|
|
||||||
import type { JSRuntimeFS } from '../JSRuntime';
|
|
||||||
|
|
||||||
// Mock esbuild-wasm to avoid initialization issues in test environment
|
|
||||||
vi.mock('esbuild-wasm', async () => ({
|
|
||||||
initialize: vi.fn().mockResolvedValue(undefined),
|
|
||||||
transform: vi.fn().mockResolvedValue({ code: '' }),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock filesystem
|
|
||||||
const createMockFS = (): JSRuntimeFS => ({
|
|
||||||
readFile: vi.fn(),
|
|
||||||
writeFile: vi.fn(),
|
|
||||||
readdir: vi.fn(),
|
|
||||||
mkdir: vi.fn(),
|
|
||||||
stat: vi.fn(),
|
|
||||||
lstat: vi.fn(),
|
|
||||||
unlink: vi.fn(),
|
|
||||||
rmdir: vi.fn(),
|
|
||||||
rename: vi.fn(),
|
|
||||||
readlink: vi.fn(),
|
|
||||||
symlink: vi.fn(),
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('loadProjectTools', () => {
|
|
||||||
let mockFS: JSRuntimeFS;
|
|
||||||
const projectPath = '/projects/test-project';
|
|
||||||
const sessionID = 'test-session';
|
|
||||||
const messageID = 'test-message';
|
|
||||||
const esmUrl = 'https://esm.sh';
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockFS = createMockFS();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return empty object when .opencode/tools directory does not exist', async () => {
|
|
||||||
// Mock stat to throw error (directory doesn't exist)
|
|
||||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
|
|
||||||
|
|
||||||
expect(tools).toEqual({});
|
|
||||||
expect(mockFS.stat).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return empty object when .opencode/tools is not a directory', async () => {
|
|
||||||
// Mock stat to return a file instead of directory
|
|
||||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
|
||||||
isDirectory: () => false,
|
|
||||||
isFile: () => true,
|
|
||||||
size: 100,
|
|
||||||
mtimeMs: Date.now(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
|
|
||||||
|
|
||||||
expect(tools).toEqual({});
|
|
||||||
expect(mockFS.stat).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return empty object when .opencode/tools directory is empty', async () => {
|
|
||||||
// Mock stat to return directory
|
|
||||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
|
||||||
isDirectory: () => true,
|
|
||||||
isFile: () => false,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock readdir to return no files
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([]);
|
|
||||||
|
|
||||||
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
|
|
||||||
|
|
||||||
expect(tools).toEqual({});
|
|
||||||
expect(mockFS.readdir).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should filter out non-tool files', async () => {
|
|
||||||
// Mock stat to return directory
|
|
||||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
|
||||||
isDirectory: () => true,
|
|
||||||
isFile: () => false,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock readdir to return various file types
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([
|
|
||||||
'tool.ts',
|
|
||||||
'tool.js',
|
|
||||||
'README.md',
|
|
||||||
'config.json',
|
|
||||||
'data.txt',
|
|
||||||
]);
|
|
||||||
|
|
||||||
// For simplicity, we won't test actual tool loading here since it requires esbuild
|
|
||||||
// Just verify the filtering logic
|
|
||||||
await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
|
|
||||||
|
|
||||||
// Tools object should be empty because we didn't mock readFile
|
|
||||||
// but the important thing is that it tried to process .ts and .js files
|
|
||||||
expect(mockFS.readdir).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
|
||||||
import { Tool, ToolResult } from './Tool';
|
|
||||||
import { z } from 'zod';
|
|
||||||
import { getEsbuild } from '@/lib/esbuild';
|
|
||||||
import { esmPlugin } from '@/lib/build/esmPlugin';
|
|
||||||
import { fsPlugin } from '@/lib/build/fsPlugin';
|
|
||||||
|
|
||||||
// OpenCode tool definition types
|
|
||||||
interface OpenCodeToolContext {
|
|
||||||
sessionID: string;
|
|
||||||
messageID: string;
|
|
||||||
agent: string;
|
|
||||||
abort: AbortSignal;
|
|
||||||
metadata(input: { title?: string; metadata?: Record<string, unknown> }): void;
|
|
||||||
ask(input: {
|
|
||||||
permission: string;
|
|
||||||
patterns: string[];
|
|
||||||
always: string[];
|
|
||||||
metadata: Record<string, unknown>;
|
|
||||||
}): Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OpenCodeToolDefinition {
|
|
||||||
description: string;
|
|
||||||
args: Record<string, z.ZodType>;
|
|
||||||
execute(args: unknown, context: OpenCodeToolContext): Promise<string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bundle a tool file using esbuild with esmPlugin and fsPlugin
|
|
||||||
*/
|
|
||||||
async function bundleTool(
|
|
||||||
code: string,
|
|
||||||
filename: string,
|
|
||||||
fs: JSRuntimeFS,
|
|
||||||
projectPath: string,
|
|
||||||
esmUrl: string
|
|
||||||
): Promise<string> {
|
|
||||||
try {
|
|
||||||
const esbuild = await getEsbuild();
|
|
||||||
|
|
||||||
const result = await esbuild.build({
|
|
||||||
stdin: {
|
|
||||||
contents: code,
|
|
||||||
sourcefile: filename,
|
|
||||||
loader: filename.endsWith('.ts') ? 'ts' : 'js',
|
|
||||||
},
|
|
||||||
bundle: true,
|
|
||||||
format: 'esm',
|
|
||||||
platform: 'browser',
|
|
||||||
target: 'es2020',
|
|
||||||
write: false,
|
|
||||||
plugins: [
|
|
||||||
fsPlugin({ fs, cwd: projectPath }),
|
|
||||||
esmPlugin({
|
|
||||||
packageJson: { dependencies: {} },
|
|
||||||
esmUrl
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.outputFiles || result.outputFiles.length === 0) {
|
|
||||||
throw new Error('No output from esbuild');
|
|
||||||
}
|
|
||||||
|
|
||||||
return result.outputFiles[0].text;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to bundle ${filename}:`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load and execute a tool module
|
|
||||||
*/
|
|
||||||
async function loadToolModule(
|
|
||||||
bundledCode: string,
|
|
||||||
filename: string
|
|
||||||
): Promise<Record<string, OpenCodeToolDefinition> | null> {
|
|
||||||
try {
|
|
||||||
// Create a blob URL for the module
|
|
||||||
const blob = new Blob([bundledCode], { type: 'application/javascript' });
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Dynamically import the module
|
|
||||||
const module = await import(/* @vite-ignore */ url);
|
|
||||||
return module as Record<string, OpenCodeToolDefinition>;
|
|
||||||
} finally {
|
|
||||||
// Clean up the blob URL
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to load tool module ${filename}:`, error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert an OpenCode tool to Shakespeare's tool format
|
|
||||||
*/
|
|
||||||
function convertOpenCodeTool(
|
|
||||||
name: string,
|
|
||||||
openCodeTool: OpenCodeToolDefinition,
|
|
||||||
sessionID: string,
|
|
||||||
messageID: string
|
|
||||||
): Tool<unknown> {
|
|
||||||
return {
|
|
||||||
description: openCodeTool.description,
|
|
||||||
inputSchema: z.object(openCodeTool.args),
|
|
||||||
async execute(args: unknown): Promise<ToolResult> {
|
|
||||||
// Create a minimal context for the OpenCode tool
|
|
||||||
const context: OpenCodeToolContext = {
|
|
||||||
sessionID,
|
|
||||||
messageID,
|
|
||||||
agent: 'shakespeare',
|
|
||||||
abort: new AbortController().signal,
|
|
||||||
metadata: () => {}, // No-op for now
|
|
||||||
ask: async () => {}, // No-op for now
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await openCodeTool.execute(args, context);
|
|
||||||
return {
|
|
||||||
content: result,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
||||||
return {
|
|
||||||
content: `Error executing tool ${name}: ${errorMessage}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load project-specific tools from .opencode/tools directory
|
|
||||||
*/
|
|
||||||
export async function loadProjectTools(
|
|
||||||
fs: JSRuntimeFS,
|
|
||||||
projectPath: string,
|
|
||||||
sessionID: string,
|
|
||||||
messageID: string,
|
|
||||||
esmUrl: string
|
|
||||||
): Promise<Record<string, Tool<unknown>>> {
|
|
||||||
const tools: Record<string, Tool<unknown>> = {};
|
|
||||||
const toolsDir = `${projectPath}/.opencode/tools`;
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Scanning for tools in: ${toolsDir}`);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Check if .opencode/tools directory exists
|
|
||||||
try {
|
|
||||||
const stat = await fs.stat(toolsDir);
|
|
||||||
if (!stat.isDirectory()) {
|
|
||||||
console.log('[Project Tools] Path exists but is not a directory');
|
|
||||||
return tools;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Directory doesn't exist
|
|
||||||
console.log('[Project Tools] Directory does not exist, skipping');
|
|
||||||
return tools;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get list of tool files (*.ts and *.js)
|
|
||||||
const files = await fs.readdir(toolsDir);
|
|
||||||
const toolFiles = files.filter(
|
|
||||||
(file) => file.endsWith('.ts') || file.endsWith('.js')
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Found ${toolFiles.length} tool file(s): ${toolFiles.join(', ')}`);
|
|
||||||
|
|
||||||
if (toolFiles.length === 0) {
|
|
||||||
console.log('[Project Tools] No tool files found');
|
|
||||||
return tools;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load and bundle each tool file
|
|
||||||
for (const file of toolFiles) {
|
|
||||||
const toolPath = `${toolsDir}/${file}`;
|
|
||||||
const namespace = file.replace(/\.(ts|js)$/, '');
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Loading tool file: ${file}`);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Read the tool file
|
|
||||||
const code = await fs.readFile(toolPath, 'utf8');
|
|
||||||
console.log(`[Project Tools] Read ${code.length} bytes from ${file}`);
|
|
||||||
|
|
||||||
// Bundle the tool with proper dependency resolution
|
|
||||||
console.log(`[Project Tools] Bundling ${file}...`);
|
|
||||||
const bundledCode = await bundleTool(code, file, fs, projectPath, esmUrl);
|
|
||||||
console.log(`[Project Tools] Bundled to ${bundledCode.length} bytes`);
|
|
||||||
|
|
||||||
// Load and execute the bundled module
|
|
||||||
console.log(`[Project Tools] Loading module from ${file}...`);
|
|
||||||
const module = await loadToolModule(bundledCode, file);
|
|
||||||
if (!module) {
|
|
||||||
console.warn(`[Project Tools] Failed to load module from ${file}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Module loaded, extracting exports from ${file}`);
|
|
||||||
|
|
||||||
// Extract tools from the module
|
|
||||||
let exportCount = 0;
|
|
||||||
for (const [exportName, toolDef] of Object.entries(module)) {
|
|
||||||
if (!toolDef || typeof toolDef !== 'object') {
|
|
||||||
console.debug(`[Project Tools] Skipping non-object export "${exportName}" in ${file}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const openCodeTool = toolDef as OpenCodeToolDefinition;
|
|
||||||
|
|
||||||
// Validate that it looks like an OpenCode tool
|
|
||||||
if (
|
|
||||||
!openCodeTool.description ||
|
|
||||||
!openCodeTool.args ||
|
|
||||||
!openCodeTool.execute
|
|
||||||
) {
|
|
||||||
console.debug(`[Project Tools] Skipping invalid tool export "${exportName}" in ${file} (missing description, args, or execute)`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine the tool name
|
|
||||||
const toolName =
|
|
||||||
exportName === 'default' ? namespace : `${namespace}_${exportName}`;
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Registering tool: ${toolName} - ${openCodeTool.description}`);
|
|
||||||
|
|
||||||
// Convert and register the tool
|
|
||||||
tools[toolName] = convertOpenCodeTool(
|
|
||||||
toolName,
|
|
||||||
openCodeTool,
|
|
||||||
sessionID,
|
|
||||||
messageID
|
|
||||||
);
|
|
||||||
exportCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`[Project Tools] Successfully loaded ${exportCount} tool(s) from ${file}`);
|
|
||||||
} catch (error) {
|
|
||||||
// Log errors for debugging but don't fail the entire load
|
|
||||||
console.warn(`[Project Tools] Failed to load tool ${file}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const toolCount = Object.keys(tools).length;
|
|
||||||
console.log(`[Project Tools] ✓ Loaded ${toolCount} custom tool(s) total: ${Object.keys(tools).join(', ')}`);
|
|
||||||
} catch (error) {
|
|
||||||
// Log errors for debugging
|
|
||||||
console.error('[Project Tools] Error loading project tools:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return tools;
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user