Compare commits

..
Author SHA1 Message Date
Alex Gleason 1ae491dd81 Support .opencode/tools/ 2026-01-23 23:00:31 -06:00
Alex Gleason 1a7397b502 Remove accidental slop file 2026-01-22 23:43:40 -06:00
Alex Gleason 86d0e6fd8e Automatically resize too-large images uploaded through the chat input 2026-01-22 13:53:19 -06:00
Alex Gleason fb7b7e7155 Fix tests 2026-01-22 13:42:23 -06:00
Alex Gleason 3d3aa07554 Improve configure git repo step 2026-01-22 13:27:16 -06:00
Alex Gleason 3bd33332f6 Remove list of tools and skills from the system prompt 2026-01-22 12:55:20 -06:00
Alex Gleason 7ef349563d List available skills in the skill tool itself 2026-01-22 12:55:17 -06:00
Alex Gleason a2c472bfef Add slash commands 2026-01-22 12:39:18 -06:00
Alex Gleason 8d6f5e6320 Fix hardcoded projectsPath in todo tools 2026-01-22 00:47:57 -06:00
Alex Gleason ec5dc6d963 Add todo tools 2026-01-22 00:42:01 -06:00
Alex Gleason 87956df961 Add webfetch and websearch tools 2026-01-21 23:25:29 -06:00
Alex Gleason 79b336f967 stripProjectPrefix tweak 2026-01-21 21:52:58 -06:00
Alex Gleason bb28e71e50 Fix grep and glob tools 2026-01-21 21:45:30 -06:00
Alex Gleason 2971a91fbb Merge branch 'main' of https://gitlab.com/soapbox-pub/shakespeare 2026-01-21 21:40:29 -06:00
Alex Gleason 48f1a59c2a Default to worker.ts, actually 2026-01-21 21:40:18 -06:00
Alex Gleason 2bc5f45512 Bundle Cloudflare Worker before deploying 2026-01-21 21:36:06 -06:00
Alex Gleason b0a48accf3 npm audit fix 2026-01-21 21:20:10 -06:00
Alex Gleason 24e367315e Fix git fetch context 2026-01-21 21:19:06 -06:00
Alex Gleason 18bdf741d3 Tool improvements 2026-01-21 21:04:52 -06:00
Alex Gleason 765652ec67 Replace text_editor_* tools with OpenCode-inspired alternatives (read/write/edit) 2026-01-21 19:40:32 -06:00
Alex Gleason 47a7835797 Brevity when explaining deployment options 2026-01-21 18:32:45 -06:00
Alex Gleason 949e7bb1f7 Stricter phrasing in deployment options system prompt 2026-01-21 17:34:24 -06:00
Alex Gleason dd5f9fe379 Support Netlify functions 2026-01-21 17:15:49 -06:00
Alex Gleason a27317ea10 Add deployment options hints to the system prompt 2026-01-21 16:30:06 -06:00
Alex Gleason c9178643fb Make Cloudflare Workers deployment aware of wrangler.jsonc, allow specifying main module 2026-01-21 16:06:45 -06:00
Alex Gleason 6ba5cf9bb2 Enable TypeScript strict mode 2026-01-21 14:46:11 -06:00
Alex Gleason d5e267103c Clean up old electron code 2026-01-21 14:37:58 -06:00
Alex Gleason ac6d4643af Only navigate to preferences on desktop 2026-01-21 14:35:07 -06:00
Alex Gleason 9f60a72621 Add "Build" button back to preview pane 2026-01-21 14:29:49 -06:00
Alex Gleason f289735da9 Fix tests by mocking the localStorage API 2026-01-21 14:08:23 -06:00
Alex Gleason 71631d3375 Upgrade to Node 25 2026-01-21 13:54:24 -06:00
Alex Gleason 79759af337 Merge branch 'ppqFeedback' into 'main'
PPQ Feedback

See merge request soapbox-pub/shakespeare!97
2026-01-21 19:53:27 +00:00
Alex Gleason 6473b6c57a Fix type error 2026-01-21 13:50:11 -06:00
Alex Gleason add3c62bda Revert "breakout new chat button from dropdown menu"
This reverts commit 05100d295e.
2026-01-21 13:48:02 -06:00
Alex Gleason 46c2539543 Fix chat scrolling issues 2026-01-21 13:40:50 -06:00
Alex Gleason c95a1a3278 Remove legacy refresh from Preview Pane 2026-01-21 12:49:40 -06:00
Alex Gleason 5dfc1d8897 Fix deleting a deployment provider and editing Railway API token 2026-01-20 23:50:58 -06:00
Alex Gleason 428b1bee2a Generate a domain automatically on Railway 2026-01-20 23:43:29 -06:00
Alex Gleason 65495ba1dd Add Railway deployment 2026-01-20 23:13:49 -06:00
Alex Gleason 5c842bed9a Read project skills from multiple supported locations 2026-01-20 22:30:39 -06:00
Alex Gleason c8e8ef714e Split apart skills.ts from plugin.ts 2026-01-20 22:16:02 -06:00
Alex Gleason 16d4f814e5 Subtle OpenSecret body fix 2026-01-20 22:02:29 -06:00
Alex Gleason 31ab27a79a Polyfill node:crypto, allow building with files outside of project directory 2026-01-20 16:50:46 -06:00
Alex Gleason 13ea7c192e Support file: URIs in package.json 2026-01-18 03:22:07 -06:00
Alex Gleason 0d6bee2025 Add Maple AI support 2026-01-17 23:22:02 -06:00
Alex Gleason fba950aeb5 Support json ESM imports 2026-01-17 18:48:29 -06:00
lemonknowsall 5348ab1fda remove unused import and prop 2026-01-16 23:15:00 -08:00
lemonknowsall 3d36c35baa add missing languages for copy all and new chat 2026-01-16 23:04:43 -08:00
lemonknowsall f1e2823882 make log pane horizontal 2026-01-16 22:50:31 -08:00
lemonknowsall 4842ac8fa4 resizeable log pane 2026-01-16 22:50:31 -08:00
lemonknowsall 7a4cd6cd00 media drag and drop in chat view 2026-01-16 22:50:31 -08:00
lemonknowsall eb381bc37e add copy all button to logs popover 2026-01-16 14:41:00 -08:00
lemonknowsall 05100d295e breakout new chat button from dropdown menu 2026-01-16 13:55:29 -08:00
lemonknowsall a4271de370 add icon tooltips for info on hover 2026-01-16 13:48:55 -08:00
lemonknowsall 5b2359d671 default settings navigation to preferences 2026-01-16 12:52:41 -08:00
Alex Gleason a047f913b4 Truncate large tool calls and save the output to tmpDir 2026-01-15 12:45:01 -06:00
Alex Gleason 44805ce481 Move OpenCode Zen up in the presets list 2026-01-14 13:13:31 -06:00
Alex Gleason a8eec32842 Update URL templates to use opts objects 2026-01-14 11:16:40 -06:00
Alex Gleason 5d075e02ab npm audit fix 2026-01-11 13:18:05 -06:00
122 changed files with 8226 additions and 3428 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
image: node:22
image: node:25
default:
interruptible: true
+30 -2
View File
@@ -41,7 +41,8 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **ReadWebpageTool**: Fetch and read web pages
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -51,6 +52,33 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
- **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
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.
@@ -232,7 +260,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `ReadWebpageTool`
- Web access: `WebFetchTool`, `WebSearchTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
+1 -1
View File
@@ -284,7 +284,7 @@ export function useNewProviderOAuth() {
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist", "electron/dist"] },
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+1 -1
View File
@@ -11,7 +11,7 @@
<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: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'; 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' 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:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
<meta name="theme-color" content="#2b0037">
+393 -33
View File
@@ -20,6 +20,7 @@
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -70,7 +71,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"openai": "^6.16.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -95,7 +96,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -105,6 +106,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
@@ -2812,9 +2814,9 @@
"license": "BSD-2-Clause"
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.25.1",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.1.tgz",
"integrity": "sha512-yO28oVFFC7EBoiKdAn+VqRm+plcfv4v0xp6osG/VsCB0NlPZWi87ajbCZZ8f/RvOFLEu7//rSRmuZZ7lMoe3gQ==",
"version": "1.25.2",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.2.tgz",
"integrity": "sha512-LZFeo4F9M5qOhC/Uc1aQSrBHxMrvxett+9KLHt7OhcExtoiRN9DKgbZffMP/nxjutWDQpfMDfP3nkHI4X9ijww==",
"license": "MIT",
"dependencies": {
"@hono/node-server": "^1.19.7",
@@ -3002,6 +3004,15 @@
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"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": {
"version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
@@ -3020,6 +3031,182 @@
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
},
"node_modules/@opensecret/react": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@opensecret/react/-/react-1.5.4.tgz",
"integrity": "sha512-nIrb1NfKIJ1G8IK+b8OnjXvPgc/C3GkLVbZVF9HCh6WBDV2yimg8B7Eo6Pqu5mUtiFrQslFL9UbeDj4Py0mbGA==",
"license": "MIT",
"dependencies": {
"@peculiar/x509": "^1.12.2",
"@stablelib/base64": "^2.0.0",
"@stablelib/chacha20poly1305": "^2.0.0",
"@stablelib/random": "^2.0.0",
"cbor2": "^1.7.0",
"tweetnacl": "^1.0.3",
"zod": "^3.23.8"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
}
},
"node_modules/@opensecret/react/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/@peculiar/asn1-cms": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.0.tgz",
"integrity": "sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-csr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.6.0.tgz",
"integrity": "sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-ecc": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.6.0.tgz",
"integrity": "sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pfx": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.0.tgz",
"integrity": "sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs8": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.0.tgz",
"integrity": "sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs9": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.0.tgz",
"integrity": "sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pfx": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-rsa": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.0.tgz",
"integrity": "sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-schema": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.6.0.tgz",
"integrity": "sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==",
"license": "MIT",
"dependencies": {
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.0.tgz",
"integrity": "sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509-attr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.0.tgz",
"integrity": "sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/x509": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-csr": "^2.6.0",
"@peculiar/asn1-ecc": "^2.6.0",
"@peculiar/asn1-pkcs9": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"pvtsutils": "^1.3.6",
"reflect-metadata": "^0.2.2",
"tslib": "^2.8.1",
"tsyringe": "^4.10.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -4385,9 +4572,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -5015,6 +5202,89 @@
"node": ">=18.0.0"
}
},
"node_modules/@stablelib/aead": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@stablelib/aead/-/aead-2.0.0.tgz",
"integrity": "sha512-U/RMANRxbT/ahIpYsPSiFwDFNjADHdnCFfmo09MO1ai2XmerPAOPtMl0qmX7XVvygnACC6ijKDyHBoT2rGyElg==",
"license": "MIT"
},
"node_modules/@stablelib/base64": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-2.0.1.tgz",
"integrity": "sha512-P2z89A7N1ETt6RxgpVdDT2xlg8cnm3n6td0lY9gyK7EiWK3wdq388yFX/hLknkCC0we05OZAD1rfxlQJUbl5VQ==",
"license": "MIT"
},
"node_modules/@stablelib/binary": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/binary/-/binary-2.0.1.tgz",
"integrity": "sha512-U9iAO8lXgEDONsA0zPPSgcf3HUBNAqHiJmSHgZz62OvC3Hi2Bhc5kTnQ3S1/L+sthDTHtCMhcEiklmIly6uQ3w==",
"license": "MIT",
"dependencies": {
"@stablelib/int": "^2.0.1"
}
},
"node_modules/@stablelib/chacha": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha/-/chacha-2.0.1.tgz",
"integrity": "sha512-lS1FqtNqofxe2vLkRsLli2m3x/XanUyAYRphLhdHumKeIsLbjbCXdCq3Pf/eWiO7G3QlSG5ViqnoVjktzfLWMg==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/chacha20poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha20poly1305/-/chacha20poly1305-2.0.1.tgz",
"integrity": "sha512-kOoBsXbDPVRlelzXl+5WViycgM19lD7lF3Bc3KWI+DzId0Stc2HlxAfSc+Xpn3RgqSCl1ZNTXr33LegqBhBBaw==",
"license": "MIT",
"dependencies": {
"@stablelib/aead": "^2.0.0",
"@stablelib/binary": "^2.0.1",
"@stablelib/chacha": "^2.0.1",
"@stablelib/constant-time": "^2.0.1",
"@stablelib/poly1305": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/constant-time": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/constant-time/-/constant-time-2.0.1.tgz",
"integrity": "sha512-0NWPogffRm+UWBH0+iM5otZmNrVe5OHFIvyoNIVankMAYOQzMwcdVALOVPrB5Ho0dST+Oc3H8/hPh65Z8R/uew==",
"license": "MIT"
},
"node_modules/@stablelib/int": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/int/-/int-2.0.1.tgz",
"integrity": "sha512-Ht63fQp3wz/F8U4AlXEPb7hfJOIILs8Lq55jgtD7KueWtyjhVuzcsGLSTAWtZs3XJDZYdF1WcSKn+kBtbzupww==",
"license": "MIT"
},
"node_modules/@stablelib/poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/poly1305/-/poly1305-2.0.1.tgz",
"integrity": "sha512-D8xfZcL/5zeVARJ9I2fZOUCnZvsJx8G4JDQvD+ecsnaCildPtqZDwqqjtOc4cfHAdScrMjOzUVsssjXUTBw3YQ==",
"license": "MIT",
"dependencies": {
"@stablelib/constant-time": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/random": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/random/-/random-2.0.1.tgz",
"integrity": "sha512-W6GAtXEEs7r+dSbuBsvoFmlyL3gLxle41tQkjKu17dDWtDdjhVUbtRfRCQcCUeczwkgjQxMPopgwYEvxXtHXGw==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/wipe": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/wipe/-/wipe-2.0.1.tgz",
"integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==",
"license": "MIT"
},
"node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "1.0.10",
@@ -5545,6 +5815,18 @@
"@types/unist": "*"
}
},
"node_modules/@types/jsdom": {
"version": "27.0.0",
"resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-27.0.0.tgz",
"integrity": "sha512-NZyFl/PViwKzdEkQg96gtnB8wm+1ljhdDay9ahn4hgb+SfVtPCbm3TlmDUFXTA+MGN3CijicnMhG18SI5H3rFw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/tough-cookie": "*",
"parse5": "^7.0.0"
}
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -5657,6 +5939,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/tough-cookie": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz",
"integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
@@ -6297,6 +6586,20 @@
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/asn1js": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.7.tgz",
"integrity": "sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.1.3",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -6762,6 +7065,15 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cbor2": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/cbor2/-/cbor2-1.12.0.tgz",
"integrity": "sha512-3Cco8XQhi27DogSp9Ri6LYNZLi/TBY/JVnDe+mj06NkBjW/ZYOtekaEU4wZ4xcRMNrFkDv8KNtOAqHyDfz3lYg==",
"license": "MIT",
"engines": {
"node": ">=18.7"
}
},
"node_modules/ccount": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
@@ -9180,9 +9492,9 @@
"license": "MIT"
},
"node_modules/hono": {
"version": "4.11.1",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz",
"integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==",
"version": "4.11.4",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz",
"integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==",
"license": "MIT",
"peer": true,
"engines": {
@@ -10391,9 +10703,9 @@
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
"license": "MIT"
},
"node_modules/lodash.castarray": {
@@ -11917,16 +12229,16 @@
}
},
"node_modules/openai": {
"version": "5.15.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-5.15.0.tgz",
"integrity": "sha512-kcUdws8K/A8m02I+IqFBwO51gS+87GP89yWEufGbzEi8anBz4FB/bti2QxaJdGwwY4mwJGzx85XO7TuL/Tpu1w==",
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-6.16.0.tgz",
"integrity": "sha512-fZ1uBqjFUjXzbGc35fFtYKEOxd20kd9fDpFeqWtsOZWiubY8CZ1NAlXHW3iathaFvqmNtCWMIsosCuyeI7Joxg==",
"license": "Apache-2.0",
"bin": {
"openai": "bin/cli"
},
"peerDependencies": {
"ws": "^8.18.0",
"zod": "^3.23.8"
"zod": "^3.25 || ^4.0"
},
"peerDependenciesMeta": {
"ws": {
@@ -12510,6 +12822,24 @@
"node": ">=6"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",
"integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
@@ -12528,9 +12858,9 @@
}
},
"node_modules/qs": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
"version": "6.14.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
"integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
@@ -12796,12 +13126,12 @@
}
},
"node_modules/react-router": {
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.0"
"@remix-run/router": "1.23.2"
},
"engines": {
"node": ">=14.0.0"
@@ -12811,13 +13141,13 @@
}
},
"node_modules/react-router-dom": {
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.0",
"react-router": "6.30.0"
"@remix-run/router": "1.23.2",
"react-router": "6.30.3"
},
"engines": {
"node": ">=14.0.0"
@@ -12961,6 +13291,12 @@
"node": ">=8"
}
},
"node_modules/reflect-metadata": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0"
},
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -14678,6 +15014,24 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsyringe": {
"version": "4.10.0",
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
"license": "MIT",
"dependencies": {
"tslib": "^1.9.3"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/tsyringe/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/turndown": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.1.tgz",
@@ -14687,6 +15041,12 @@
"@mixmark-io/domino": "^2.2.0"
}
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
"license": "Unlicense"
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -16472,9 +16832,9 @@
}
},
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
+4 -2
View File
@@ -31,6 +31,7 @@
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -81,7 +82,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"openai": "^6.16.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -106,7 +107,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -116,6 +117,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
+5
View File
@@ -48,6 +48,11 @@ export default {
hostname = 'docs.z.ai';
}
// Deployment-provider-specific hacks
if (url.host === 'backboard.railway.com') {
hostname = 'railway.com';
}
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
+3 -6
View File
@@ -1,4 +1,4 @@
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
@@ -25,11 +25,8 @@ import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<Router>
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -58,7 +55,7 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</BrowserRouter>
);
}
export default AppRouter;
+3
View File
@@ -19,12 +19,14 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
projectId: string; // Current project ID for path display
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
projectId,
}: AIMessageItemProps) => {
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
@@ -71,6 +73,7 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+41 -7
View File
@@ -1041,12 +1041,31 @@ export function AIProviderConfigDialog({
<div className="grid gap-2">
<Label htmlFor="provider-auth">{t('authentication')}</Label>
<Select
value={localProvider.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
...localProvider,
nostr: value === 'nostr' || undefined,
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
})}
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
if (value === 'nostr') {
setLocalProvider({
...localProvider,
nostr: true,
openSecret: undefined,
apiKey: undefined
});
} else if (value === 'opensecret') {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: localProvider.openSecret,
apiKey: localProvider.apiKey
});
} else {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: undefined,
apiKey: localProvider.apiKey
});
}
}}
>
<SelectTrigger>
<SelectValue />
@@ -1054,10 +1073,25 @@ export function AIProviderConfigDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{localProvider.openSecret && (
<div className="grid gap-2">
<Label htmlFor="provider-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="provider-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={localProvider.openSecret || ''}
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
/>
</div>
)}
{!localProvider.nostr && (
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
@@ -1139,7 +1173,7 @@ export function AIProviderConfigDialog({
<div className="space-y-3">
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
+26 -3
View File
@@ -50,7 +50,8 @@ export function AddCustomAIProviderDialog({
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
@@ -66,6 +67,11 @@ export function AddCustomAIProviderDialog({
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
} else if (customAuthMethod === 'opensecret') {
provider.openSecret = customOpenSecretUrl.trim();
if (customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
}
}
if (customProxy) {
@@ -81,6 +87,7 @@ export function AddCustomAIProviderDialog({
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomOpenSecretUrl('');
setCustomProxy(false);
onOpenChange(false);
@@ -89,6 +96,7 @@ export function AddCustomAIProviderDialog({
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
@@ -156,7 +164,7 @@ export function AddCustomAIProviderDialog({
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
@@ -169,11 +177,26 @@ export function AddCustomAIProviderDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
{customAuthMethod === 'opensecret' && (
<div className="grid gap-2">
<Label htmlFor="custom-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="custom-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={customOpenSecretUrl}
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
/>
</div>
)}
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
+22 -6
View File
@@ -28,6 +28,7 @@ import type {
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
RailwayProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
@@ -37,7 +38,8 @@ type DeployProviderInput =
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>;
| Omit<DenoDeployProvider, 'id'>
| Omit<RailwayProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
@@ -51,7 +53,7 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
@@ -129,6 +131,15 @@ export function AddCustomProviderDialog({
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'railway') {
if (!customApiKey.trim()) return;
provider = {
type: 'railway',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -156,7 +167,8 @@ export function AddCustomProviderDialog({
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim())));
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -175,7 +187,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -200,6 +212,7 @@ export function AddCustomProviderDialog({
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
<SelectItem value="railway">Railway</SelectItem>
</SelectContent>
</Select>
</div>
@@ -299,7 +312,8 @@ export function AddCustomProviderDialog({
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
'Access Token'} <span className="text-destructive">*</span>
customProviderType === 'railway' ? 'API Token' :
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -319,7 +333,9 @@ export function AddCustomProviderDialog({
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: 'https://api.cloudflare.com/client/v4'
: customProviderType === 'railway'
? 'https://backboard.railway.com'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
+2 -2
View File
@@ -9,7 +9,7 @@ import { getSentryInstance } from '@/lib/sentry';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
onError?: (error: Error, info: { componentStack: string | null }) => void;
onError?: (error: Error, info: { componentStack?: string | null }) => void;
/** Whether to report errors to Sentry (default: true) */
reportToSentry?: boolean;
}
@@ -91,7 +91,7 @@ export function ErrorBoundary({
onError,
reportToSentry = true,
}: ErrorBoundaryProps) {
const handleError = (error: Error, info: { componentStack: string | null }) => {
const handleError = (error: Error, info: { componentStack?: string | null }) => {
// Log error details for debugging
console.error('ErrorBoundary caught an error:', error, info);
+2 -2
View File
@@ -33,10 +33,10 @@ export function ExternalFavicon({
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
// Normalize the URL to ensure it has a protocol
return faviconUrl(config.faviconUrl, parsedUrl);
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
} catch {
return;
}
+1
View File
@@ -327,6 +327,7 @@ export function ProjectSidebar({
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
title={(onClose && isMobile) ? t('closeSidebar') : t('hidePaneButtonTooltip')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
+2 -4
View File
@@ -27,7 +27,6 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
@@ -40,7 +39,6 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -111,11 +109,11 @@ export function ProjectTitleMenu({
<DropdownMenuItem
onClick={onNewChat}
disabled={isAILoading}
disabled={isAnyLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
{t('newChat')}
New Chat
</DropdownMenuItem>
<DropdownMenuItem
+6 -1
View File
@@ -212,6 +212,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
}
}}
/>
@@ -227,7 +229,8 @@ export function ProviderConfigDialog({
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
'Base URL'
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
@@ -239,6 +242,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
}
}}
/>
-16
View File
@@ -1,16 +0,0 @@
import { useTranslation } from 'react-i18next';
/** Visual divider between chat sessions */
export function SessionDivider() {
const { t } = useTranslation();
return (
<div className="flex items-center gap-3 text-xs text-muted-foreground py-4">
<div className="flex-1 h-px bg-border" />
<span className="uppercase tracking-wide">
{t('newChat', 'New chat')}
</span>
<div className="flex-1 h-px bg-border" />
</div>
);
}
+164 -31
View File
@@ -1,13 +1,20 @@
import { useState, useCallback, memo } from 'react';
import { useState, useCallback, memo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
export interface SlashCommand {
name: string;
description: string;
action: () => void;
}
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
@@ -29,6 +36,7 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
slashCommands?: SlashCommand[];
}
export const ChatInput = memo(function ChatInput({
@@ -52,10 +60,15 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
slashCommands = [],
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -78,16 +91,110 @@ export const ChatInput = memo(function ChatInput({
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const executeSlashCommand = useCallback((command: SlashCommand) => {
setInput('');
setShowSlashCommands(false);
setSelectedCommandIndex(0);
command.action();
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Handle arrow key navigation when slash commands are showing
if (showSlashCommands && filteredCommands.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
e.preventDefault();
executeSlashCommand(filteredCommands[selectedCommandIndex]);
return;
}
// If slash commands are showing and user presses Escape, close the popover
if (e.key === 'Escape') {
e.preventDefault();
setShowSlashCommands(false);
setSelectedCommandIndex(0);
return;
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
const value = e.target.value;
setInput(value);
// Check if slash command autocomplete should be shown
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
const query = value.slice(1).toLowerCase();
const filtered = slashCommands.filter(cmd =>
cmd.name.toLowerCase().includes(query)
);
setFilteredCommands(filtered);
setShowSlashCommands(filtered.length > 0);
setSelectedCommandIndex(0); // Reset selection when filtering
} else {
setShowSlashCommands(false);
setSelectedCommandIndex(0);
}
}, [slashCommands]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Call parent's drop handler for visual state management
onDrop(e);
// Extract files from the drop event
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
}, [onDrop]);
// Close popover when clicking outside
useEffect(() => {
if (!showSlashCommands) return;
const handleClickOutside = (e: MouseEvent) => {
// Check if click is outside the popover and textarea
const target = e.target as Node;
if (textareaRef.current && !textareaRef.current.contains(target)) {
setShowSlashCommands(false);
}
};
// Use a slight delay to avoid closing immediately on focus
const timeoutId = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', handleClickOutside);
};
}, [showSlashCommands]);
return (
<div className="border-t p-4">
@@ -99,35 +206,61 @@ export const ChatInput = memo(function ChatInput({
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{showSlashCommands && filteredCommands.length > 0 && (
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
<Command value={filteredCommands[selectedCommandIndex]?.name}>
<CommandList>
<CommandGroup>
{filteredCommands.map((command) => (
<CommandItem
key={command.name}
value={command.name}
onSelect={() => executeSlashCommand(command)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<div className="font-medium">/{command.name}</div>
<div className="text-xs text-muted-foreground">{command.description}</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
)}
</div>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
+147 -107
View File
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
import { ChevronDown, Play } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
@@ -15,12 +15,15 @@ import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useMCPTools } from '@/hooks/useMCPTools';
import { useProjectTools } from '@/hooks/useProjectTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { ReadTool } from '@/lib/tools/ReadTool';
import { WriteTool } from '@/lib/tools/WriteTool';
import { EditTool } from '@/lib/tools/EditTool';
import { GlobTool } from '@/lib/tools/GlobTool';
import { GrepTool } from '@/lib/tools/GrepTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
@@ -39,7 +42,11 @@ import { SkillTool } from '@/lib/tools/SkillTool';
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -47,12 +54,13 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { SessionDivider } from '@/components/SessionDivider';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
import { AIMessage } from '@/lib/SessionManager';
import { getAllSkills } from '@/lib/skills';
// Clean interfaces now handled by proper hooks
@@ -92,12 +100,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const scrolledProjectsRef = useRef(new Set<string>());
const shouldScrollToBottomRef = useRef(false);
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
const [showToolsDialog, setShowToolsDialog] = useState(false);
const [availableSkills, setAvailableSkills] = useState<Array<{ name: string; description: string; path: string; plugin: string }>>([]);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
@@ -168,16 +179,45 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
}, [queryClient, cwd]);
// Load available skills
useEffect(() => {
const loadSkills = async () => {
const skills = await getAllSkills(fs, pluginsPath, cwd);
setAvailableSkills(skills);
};
loadSkills().catch(err => {
console.error('Failed to load skills:', err);
setAvailableSkills([]);
});
}, [fs, pluginsPath, cwd]);
// Fetch MCP tools
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
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
// File operation tools (OpenCode-compatible API)
read: new ReadTool(fs, cwd, { projectsPath }),
write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
glob: new GlobTool(fs, cwd),
grep: new GrepTool(fs, cwd),
// Other tools
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
@@ -191,7 +231,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath, cwd),
skill: new SkillTool(fs, availableSkills),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
};
// Add generate_image tool if imageModel is configured
@@ -243,16 +287,21 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
// Combined tool executors (for SessionManager to call)
const customTools = useMemo(() => ({
...builtInTools,
...mcpToolWrappers,
}), [builtInTools, mcpToolWrappers]);
const customTools = useMemo(() => {
const combined = {
...builtInTools,
...projectTools,
...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
const tools = useMemo(() => {
@@ -263,11 +312,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
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)
Object.assign(result, mcpOpenAITools);
console.log(`[ChatPane] Total tools available to AI: ${Object.keys(result).length}`);
return result;
}, [builtInTools, mcpOpenAITools]);
}, [builtInTools, projectTools, mcpOpenAITools]);
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
@@ -295,13 +351,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const {
messages,
displayMessages,
sessionName,
streamingMessage,
isLoading: internalIsLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
@@ -310,7 +362,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
startGeneration,
stopGeneration,
startNewSession: internalStartNewSession,
loadMoreHistory,
} = useAIChat({
projectId,
tools,
@@ -324,7 +375,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const checkTemplateInfo = async () => {
try {
// Only check if we have at least 1 message
if (displayMessages.length === 0) {
if (messages.length === 0) {
setShowTemplateInfo(false);
return;
}
@@ -363,7 +414,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
checkTemplateInfo();
}, [fs, projectsPath, projectId, displayMessages.length]);
}, [fs, projectsPath, projectId, messages.length]);
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(async () => {
@@ -442,11 +493,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Function to scroll to bottom
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, []);
@@ -499,33 +546,46 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
const container = scrollAreaRef.current;
const lastMessage = messages[messages.length - 1];
const isUserMessage = lastMessage?.role === 'user';
// Check if user was already near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Scroll to bottom if user sent a message or was already near the bottom
if (isUserMessage || isNearBottom) {
scrollToBottom();
// Auto-scroll if:
// 1. User just sent a message (shouldScrollToBottomRef is true), OR
// 2. User was already near the bottom
if (shouldScrollToBottomRef.current || isNearBottom) {
// Double requestAnimationFrame ensures scroll happens after layout and paint
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
});
shouldScrollToBottomRef.current = false; // Reset the flag
}
}
}, [messages, streamingMessage, isLoading, scrollToBottom]);
}, [messages, streamingMessage, isLoading]);
// Remove project from scrolled set when loading starts (so it can scroll again after loading)
useEffect(() => {
if (isLoadingHistory) {
scrolledProjectsRef.current.delete(projectId);
}
}, [projectId, isLoadingHistory]);
// Scroll to bottom when first visiting a project (including page refresh)
useEffect(() => {
if (projectId && !scrolledProjects.has(projectId)) {
// Small delay to ensure messages have loaded
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
if (projectId && !scrolledProjectsRef.current.has(projectId) && !isLoadingHistory && messages.length > 0) {
// Use double RAF to ensure DOM is fully rendered after isLoadingHistory becomes false
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollToBottom();
scrolledProjectsRef.current.add(projectId);
});
});
}
}, [projectId, scrolledProjects, scrollToBottom]);
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
@@ -590,11 +650,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Scroll to bottom when user sends a message
scrollToBottom();
// Mark that we should scroll to bottom when the message is added
shouldScrollToBottomRef.current = true;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, scrollToBottom]);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
@@ -615,6 +675,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [onFirstInteraction]);
// Slash commands
const slashCommands: SlashCommand[] = [
{
name: 'new',
description: 'Start a new chat session',
action: () => {
internalStartNewSession();
onNewChat();
},
},
{
name: 'tools',
description: "View the current session's available tools",
action: () => setShowToolsDialog(true),
},
];
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
@@ -634,6 +711,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
projectId={projectId}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
@@ -649,6 +727,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -685,6 +764,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -773,7 +853,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
)}
{/* Empty state when no messages and not loading */}
{!isLoadingHistory && displayMessages.length === 0 && !streamingMessage && !isLoading && (
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
<div className="text-center space-y-4 max-w-md mx-auto">
<div className="mb-6">
@@ -797,49 +877,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{/* Load older messages button */}
{!isLoadingHistory && hasMoreHistory && (
<div className="flex justify-center py-3">
<Button
variant="ghost"
size="sm"
onClick={async () => {
const container = scrollAreaRef.current;
const oldScrollHeight = container?.scrollHeight || 0;
await loadMoreHistory();
// Preserve scroll position after prepending content
if (container) {
requestAnimationFrame(() => {
container.scrollTop += container.scrollHeight - oldScrollHeight;
});
}
}}
disabled={isLoadingMoreHistory}
className="gap-2 text-muted-foreground"
>
<ChevronUp className="h-4 w-4" />
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
</Button>
</div>
)}
{!isLoadingHistory && displayMessages.map((message, index) => {
// Get the current message's session ID and compare to previous
const currentSessionId = (message as DisplayMessage).sessionId;
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage).sessionId : undefined;
// Show divider when session changes (not on first message)
const showDivider = index > 0 && currentSessionId !== prevSessionId;
// Dim messages from older sessions (compare against current active session)
const isOlderSession = currentSessionId !== sessionName;
{!isLoadingHistory && messages.map((message, index) => {
// Find the corresponding tool call for tool messages
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
if (message.role === 'tool') {
// Look backwards to find the assistant message with matching tool call
for (let i = index - 1; i >= 0; i--) {
const prevMessage = displayMessages[i];
const prevMessage = messages[i];
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
if (toolCall) break;
@@ -848,27 +892,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return (
<div
<AIMessageItem
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
className={isOlderSession ? 'opacity-65' : ''}
>
{showDivider && <SessionDivider />}
<AIMessageItem
message={message}
toolCall={toolCall}
/>
</div>
message={message}
toolCall={toolCall}
projectId={projectId}
/>
);
})}
{/* Trailing session divider - shown when New Chat is clicked before sending a message */}
{!isLoadingHistory && displayMessages.length > 0 && (() => {
const lastSessionId = (displayMessages[displayMessages.length - 1] as DisplayMessage).sessionId;
return sessionName && lastSessionId && sessionName !== lastSessionId ? (
<SessionDivider key="trailing-divider" />
) : null;
})()}
{!isLoadingHistory && renderStreamingMessage()}
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
@@ -937,6 +969,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -944,6 +977,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
+282 -146
View File
@@ -10,17 +10,14 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer, RefreshCw } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -77,14 +74,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [buildError, setBuildError] = useState<string | null>(null);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
const logsPanelRef = useRef<ImperativePanelHandle>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
@@ -177,19 +178,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [projectId, projectsManager]);
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 10);
}
}, [projectId, previewDomain]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
@@ -440,6 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setBuildError(null);
// Reset navigation history and state
setCurrentPath('/');
@@ -464,13 +454,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframeLegacy();
refreshIframe();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
}, [projectId, checkForBuiltProject, refreshIframe]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -500,106 +490,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
};
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
const [copiedBuildError, setCopiedBuildError] = useState(false);
const messages = isOpen ? getConsoleMessages() : [];
const messages = isLogsOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 gap-2 relative"
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
sideOffset={4}
>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const copyAllMessagesToClipboard = async () => {
try {
const allMessages = messages.map(msg => msg.message).join('\n');
await navigator.clipboard.writeText(allMessages);
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
} catch (error) {
console.error('Failed to copy all messages to clipboard:', error);
}
};
const messageCount = messages.length;
// Programmatically resize panels when isLogsOpen changes
useEffect(() => {
if (isLogsOpen) {
// Open logs panel to 40% and resize iframe to 60%
logsPanelRef.current?.resize(40);
iframePanelRef.current?.resize(60);
} else {
// Close logs panel and expand iframe to 100%
logsPanelRef.current?.resize(0);
iframePanelRef.current?.resize(100);
}
}, [isLogsOpen]);
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
@@ -656,7 +588,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title="Build project"
title={t('buildButtonTooltip')}
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -671,45 +603,249 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
title={t('codeButtonTooltip')}
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<ConsoleDropdown />
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(!isLogsOpen)}
className={cn("h-8 gap-2 relative", isLogsOpen && "bg-muted")}
title={t('logsButtonTooltip')}
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</div>
</div>
{/* Content area */}
<div className="flex-1 flex items-center justify-center bg-muted/30">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
<div className="flex-1 bg-muted/30 min-h-0 overflow-hidden">
<ResizablePanelGroup direction="vertical" className="h-full">
<ResizablePanel
ref={iframePanelRef}
defaultSize={isLogsOpen ? 60 : 100}
minSize={30}
className="min-h-0"
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
<div className="h-full flex items-center justify-center min-h-0">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted p-4">
<div className="text-center space-y-4 max-w-2xl w-full">
<div>
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
</div>
{buildError && (
<div className="bg-destructive/10 border border-destructive/20 rounded-lg overflow-hidden text-left">
<div className="px-4 py-2 bg-destructive/20 border-b border-destructive/20 flex items-center justify-between">
<p className="font-semibold text-destructive text-sm">Build Failed</p>
<Button
variant="ghost"
size="sm"
onClick={async () => {
try {
await navigator.clipboard.writeText(buildError);
setCopiedBuildError(true);
setTimeout(() => setCopiedBuildError(false), 2000);
} catch (error) {
console.error('Failed to copy error to clipboard:', error);
}
}}
className="h-7 px-2 text-xs hover:bg-destructive/10"
>
{copiedBuildError ? (
<>
<Check className="h-3 w-3 mr-1.5" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
Copy
</>
)}
</Button>
</div>
<ScrollArea className="max-h-48">
<div className="overflow-x-auto">
<pre className="p-4 text-xs font-mono text-destructive whitespace-pre leading-relaxed">{buildError}</pre>
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
)}
<Button
variant="outline"
onClick={() => {
setBuildError(null);
buildProject(undefined, {
onSuccess: () => {
setBuildError(null);
},
onError: (error) => {
console.error('Build failed:', error);
setBuildError(error instanceof Error ? error.message : String(error));
}
});
}}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Building...
</>
) : buildError ? (
<>
<RefreshCw className="h-4 w-4" />
Retry
</>
) : (
<>
<Hammer className="h-4 w-4" />
Build
</>
)}
</Button>
</div>
</div>
)}
</div>
</div>
)}
</ResizablePanel>
<ResizableHandle withHandle className={cn(!isLogsOpen && "hidden")} />
<ResizablePanel
ref={logsPanelRef}
defaultSize={isLogsOpen ? 40 : 0}
minSize={0}
maxSize={isLogsOpen ? undefined : 0}
className="min-h-0 min-w-0"
collapsible
collapsedSize={0}
>
{/* Logs Panel */}
<div className="h-full flex flex-col bg-background border-t overflow-hidden min-h-0 w-full min-w-0">
{/* Logs Header */}
<div className="h-12 px-4 border-b flex items-center justify-between flex-shrink-0">
<div className="flex items-center gap-2">
{hasConsoleErrors && (
<span className="h-2 w-2 rounded-full bg-red-500" />
)}
</div>
<div className="flex items-center gap-2">
{messageCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={copyAllMessagesToClipboard}
className="h-7 px-2 text-xs"
>
{copiedAll ? (
<>
<Check className="h-3 w-3 mr-1.5 text-success" />
{t('copied')}
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
{t('copyAll')}
</>
)}
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(false)}
className="h-7 w-7 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Logs Content */}
<div className="flex-1 min-h-0 overflow-hidden w-full">
<ScrollArea className="h-full w-full">
<div className="p-2 space-y-0 w-full min-w-0 max-w-full">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer w-full max-w-full"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div
className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words w-full min-w-0 max-w-full",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}
style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</ScrollArea>
</div>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
{/* Build loading overlay */}
@@ -0,0 +1,59 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import OpenAI from 'openai';
interface ToolsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
}
export function ToolsDialog({ open, onOpenChange, tools }: ToolsDialogProps) {
const toolEntries = Object.entries(tools);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>Available Tools</DialogTitle>
<DialogDescription>
The current session's full list of available tools ({toolEntries.length} tools)
</DialogDescription>
</DialogHeader>
<ScrollArea className="h-[60vh] w-full pr-4">
<Accordion type="single" collapsible className="w-full space-y-2">
{toolEntries.map(([name, tool]) => {
const func = 'function' in tool ? tool.function : undefined;
return (
<AccordionItem key={name} value={name} className="border rounded-lg px-4">
<AccordionTrigger className="text-sm font-mono hover:no-underline py-3 outline-none focus:outline-none focus-visible:outline-none">
{name}
</AccordionTrigger>
<AccordionContent className="pt-2 pb-4">
<div className="space-y-3 text-sm">
<div>
<div className="font-semibold mb-1">Description:</div>
<div className="text-muted-foreground whitespace-pre-wrap">
{func?.description || 'No description available'}
</div>
</div>
{func?.parameters && (
<div>
<div className="font-semibold mb-1">Parameters:</div>
<pre className="text-xs bg-muted p-3 rounded-md overflow-x-auto">
{JSON.stringify(func.parameters, null, 2)}
</pre>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ToolCallDisplay } from './ToolCallDisplay';
describe('ToolCallDisplay', () => {
describe('path stripping', () => {
it('should strip project prefix from absolute paths for read tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/mysite/src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="write"
toolArgs={{ filePath: '/projects/mysite/src/App.tsx', content: 'code' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for edit tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="edit"
toolArgs={{
filePath: '/projects/mysite/src/components/Header.tsx',
oldString: 'old',
newString: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument();
});
it('should handle paths without project prefix', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: 'src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should handle legacy text_editor_view tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_view"
toolArgs={{ path: '/projects/mysite/README.md' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed README.md')).toBeInTheDocument();
});
it('should handle legacy text_editor_write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_write"
toolArgs={{ path: '/projects/mysite/package.json', file_text: '{}' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote package.json')).toBeInTheDocument();
});
it('should handle legacy text_editor_str_replace tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_str_replace"
toolArgs={{
path: '/projects/mysite/src/utils.ts',
old_str: 'old',
new_str: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument();
});
it('should handle different projects with same relative path', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/another-project/src/index.ts' }}
state="completed"
result="File content"
projectId="another-project"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
});
});
+319 -66
View File
@@ -26,12 +26,15 @@ import {
Settings,
TriangleAlert,
X,
Search,
Clipboard,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ImageModelDialog } from '@/components/ImageModelDialog';
import { ImageLightbox } from '@/components/ImageLightbox';
import { useFSPaths } from '@/hooks/useFSPaths';
interface ToolInfo {
icon: LucideIcon;
@@ -45,6 +48,7 @@ interface ToolCallDisplayProps {
toolArgs: Record<string, unknown>;
state: 'calling' | 'waiting' | 'completed';
result?: string; // The tool result content (only for completed state)
projectId: string; // Current project ID for path display
}
// Component to show image generation errors inline
@@ -77,21 +81,95 @@ function ImageGenerationError() {
);
}
/**
* Strip project path prefix from absolute paths
* e.g., /projects/mysite/src/index.ts -> src/index.ts
*/
function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/projects'): string {
if (!projectId) return path;
const projectPrefix = `${projectsPath}/${projectId}/`;
if (path === `${projectsPath}/${projectId}`) {
return '.';
} else if (path.startsWith(projectPrefix)) {
return path.slice(projectPrefix.length);
}
return path;
}
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? String(args.command) : 'Shell Command',
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
title: args.command ? String(args.command) : 'Shell command',
callingTitle: args.command ? String(args.command) : 'Running shell command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell command failed',
};
// New tools (OpenCode-compatible names)
case 'read': {
const rawPath = args.filePath ? String(args.filePath) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : undefined;
const lineInfo = (typeof offset === 'number' && typeof limit === 'number')
? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})`
: '';
return {
icon: Eye,
title: `Viewed ${path}${lineInfo}`,
callingTitle: `Viewing ${path}${lineInfo}`,
errorTitle: `Failed to view ${path}${lineInfo}`,
};
}
case 'write': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'edit': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'glob':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'File pattern search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
case 'grep':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'Content search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
// Legacy tools (kept for old chat history)
case 'text_editor_view': {
const path = args.path ? String(args.path) : 'File';
const rawPath = args.path ? String(args.path) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
@@ -104,21 +182,27 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
};
}
case 'text_editor_write':
case 'text_editor_write': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'text_editor_str_replace':
case 'text_editor_str_replace': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File',
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
@@ -134,25 +218,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
title: args.name ? `Removed ${args.name}` : 'Removed package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to remove package',
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
errorTitle: 'Failed to Commit Changes',
title: args.message ? `Committed: ${args.message}` : 'Committed changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing changes',
errorTitle: 'Failed to commit changes',
};
case 'build_project':
return {
icon: Package,
title: 'Built Project',
callingTitle: 'Building Project',
errorTitle: 'Failed to Build Project',
title: 'Built project',
callingTitle: 'Building project',
errorTitle: 'Failed to build project',
};
case 'nostr_read_nip':
@@ -160,55 +244,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to read NIP',
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
title: args.identifier ? `Viewed ${String(args.identifier).slice(0, 16)}...` : 'Viewed event',
callingTitle: args.identifier ? `Viewing ${String(args.identifier).slice(0, 16)}...` : 'Viewing event',
errorTitle: args.identifier ? `Failed to view ${String(args.identifier).slice(0, 16)}...` : 'Failed to view event',
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
title: args.kind !== undefined ? `Viewed kind ${args.kind}` : 'Viewed kind',
callingTitle: args.kind !== undefined ? `Viewing kind ${args.kind}` : 'Viewing kind',
errorTitle: args.kind !== undefined ? `Failed to view kind ${args.kind}` : 'Failed to view kind',
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
title: args.tag ? `Viewed tag "${args.tag}"` : 'Viewed tag',
callingTitle: args.tag ? `Viewing tag "${args.tag}"` : 'Viewing tag',
errorTitle: args.tag ? `Failed to view tag "${args.tag}"` : 'Failed to view tag',
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
title: args.doc ? `Viewed protocol ${args.doc}` : 'Viewed protocol',
callingTitle: args.doc ? `Viewing protocol ${args.doc}` : 'Viewing protocol',
errorTitle: args.doc ? `Failed to view protocol ${args.doc}` : 'Failed to view protocol',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read NIPs Index',
title: 'Viewed NIPs index',
callingTitle: 'Viewing NIPs index',
errorTitle: 'Failed to view NIPs index',
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
title: args.range ? `Generated ${args.range} kind` : 'Generated kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to generate kind',
};
case 'nostr_publish_events': {
@@ -217,58 +301,117 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to publish Nostr event',
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to deploy project',
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read Console',
title: 'Viewed console',
callingTitle: 'Viewing console',
errorTitle: 'Failed to view console',
};
case 'webfetch': {
const url = args.url ? String(args.url) : '';
return {
icon: Globe,
title: url ? `Viewed ${url}` : 'Viewed webpage',
callingTitle: url ? `Viewing ${url}` : 'Viewing webpage',
errorTitle: url ? `Failed to view ${url}` : 'Failed to view webpage',
};
}
case 'websearch': {
const query = args.query ? String(args.query) : '';
return {
icon: Search,
title: query ? `Searched "${query}"` : 'Web search',
callingTitle: query ? `Searching "${query}"` : 'Searching web',
errorTitle: query ? `Failed to search "${query}"` : 'Search failed',
};
}
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill',
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
callingTitle: args.name ? `Running skill: ${args.name}` : 'Running skill',
errorTitle: args.name ? `Skill failed: ${args.name}` : 'Skill failed',
};
case 'generate_image':
return {
icon: Image,
title: args.prompt ? String(args.prompt) : 'Generated Image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
errorTitle: 'Failed to Generate Image',
title: args.prompt ? String(args.prompt) : 'Generated image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating image',
errorTitle: 'Failed to generate image',
};
case 'view_available_models':
return {
icon: Eye,
title: 'Viewed Available Models',
callingTitle: 'Viewing Available Models',
errorTitle: 'Failed to View Available Models',
title: 'Viewed available models',
callingTitle: 'Viewing available models',
errorTitle: 'Failed to view available models',
};
case 'configure_image_generation':
return {
icon: Settings,
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
title: args.model ? `Configured image model: ${args.model}` : 'Configured image generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring image generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
};
case 'todowrite':
case 'todoread': {
// Try to parse the result to get task counts for the title
let title = toolName === 'todowrite' ? 'Updated todo list' : 'Viewed todo list';
if (result) {
try {
const todos = JSON.parse(result);
if (Array.isArray(todos)) {
const activeTodos = todos.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completedTodos = todos.filter((x: { status: string }) => x.status === 'completed');
const inProgressTask = todos.find((x: { status: string }) => x.status === 'in_progress');
// Format: "[<completed>/<total>] <active-task>" if in_progress task exists
if (inProgressTask) {
const taskName = inProgressTask.content || 'Task';
const totalTasks = todos.length;
title = `[${completedTodos.length + 1}/${totalTasks}] ${taskName}`;
} else if (activeTodos.length === 0 && completedTodos.length > 0) {
// All tasks completed
title = `${completedTodos.length + 1} task${completedTodos.length !== 0 ? 's' : ''} completed`;
} else if (completedTodos.length === 0) {
// No completed tasks yet
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}`;
} else {
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}, ${completedTodos.length} completed`;
}
}
} catch {
// If parsing fails, use default title
}
}
return {
icon: Clipboard,
title,
callingTitle: toolName === 'todowrite' ? 'Updating todo list' : 'Viewing todo list',
errorTitle: toolName === 'todowrite' ? 'Failed to update todo list' : 'Failed to view todo list',
};
}
default: {
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
return {
@@ -299,12 +442,13 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const [imageLoadError, setImageLoadError] = useState(false);
const { projectsPath } = useFSPaths();
const toolInfo = getToolInfo(toolName, toolArgs);
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath, result);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -342,19 +486,26 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
// Write tool expanded content (new and legacy)
if ((toolName === 'write' && typeof toolArgs.content === 'string') ||
(toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string')) {
const content = toolName === 'write' ? String(toolArgs.content) : String(toolArgs.file_text);
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text}
{content}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
const oldLines = String(toolArgs.old_str).split('\n');
const newLines = String(toolArgs.new_str).split('\n');
// Edit tool expanded content (new and legacy)
if ((toolName === 'edit' && typeof toolArgs.oldString === 'string' && typeof toolArgs.newString === 'string') ||
(toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string')) {
const oldStr = toolName === 'edit' ? String(toolArgs.oldString) : String(toolArgs.old_str);
const newStr = toolName === 'edit' ? String(toolArgs.newString) : String(toolArgs.new_str);
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
@@ -387,6 +538,56 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Read tool expanded content - parse and display file content nicely
if (toolName === 'read' || toolName === 'text_editor_view') {
// Parse the result to extract file content from <file> tags
const fileMatch = result.match(/<file>\n([\s\S]*?)\n\n\((.*?)\)\n<\/file>/);
if (fileMatch) {
const fileContent = fileMatch[1];
const footerMessage = fileMatch[2];
// Split content into lines and parse line numbers
const lines = fileContent.split('\n');
return (
<div className="mt-1 rounded border bg-background text-xs font-mono overflow-hidden">
<div className="max-h-96 overflow-y-auto">
<div>
{lines.map((line, idx) => {
// Parse line number and content (format: " 1| content")
const match = line.match(/^(\s*\d+)\|(.*)$/);
if (match) {
return (
<div key={idx} className="flex hover:bg-muted/30 transition-colors">
<div className="text-muted-foreground/60 select-none px-3 py-0.5 text-right min-w-[3rem] bg-muted/20">
{match[1].trim()}
</div>
<div className="flex-1 px-3 py-0.5 whitespace-pre-wrap break-words">
{match[2]}
</div>
</div>
);
}
// Fallback for lines that don't match expected format
return (
<div key={idx} className="px-3 py-0.5 whitespace-pre-wrap break-words">
{line}
</div>
);
})}
</div>
</div>
{footerMessage && (
<div className="px-3 py-1.5 bg-muted/30 border-t text-muted-foreground text-[10px]">
{footerMessage}
</div>
)}
</div>
);
}
// Fallback to default rendering if no <file> tags found
}
if (toolName === 'generate_image') {
// For generate_image, when expanded show the full prompt
return (
@@ -396,6 +597,58 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Todo tools expanded content
if (toolName === 'todowrite' || toolName === 'todoread') {
try {
const todos = JSON.parse(result);
if (!Array.isArray(todos)) {
throw new Error('Invalid todo format');
}
if (todos.length === 0) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="text-muted-foreground italic">No todos found</div>
</div>
);
}
// Find the first in_progress task for bold styling
const firstInProgressIndex = todos.findIndex((x: { status: string }) => x.status === 'in_progress');
return (
<div className="mt-1 rounded border bg-muted/30 text-xs overflow-hidden">
<div className="px-3 py-2 space-y-1">
{todos.map((todo: { id: string; content: string; status: string; priority: string }, index: number) => {
const isChecked = todo.status === 'completed' || todo.status === 'cancelled';
const isFirstInProgress = index === firstInProgressIndex;
return (
<div key={todo.id} className="flex items-start gap-2 py-1">
<input
type="checkbox"
checked={isChecked}
readOnly
className="mt-0.5 h-4 w-4 rounded border-gray-300 cursor-default"
/>
<span className={cn(
"flex-1 text-foreground",
isChecked && "line-through text-muted-foreground",
isFirstInProgress && "font-bold"
)}>
{todo.content}
</span>
</div>
);
})}
</div>
</div>
);
} catch {
// If parsing fails, fall through to default rendering
}
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
-1
View File
@@ -35,7 +35,6 @@ export function UserMessage({ content }: UserMessageProps) {
// Detect "Added file: <filename>" pattern
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
console.log('fileAddedMatch', part, fileAddedMatch);
if (fileAddedMatch && fileAddedMatch[1]) {
const path = fileAddedMatch[1];
const filename = getFileName(path);
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
+1 -1
View File
@@ -56,7 +56,7 @@ export function DenoDeployForm({
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
+3
View File
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { DeploySteps } from './DeploySteps';
import { useTranslation } from 'react-i18next';
interface DeployButtonProps {
projectId: string;
@@ -14,6 +15,7 @@ interface DeployButtonProps {
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
const [open, setOpen] = useState(false);
const { t } = useTranslation();
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -24,6 +26,7 @@ export function DeployButton({ projectId, projectName, className, disabled }: De
className={cn("size-8 p-0 group", className)}
aria-label="Deploy project"
disabled={disabled}
title={t('deployButtonTooltip')}
>
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
</Button>
+83 -1
View File
@@ -23,6 +23,7 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
@@ -31,6 +32,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
/**
* Normalize a URL string to ensure it has a protocol
@@ -101,6 +103,14 @@ interface DenoDeployFormData {
projectName: string;
}
interface RailwayFormData {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -138,6 +148,13 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
const [railwayForm, setRailwayForm] = useState<RailwayFormData>({
workspaceId: '',
projectId: '',
environmentId: '',
serviceId: '',
projectName: projectName || projectId,
});
// Load project settings when component mounts
useEffect(() => {
@@ -242,6 +259,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
baseDomain: cloudflareProvider.baseDomain,
projectName: cloudflareForm.projectName || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
esmUrl: config.esmUrl,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider;
@@ -261,6 +279,23 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
if (!railwayProvider.apiKey) {
throw new Error('Railway API token is required');
}
adapter = new RailwayAdapter({
fs,
apiKey: railwayProvider.apiKey,
baseURL: railwayProvider.baseURL,
workspaceId: railwayForm.workspaceId || undefined,
projectId: railwayForm.projectId || undefined,
environmentId: railwayForm.environmentId || undefined,
serviceId: railwayForm.serviceId || undefined,
projectName: railwayForm.projectName || undefined,
corsProxy: railwayProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -320,6 +355,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'railway') {
await updateProjectSettings(selectedProviderId, {
type: 'railway',
url: result.url,
data: {
workspaceId: railwayForm.workspaceId || undefined,
projectId: result.metadata?.projectId as string | undefined,
environmentId: result.metadata?.environmentId as string | undefined,
serviceId: result.metadata?.serviceId as string | undefined,
},
});
}
setDeployResult(result);
@@ -341,6 +387,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
onClose();
};
@@ -372,6 +419,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDenoDeployForm({ projectName });
}, []);
const handleRailwayConfigChange = useCallback((config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => {
setRailwayForm(config);
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -477,6 +534,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
);
}
if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedWorkspaceId = savedConfig?.type === 'railway' ? savedConfig.data.workspaceId : undefined;
const savedProjectId = savedConfig?.type === 'railway' ? savedConfig.data.projectId : undefined;
const savedEnvironmentId = savedConfig?.type === 'railway' ? savedConfig.data.environmentId : undefined;
const savedServiceId = savedConfig?.type === 'railway' ? savedConfig.data.serviceId : undefined;
return (
<RailwayDeployForm
apiKey={railwayProvider.apiKey}
baseURL={railwayProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedWorkspaceId={savedWorkspaceId}
savedProjectId={savedProjectId}
savedEnvironmentId={savedEnvironmentId}
savedServiceId={savedServiceId}
onConfigChange={handleRailwayConfigChange}
corsProxy={railwayProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -653,7 +734,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
}
className="w-full"
>
+1 -1
View File
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: {
+382
View File
@@ -0,0 +1,382 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface Workspace {
id: string;
name: string;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
services: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
}
interface RailwayDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedWorkspaceId?: string;
savedProjectId?: string;
savedEnvironmentId?: string;
savedServiceId?: string;
onConfigChange: (config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => void;
corsProxy?: string;
}
export function RailwayDeployForm({
apiKey,
baseURL = 'https://backboard.railway.com',
projectId,
projectName,
savedWorkspaceId,
savedProjectId,
savedEnvironmentId,
savedServiceId,
onConfigChange,
corsProxy,
}: RailwayDeployFormProps) {
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>('');
const [selectedProjectId, setSelectedProjectId] = useState<string>('');
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string>('');
const [selectedServiceId, setSelectedServiceId] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchWorkspaces = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const url = `${baseURL}/graphql/v2`;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
if (!response.ok) {
throw new Error(`Failed to fetch workspaces: ${response.status} ${response.statusText}`);
}
const result = await response.json();
if (result.errors) {
throw new Error(`Railway API error: ${result.errors[0]?.message || 'Unknown error'}`);
}
const workspacesData: Workspace[] = result.data.me.workspaces;
setWorkspaces(workspacesData);
// Auto-select workspace if saved or if there's only one
if (savedWorkspaceId && workspacesData.some(w => w.id === savedWorkspaceId)) {
setSelectedWorkspaceId(savedWorkspaceId);
} else if (workspacesData.length === 1) {
setSelectedWorkspaceId(workspacesData[0].id);
}
// Auto-select project if saved
if (savedProjectId) {
setSelectedProjectId(savedProjectId);
}
// Auto-select environment if saved
if (savedEnvironmentId) {
setSelectedEnvironmentId(savedEnvironmentId);
}
// Auto-select service if saved
if (savedServiceId) {
setSelectedServiceId(savedServiceId);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch workspaces');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedWorkspaceId, savedProjectId, savedEnvironmentId, savedServiceId, corsProxy]);
useEffect(() => {
fetchWorkspaces();
}, [fetchWorkspaces]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectId === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectId, newProjectName, projectName, projectId]);
// Notify parent of configuration changes
useEffect(() => {
if (!selectedWorkspaceId || !selectedProjectId) {
return;
}
if (selectedProjectId === 'new') {
// Creating new project - only require workspace and project name
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: '',
environmentId: '',
serviceId: '',
projectName: newProjectName,
});
} else {
// Existing project - require environment and service
if (!selectedEnvironmentId || !selectedServiceId) {
return;
}
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: selectedProjectId,
environmentId: selectedEnvironmentId,
serviceId: selectedServiceId === 'new' ? '' : selectedServiceId,
});
}
}, [selectedWorkspaceId, selectedProjectId, selectedEnvironmentId, selectedServiceId, newProjectName, onConfigChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Workspace</Label>
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
</div>
);
}
const selectedWorkspace = workspaces.find(w => w.id === selectedWorkspaceId);
const projects = selectedWorkspace?.projects.edges.map(e => e.node) || [];
const selectedProject = projects.find(p => p.id === selectedProjectId);
const environments = selectedProject?.environments.edges.map(e => e.node) || [];
const services = selectedProject?.services.edges.map(e => e.node) || [];
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Workspace Selection */}
<div className="space-y-2">
<Label htmlFor="railway-workspace">Workspace</Label>
<Select value={selectedWorkspaceId} onValueChange={setSelectedWorkspaceId}>
<SelectTrigger id="railway-workspace">
<SelectValue placeholder="Select a workspace..." />
</SelectTrigger>
<SelectContent>
{workspaces.map((workspace) => (
<SelectItem key={workspace.id} value={workspace.id}>
{workspace.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Project Selection */}
{selectedWorkspaceId && (
<div className="space-y-2">
<Label htmlFor="railway-project">Project</Label>
<Select
value={selectedProjectId}
onValueChange={(value) => {
setSelectedProjectId(value);
setSelectedEnvironmentId('');
setSelectedServiceId('');
}}
>
<SelectTrigger id="railway-project">
<SelectValue placeholder="Select a project or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new project
</div>
</SelectItem>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* New Project Name */}
{selectedProjectId === 'new' && (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Project Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
A new project with a production environment and web service will be created when you deploy
</p>
</div>
)}
{/* Environment Selection */}
{selectedProjectId && selectedProjectId !== 'new' && environments.length > 0 && (
<div className="space-y-2">
<Label htmlFor="railway-environment">Environment</Label>
<Select value={selectedEnvironmentId} onValueChange={setSelectedEnvironmentId}>
<SelectTrigger id="railway-environment">
<SelectValue placeholder="Select an environment..." />
</SelectTrigger>
<SelectContent>
{environments.map((env) => (
<SelectItem key={env.id} value={env.id}>
{env.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Service Selection */}
{selectedProjectId && selectedProjectId !== 'new' && selectedEnvironmentId && (
<div className="space-y-2">
<Label htmlFor="railway-service">Service</Label>
<Select value={selectedServiceId} onValueChange={setSelectedServiceId}>
<SelectTrigger id="railway-service">
<SelectValue placeholder="Select a service or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new service
</div>
</SelectItem>
{services.map((service) => (
<SelectItem key={service.id} value={service.id}>
{service.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Project Info */}
{selectedProject && selectedProjectId !== 'new' && (
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedProject.name}</p>
<p className="text-xs text-muted-foreground">
{environments.length} environment(s), {services.length} service(s)
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://railway.app/project/${selectedProject.id}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
);
}
@@ -7,6 +7,7 @@ import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useFSPaths } from '@/hooks/useFSPaths';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
import { useTranslation } from 'react-i18next';
interface GitSyncButtonProps {
projectId: string;
@@ -18,6 +19,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { t } = useTranslation();
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
@@ -129,6 +131,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
title={t('cloudSyncButtonTooltip')}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
@@ -2,7 +2,6 @@ import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGit } from '@/hooks/useGit';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -20,6 +19,8 @@ import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
import { useGitAutosync } from '@/hooks/useGitAutosync';
import { ArrowUp } from 'lucide-react';
import { ForcePushDialog } from './ForcePushDialog';
import { SyncStepError } from './SyncStepError';
// Helper function to convert kebab-case to Title Case
function kebabToTitleCase(str: string): string {
@@ -41,7 +42,8 @@ export function ConfigureRepoStep({
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
const { user } = useCurrentUser();
const { git } = useGit();
@@ -74,9 +76,10 @@ export function ConfigureRepoStep({
setIsRepoNameManuallyEdited(true);
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
// Shared push logic for both initial push and force push
const executePush = async (force: boolean = false) => {
// Store the URL we're trying to add so we can remove it on error
let remoteAdded = false;
try {
if (selectedProvider.id === 'nostr') {
@@ -196,12 +199,14 @@ export function ConfigureRepoStep({
url: nostrURI.toString(),
force: true,
});
remoteAdded = true;
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
} else {
// Validate repository URL
@@ -216,12 +221,14 @@ export function ConfigureRepoStep({
url: repositoryUrl,
force: true, // Override if exists
});
remoteAdded = true;
// Push to remote
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
}
@@ -238,8 +245,45 @@ export function ConfigureRepoStep({
// Show success state
onSuccess();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to push';
setError(message);
const error = err instanceof Error ? err : new Error(force ? 'Failed to force push' : 'Failed to push');
// If we added the remote but push failed, remove it
if (remoteAdded) {
try {
await git.deleteRemote({ dir, remote: 'origin' });
} catch {
// Ignore errors when cleaning up remote
}
}
throw error; // Re-throw so caller can handle
}
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
await executePush(false);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to push');
setError(error);
} finally {
setIsPushing(false);
}
};
const handleForcePush = async () => {
setIsPushing(true);
setError(null);
setShowForcePushDialog(false);
try {
await executePush(true);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to force push');
setError(error);
} finally {
setIsPushing(false);
}
@@ -343,9 +387,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -360,6 +408,13 @@ export function ConfigureRepoStep({
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
@@ -386,9 +441,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -407,6 +466,13 @@ export function ConfigureRepoStep({
)}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
+1 -1
View File
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
if (url.protocol === 'nostr:') {
const nostrUri = await NostrURI.parse(url.href);
return ngitWebUrl(config.ngitWebUrl, nostrUri);
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
}
return null;
+44 -10
View File
@@ -8,14 +8,16 @@ import { getSentryInstance } from '@/lib/sentry';
interface SyncStepErrorProps {
error: Error;
onDismiss: () => void;
onForcePull: () => void;
onForcePull?: () => void;
onForcePush: () => void;
onPull: () => void;
remoteUrl: URL;
onPull?: () => void;
remoteUrl?: URL;
remoteName: string;
/** Context for error messages - 'sync' for existing remotes, 'configure' for initial setup */
context?: 'sync' | 'configure';
}
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl, context = 'sync' }: SyncStepErrorProps) {
const renderForcePullButton = () => (
<Button
variant="outline"
@@ -104,17 +106,23 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
// PushRejectedError - remote has changes
if (error instanceof GitErrors.PushRejectedError) {
// Different message based on context
const message = context === 'configure'
? `The repository on ${remoteName} is not empty. You'll need to force push to overwrite it with your local project.`
: `Push rejected. The remote repository has changes you don't have locally. Try pulling first.`;
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
{message}
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderPullButton()}
{/* Only show Pull button in sync context (not during initial configure) */}
{context === 'sync' && onPull && renderPullButton()}
{renderForcePushButton()}
</div>
</div>
@@ -126,17 +134,43 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
if (error instanceof GitErrors.HttpError) {
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
if (remoteUrl.protocol === 'nostr:') {
// Check if remoteUrl is a Nostr URL
if (remoteUrl?.protocol === 'nostr:') {
// This should never happen
getSentryInstance()?.captureException(error);
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
} else if (remoteUrl && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
// Handle standard HTTP errors based on status code
switch (error.data.statusCode) {
case 401:
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
message = context === 'configure'
? <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
: <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
message = context === 'configure'
? <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>
: <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
} else {
// No remoteUrl available or it's a standard HTTP/HTTPS URL
switch (error.data.statusCode) {
case 401:
message = <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
}
+1
View File
@@ -7,6 +7,7 @@ export interface AIProvider {
apiKey?: string;
nostr?: boolean;
proxy?: boolean;
openSecret?: string;
}
export interface MCPServer {
+8 -1
View File
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface RailwayProvider extends BaseDeployProvider {
type: 'railway';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export interface DeploySettings {
providers: DeployProvider[];
+13 -49
View File
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
import { useAISettings } from '@/hooks/useAISettings';
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
import type { AIMessage } from '@/lib/SessionManager';
import type OpenAI from 'openai';
import type { Tool } from '@/lib/tools/Tool';
@@ -39,35 +39,31 @@ export function useAIChat({
// Split session state into individual variables for efficient updates
const [messages, setMessages] = useState<AIMessage[]>([]);
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
const [sessionName, setSessionName] = useState<string>('');
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [totalCost, setTotalCost] = useState<number>(0);
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
const initSession = useCallback(async () => {
setIsLoadingHistory(true);
const initSession = useCallback(async (showLoading = true) => {
if (showLoading) {
setIsLoadingHistory(true);
}
try {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session
setMessages([...session.messages]);
setDisplayMessages([...session.displayMessages]);
setSessionName(session.sessionName);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
} finally {
setIsLoadingHistory(false);
if (showLoading) {
setIsLoadingHistory(false);
}
}
}, [sessionManager, projectId, tools, customTools, maxSteps]);
@@ -131,32 +127,14 @@ export function useAIChat({
}
}, [projectId]);
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
if (updatedProjectId === projectId) {
setDisplayMessages(prev => [...prev, message]);
}
}, [projectId]);
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
if (updatedProjectId === projectId) {
setDisplayMessages(prev => [...newMessages, ...prev]);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
}
}, [projectId, sessionManager]);
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
if (updatedProjectId === projectId) {
setIsLoadingMoreHistory(loading);
}
}, [projectId]);
// Actions
const sendMessage = useCallback(async (
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
providerModel: string
) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
@@ -169,7 +147,8 @@ export function useAIChat({
const startGeneration = useCallback(async (providerModel: string) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
@@ -191,13 +170,7 @@ export function useAIChat({
const startNewSession = useCallback(async () => {
await sessionManager.startNewSession(projectId);
// Get the updated session to retrieve the new session name
const session = sessionManager.getSession(projectId);
if (session) {
setSessionName(session.sessionName);
}
// Reset only AI prompt state (not display state which is handled via events)
// Reset individual state variables
setMessages([]);
setStreamingMessage(undefined);
setTotalCost(0);
@@ -210,19 +183,11 @@ export function useAIChat({
await startNewSession();
}, [startNewSession]);
const loadMoreHistory = useCallback(async () => {
await sessionManager.loadOlderSession(projectId);
}, [projectId, sessionManager]);
return {
messages,
displayMessages,
sessionName,
streamingMessage,
isLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
@@ -232,7 +197,6 @@ export function useAIChat({
clearMessages,
startNewSession,
addMessage,
loadMoreHistory,
isConfigured,
projectId
};
+1 -1
View File
@@ -30,7 +30,7 @@ export function useGitHubOAuth() {
redirectUri: window.location.origin + '/oauth/github',
usePKCE: true, // GitHub supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.github.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -30,7 +30,7 @@ export function useNetlifyOAuth() {
redirectUri: window.location.origin + '/oauth/netlify',
usePKCE: false, // Netlify doesn't support PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+4 -2
View File
@@ -5,12 +5,14 @@ import { useCurrentUser } from "./useCurrentUser";
import type { NostrEvent } from "@nostrify/nostrify";
export function useNostrPublish(): UseMutationResult<NostrEvent> {
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
mutationFn: async (t: NostrEventInput) => {
if (user) {
const tags = t.tags ?? [];
+1 -1
View File
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
}
// Exchange code for access token
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
+2 -1
View File
@@ -1,7 +1,8 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPluginSkills } from '@/lib/skills';
import { useGit } from './useGit';
import { join } from 'path-browserify';
+13
View File
@@ -52,6 +52,17 @@ const denoDeployProjectConfigSchema = z.object({
}),
});
const railwayProjectConfigSchema = z.object({
type: z.literal('railway'),
url: z.string(),
data: z.object({
workspaceId: z.string().optional(),
projectId: z.string().optional(),
environmentId: z.string().optional(),
serviceId: z.string().optional(),
}),
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
nsiteProjectConfigSchema,
@@ -59,6 +70,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
railwayProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -72,6 +84,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
+43
View File
@@ -0,0 +1,43 @@
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;
}
+1 -1
View File
@@ -34,7 +34,7 @@ export function useVercelOAuth() {
redirectUri: window.location.origin + '/oauth/vercel',
usePKCE: false, // Vercel doesn't require PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+67
View File
@@ -27,6 +27,73 @@ describe('DotAI', () => {
dotAI = new DotAI(mockFS, '/test-project');
});
describe('readLastSessionHistory', () => {
it('should return null when history directory does not exist', async () => {
// Mock historyDirExists to return false
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when no session files exist', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
vi.mocked(mockFS.readdir).mockResolvedValue([]);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return messages and session name from most recent file', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue([
'2024-08-24T16-30-45Z-abc.jsonl',
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
'2024-08-24T15-00-00Z-xyz.jsonl'
]);
// Mock readFile to return JSONL content
const mockContent = `{"role":"user","content":"Hello"}
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
expect(result?.messages).toHaveLength(2);
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
// Mock readFile to return content with malformed JSON
const mockContent = `{"role":"user","content":"Hello"}
invalid json line
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
});
describe('setHistory', () => {
it('should create history directory if it does not exist', async () => {
// Mock historyDirExists to return false initially
+52 -36
View File
@@ -216,50 +216,66 @@ export class DotAI {
}
/**
* List all session names sorted chronologically (oldest first)
* Fast operation - does not load message content
* @returns Array of session names (filenames without .jsonl extension)
* Read the most recent session history
* @returns Object containing messages array and session name, or null if no history found
*/
async listSessionNames(): Promise<string[]> {
async readLastSessionHistory(): Promise<{
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
sessionName: string;
} | null> {
try {
// Check if history directory exists
if (!(await this.historyDirExists())) {
return [];
return null;
}
const files = await this.fs.readdir(this.historyDir);
return files
.filter(file => file.endsWith('.jsonl'))
.map(file => file.replace('.jsonl', ''))
.sort(); // Chronological order (oldest first) - filenames contain timestamps
} catch {
return [];
}
}
// Find the most recent session file
try {
const files = await this.fs.readdir(this.historyDir);
const sessionFiles = files
.filter(file => file.endsWith('.jsonl'))
.sort()
.reverse(); // Most recent first
/**
* Read messages for a single session
* @param sessionName The session name (filename without .jsonl)
* @returns Array of messages, or empty array if session not found
*/
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
try {
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch {
// Skip malformed lines
if (sessionFiles.length === 0) {
return null;
}
}
return messages;
} catch {
return [];
const latestSessionFile = sessionFiles[0];
const sessionPath = join(this.historyDir, latestSessionFile);
try {
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch (parseError) {
console.warn('Failed to parse message from history:', parseError);
}
}
// Return session name without .jsonl extension
const sessionName = latestSessionFile.replace('.jsonl', '');
return {
messages,
sessionName
};
} catch (readError) {
console.warn('Failed to read session file:', readError);
return null;
}
} catch (readdirError) {
console.warn('Failed to read history directory:', readdirError);
return null;
}
} catch (error) {
console.warn('Failed to read last session history:', error);
return null;
}
}
-371
View File
@@ -1,371 +0,0 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { KindGenerator } from './KindGenerator.ts';
const __dirname = dirname(fileURLToPath(import.meta.url));
describe('KindGenerator', () => {
it('should extract used kinds from real NIPs fixture', () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Check that some expected kinds are extracted from the real NIPs index
const expectedKinds = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
20,
21,
22,
30,
31,
32,
33,
40,
41,
42,
43,
44,
62,
64,
818,
1018,
1021,
1022,
1040,
1059,
1063,
1068,
1111,
1311,
1337,
1617,
1621,
1622,
1971,
1984,
1985,
1986,
1987,
2003,
2004,
2022,
4550,
7000,
7374,
7375,
7376,
9041,
9321,
9467,
9734,
9735,
9802,
10000,
10001,
10002,
10003,
10004,
10005,
10006,
10007,
10009,
10012,
10013,
10015,
10019,
10020,
10030,
10050,
10063,
10096,
10166,
13194,
17375,
21000,
22242,
23194,
23195,
24133,
24242,
27235,
30000,
30001,
30002,
30003,
30004,
30005,
30007,
30008,
30009,
30015,
30017,
30018,
30019,
30020,
30023,
30024,
30030,
30040,
30041,
30063,
30078,
30166,
30267,
30311,
30315,
30388,
30402,
30403,
30617,
30618,
30818,
30819,
31234,
31388,
31890,
31922,
31923,
31924,
31925,
31989,
31990,
32267,
34550,
38383,
39089,
39092,
39701,
];
for (const kind of expectedKinds) {
expect(usedKinds.has(kind)).toBe(true);
}
// Check that ranges are properly extracted
// `5000`-`5999` should add all numbers from 5000 to 5999
for (let i = 5000; i <= 5999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `6000`-`6999` should add all numbers from 6000 to 6999
for (let i = 6000; i <= 6999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `9000`-`9030` should add all numbers from 9000 to 9030
for (let i = 9000; i <= 9030; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `39000-9` should add all numbers from 39000 to 39009
for (let i = 39000; i <= 39009; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `1630`-`1633` should add all numbers from 1630 to 1633
for (let i = 1630; i <= 1633; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should extract used kinds from mock data', () => {
const mockNipsIndex = `
## Event Kinds
| kind | description | NIP |
| ------------- | ------------------------------- | -------------------------------------- |
| \`0\` | User Metadata | [01](01.md) |
| \`1\` | Short Text Note | [10](10.md) |
| \`3\` | Follows | [02](02.md) |
| \`1000\`-\`1999\` | Custom Range | [test](test.md) |
| \`30000\` | Addressable Event | [51](51.md) |
`;
const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex);
// Check individual kinds
expect(usedKinds.has(0)).toBe(true);
expect(usedKinds.has(1)).toBe(true);
expect(usedKinds.has(3)).toBe(true);
expect(usedKinds.has(30000)).toBe(true);
// Check range
for (let i = 1000; i <= 1999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should get kind range info correctly', () => {
const regularRange = KindGenerator.getKindRangeInfo('regular');
expect(regularRange.min).toBe(1000);
expect(regularRange.max).toBe(9999);
expect(regularRange.name).toBe('Regular Events');
const replaceableRange = KindGenerator.getKindRangeInfo('replaceable');
expect(replaceableRange.min).toBe(10000);
expect(replaceableRange.max).toBe(19999);
const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral');
expect(ephemeralRange.min).toBe(20000);
expect(ephemeralRange.max).toBe(29999);
const addressableRange = KindGenerator.getKindRangeInfo('addressable');
expect(addressableRange.min).toBe(30000);
expect(addressableRange.max).toBe(39999);
});
it('should generate available kinds in correct ranges', () => {
const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]);
// Test regular range
const regularKind = KindGenerator.generateAvailableKind(
'regular',
usedKinds,
);
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
// Check new constraints
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
// Check buffer constraint - should not be within 2 of any used kind
for (const usedKind of usedKinds) {
const distance = Math.abs(regularKind - usedKind);
expect(distance > 2).toBe(true);
}
// Test replaceable range
const replaceableKind = KindGenerator.generateAvailableKind(
'replaceable',
usedKinds,
);
expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true);
expect(usedKinds.has(replaceableKind)).toBe(false);
expect(replaceableKind % 2 !== 0).toBe(true);
expect(replaceableKind % 5 !== 0).toBe(true);
// Test ephemeral range
const ephemeralKind = KindGenerator.generateAvailableKind(
'ephemeral',
usedKinds,
);
expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true);
expect(usedKinds.has(ephemeralKind)).toBe(false);
expect(ephemeralKind % 2 !== 0).toBe(true);
expect(ephemeralKind % 5 !== 0).toBe(true);
// Test addressable range
const addressableKind = KindGenerator.generateAvailableKind(
'addressable',
usedKinds,
);
expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true);
expect(usedKinds.has(addressableKind)).toBe(false);
expect(addressableKind % 2 !== 0).toBe(true);
expect(addressableKind % 5 !== 0).toBe(true);
});
it('should respect buffer constraints when generating kinds', () => {
// Test buffer constraint specifically
const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should be in range
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
// Should be odd
expect(regularKind % 2 !== 0).toBe(true);
// Should not be multiple of 5
expect(regularKind % 5 !== 0).toBe(true);
// Should not be within buffer of used kinds
const forbiddenNumbers = new Set([
1005, 1006, 1007, 1008, 1009, // around 1007
1011, 1012, 1013, 1014, 1015, // around 1013
1017, 1018, 1019, 1020, 1021, // around 1019
]);
expect(forbiddenNumbers.has(regularKind)).toBe(false);
});
it('should handle edge cases with many used kinds', () => {
// Test with many used kinds to ensure we still find valid ones
const usedKinds = new Set<number>();
// Fill most even numbers and multiples of 5 in a small range
for (let i = 1000; i <= 1100; i++) {
if (i % 2 === 0 || i % 5 === 0) {
usedKinds.add(i);
}
}
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should still find a valid kind
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
});
it('should generate random kinds with good distribution', { timeout: 10000 }, () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Generate many kinds and check distribution
const results = new Map<number, number>();
const iterations = 50; // Reduced from 100 to 50 for performance
for (let i = 0; i < iterations; i++) {
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
results.set(kind, (results.get(kind) || 0) + 1);
// Verify constraints on each generated kind
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
expect(usedKinds.has(kind)).toBe(false);
}
// Check that we get good variety (at least 5 unique kinds in 50 iterations)
// Reduced expectations due to fewer iterations
expect(results.size).toBeGreaterThanOrEqual(5);
// Check that no single kind dominates (no kind should appear more than 50% of the time)
// Increased threshold due to fewer iterations
const maxFrequency = Math.max(...results.values());
const maxFrequencyPercent = (maxFrequency / iterations) * 100;
expect(maxFrequencyPercent).toBeLessThanOrEqual(50);
// Check that all generated kinds follow our constraints
for (const [kind] of results) {
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
// Check buffer constraint
for (const usedKind of usedKinds) {
const distance = Math.abs(kind - usedKind);
expect(distance > 2).toBe(true);
}
}
});
});
+50 -120
View File
@@ -24,20 +24,12 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
/** AIMessage with session tracking for UI display */
export type DisplayMessage = AIMessage & {
sessionId?: string; // Session identifier for grouping messages in UI
};
export interface SessionState {
projectId: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
maxSteps?: number;
messages: AIMessage[]; // Current session messages (sent to AI)
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
availableSessionNames: string[]; // All session names (for lazy loading)
loadedSessionCount: number; // How many sessions loaded from the end
messages: AIMessage[];
streamingMessage?: {
role: 'assistant';
content: string;
@@ -45,7 +37,6 @@ export interface SessionState {
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
isLoadingMoreHistory: boolean; // Loading older sessions
sessionName: string;
lastActivity: Date;
abortController?: AbortController;
@@ -59,11 +50,8 @@ export interface SessionManagerEvents {
sessionCreated: (projectId: string) => void;
sessionDeleted: (projectId: string) => void;
messageAdded: (projectId: string, message: AIMessage) => void;
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (projectId: string, isLoading: boolean) => void;
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
costUpdated: (projectId: string, totalCost: number) => void;
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
fileChanged: (projectId: string, filePath: string) => void;
@@ -109,7 +97,7 @@ export class SessionManager {
}
/**
* Create a new session for a project (lazy loading - only loads most recent session)
* Create a new session for a project
*/
async loadSession(
projectId: string,
@@ -117,39 +105,18 @@ export class SessionManager {
customTools: Record<string, Tool<unknown>>,
maxSteps?: number
): Promise<SessionState> {
const messages: AIMessage[] = [];
const displayMessages: DisplayMessage[] = [];
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
let sessionName = DotAI.generateSessionName();
let availableSessionNames: string[] = [];
let loadedSessionCount = 0;
let lastFinishReason: string | null | undefined;
// Try to load existing history (lazy - only load last session)
// Try to load existing history
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Get all available session names (fast - no content loading)
availableSessionNames = await dotAI.listSessionNames();
if (availableSessionNames.length > 0) {
// Only load the most recent session
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
if (lastSessionMessages.length > 0) {
// Add messages with sessionId annotation
for (const msg of lastSessionMessages) {
displayMessages.push({
...msg as AIMessage,
sessionId: lastSessionName,
});
}
messages.push(...lastSessionMessages as AIMessage[]);
sessionName = lastSessionName;
loadedSessionCount = 1;
}
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
sessionName = lastSession.sessionName;
}
// Load last finish reason
@@ -164,33 +131,21 @@ export class SessionManager {
customTools,
maxSteps,
isLoading: false,
isLoadingMoreHistory: false,
lastActivity: new Date(),
totalCost: 0,
lastInputTokens: 0,
lastFinishReason,
...this.sessions.get(projectId),
messages,
displayMessages,
availableSessionNames,
loadedSessionCount,
sessionName,
};
// Update session configuration
session.projectId = projectId;
session.tools = tools;
session.customTools = customTools;
session.maxSteps = maxSteps;
// Update messages from loaded history if not already set by an existing session
if (!this.sessions.has(projectId)) {
session.messages = messages;
session.displayMessages = displayMessages;
session.availableSessionNames = availableSessionNames;
session.loadedSessionCount = loadedSessionCount;
session.sessionName = sessionName;
}
this.sessions.set(projectId, session);
@@ -232,69 +187,11 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
// Add to current session messages (for AI prompts)
session.messages.push(message);
// Also add to display messages with session ID annotation (for UI)
const displayMessage: DisplayMessage = { ...message, sessionId: session.sessionName };
session.displayMessages.push(displayMessage);
session.lastActivity = new Date();
await this.saveSessionHistory(projectId);
this.emit('messageAdded', projectId, message);
this.emit('displayMessageAdded', projectId, displayMessage);
}
/**
* Check if there are more historical sessions to load
*/
hasMoreHistory(projectId: string): boolean {
const session = this.sessions.get(projectId);
if (!session) return false;
return session.loadedSessionCount < session.availableSessionNames.length;
}
/**
* Load the next older session and prepend to displayMessages
*/
async loadOlderSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
session.isLoadingMoreHistory = true;
this.emit('loadingMoreHistoryChanged', projectId, true);
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Get the next older session (counting from the end)
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
if (nextIndex < 0) return;
const olderSessionName = session.availableSessionNames[nextIndex];
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
if (olderMessages.length > 0) {
// Create display messages with sessionId
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
...msg as AIMessage,
sessionId: olderSessionName,
}));
// Prepend to displayMessages
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
session.loadedSessionCount++;
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
}
} catch (error) {
console.warn('Failed to load older session:', error);
} finally {
session.isLoadingMoreHistory = false;
this.emit('loadingMoreHistoryChanged', projectId, false);
}
}
/**
@@ -764,7 +661,7 @@ export class SessionManager {
console.error('AI generation error:', error);
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
return; // User cancelled
}
@@ -802,7 +699,7 @@ export class SessionManager {
}
/**
* Start a new session (clear AI messages but keep display history)
* Start a new session (clear messages but keep configuration)
*/
async startNewSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
@@ -810,13 +707,9 @@ export class SessionManager {
this.stopGeneration(projectId);
// Generate new session name - new messages will automatically get this sessionId
const newSessionName = DotAI.generateSessionName();
// Clear only the AI prompt messages (not display messages)
session.messages = [];
session.streamingMessage = undefined;
session.sessionName = newSessionName;
session.sessionName = DotAI.generateSessionName();
session.lastActivity = new Date();
session.totalCost = 0;
session.lastInputTokens = 0;
@@ -827,13 +720,50 @@ export class SessionManager {
this.emit('finishReasonChanged', projectId, null);
}
/**
* Check if content exceeds size/line limits
*/
private exceedsLimits(content: string): boolean {
const MAX_SIZE_BYTES = 50 * 1024; // 50 KiB
const MAX_LINES = 2000;
const sizeBytes = new Blob([content]).size;
const lineCount = content.split('\n').length;
return sizeBytes > MAX_SIZE_BYTES || lineCount > MAX_LINES;
}
/**
* Save content to tmpDir and return the file path
*/
private async saveToTmpFile(projectId: string, content: string, toolCallId: string): Promise<string> {
const config = this.getConfig();
const timestamp = Date.now();
const filename = `tool-output-${toolCallId}-${timestamp}.txt`;
const filepath = `${config.fsPathTmp}/${filename}`;
await this.fs.writeFile(filepath, content, 'utf8');
return filepath;
}
/**
* Helper to add tool messages and update conversation
*/
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
let finalContent = content;
// Check if content exceeds limits
if (this.exceedsLimits(content)) {
// Save full content to tmp file
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
// Create placeholder message
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse \`grep\` to search the full content or \`read\` with offset/limit to view specific sections.`;
}
const toolMessage: AIMessage = {
role: 'tool',
content,
content: finalContent,
tool_call_id: toolCallId
};
+9 -5
View File
@@ -12,15 +12,19 @@ import { proxyUrl } from './proxyUrl';
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
*/
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
const openai = new OpenAI({
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
};
const openai = new OpenAI({
...baseConfig,
fetch: async (input, init) => {
// OpenSecret auth
// https://docs.opensecret.cloud/docs/maple-ai/
if (provider.openSecret) {
const { createCustomFetch } = await import('@opensecret/react');
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
}
let request = new Request(input, init);
// Add OpenRouter headers
@@ -47,7 +51,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
if (provider.proxy && corsProxy) {
request = new Request(proxyUrl(corsProxy, request.url), request);
request = new Request(proxyUrl({ template: corsProxy, url: request.url }), request);
}
return fetch(request);
+16 -7
View File
@@ -6,6 +6,7 @@ export interface PresetProvider {
nostr?: boolean;
tosURL?: string;
proxy?: boolean;
openSecret?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -16,13 +17,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://ai.shakespeare.diy/terms",
nostr: true,
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "opencode",
name: "OpenCode Zen",
@@ -31,6 +25,21 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://opencode.ai/legal/terms-of-service",
proxy: true,
},
{
id: "maple",
name: "Maple AI",
baseURL: "https://enclave.trymaple.ai/v1",
apiKeysURL: "https://trymaple.ai/",
tosURL: "https://opensecret.cloud/terms",
openSecret: "https://enclave.trymaple.ai",
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "ppq",
name: "PayPerQ",
+21 -1
View File
@@ -158,7 +158,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
let current: string | undefined = base;
while (current && current.length) {
// Remove the last package from the path (handling scoped packages like @scope/name)
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
const next: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
if (next === current) break;
current = next;
const candidate = `${current}/node_modules/${name}`;
@@ -226,6 +226,11 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
};
case "crypto":
return {
path: `${esmUrl}/crypto-browserify?target=${target ?? "esnext"}`,
namespace: "esm",
};
default:
return {
errors: [{ text: `Module not found: ${args.path}` }],
@@ -260,6 +265,19 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// not a URL; continue
}
// Check if this is a file: dependency
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Let fsPlugin handle file: dependencies
return;
}
// Determine importer lock path (breadcrumb)
const importerLockPath = getImporterLockPath(args.importer);
@@ -430,6 +448,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
if (contentType) {
if (contentType === "application/javascript") {
loader = "js";
} else if (contentType === "application/json") {
loader = "json";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
+94 -13
View File
@@ -10,14 +10,21 @@ interface TsConfig {
};
}
interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
interface FsPluginOptions {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig } = options;
const { fs, cwd, tsconfig, packageJson } = options;
return {
name: "fs",
@@ -30,27 +37,66 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
});
build.onResolve({ filter: /.*/ }, async (args) => {
// Skip resolving paths from external URLs
// Skip resolving paths from external URLs (but not fs: namespace)
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string;
let resolved: string | undefined;
// Handle absolute paths
if (args.path.startsWith("/")) {
resolved = args.path;
} else if (args.path.startsWith("@/")) {
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else {
}
// Nothing matched, let other plugins handle it
else {
return;
}
// Security: prevent accessing files outside the project directory
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
if (!resolved) {
return;
}
// Vite query parameters https://vite.dev/guide/assets
@@ -114,8 +160,43 @@ async function tryFileVariants(
return basePath;
}
// If it's a directory, try index files
// If it's a directory, try package.json first, then index files
if (stat.isDirectory()) {
// Try to read package.json for entry point
try {
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
const entryExtStat = await statSafe(fs, entryWithExt);
if (entryExtStat.isFile()) {
return entryWithExt;
}
}
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
+60 -1
View File
@@ -130,7 +130,7 @@ describe('buildProject', () => {
});
vi.mocked(mockFS.readdir)
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
if (path === '/test/project/public') {
return [
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
@@ -535,4 +535,63 @@ react@^18.0.0:
// Verify tsconfig.json was attempted to be read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8');
});
it('should support file: dependencies in package.json', async () => {
const packageJsonWithFileDeps = JSON.stringify({
name: "test-project",
dependencies: {
"@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh",
"react": "^18.2.0"
}
});
// Mock required files
vi.mocked(mockFS.readFile)
.mockImplementation(async (path: string) => {
if (path.endsWith('package.json')) {
return packageJsonWithFileDeps;
}
if (path.endsWith('index.html')) {
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
}
if (path.endsWith('package-lock.json')) {
return '{"dependencies": {}}';
}
throw new Error(`File not found: ${path}`);
});
// Mock stat to indicate no public directory
vi.mocked(mockFS.stat)
.mockImplementation(async (path: string) => {
if (path === '/test/project/public') {
throw new Error('Directory not found');
}
return { isDirectory: () => false, isFile: () => true };
});
// Mock additional filesystem operations for buildProject
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
if (path === '/test/project/dist') {
return [];
}
return [];
});
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await buildProject({
fs: mockFS,
projectPath: '/test/project',
domParser: mockDOMParser,
esmUrl: 'https://esm.shakespeare.diy',
});
// Should successfully build with file: dependencies
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
+113 -57
View File
@@ -10,6 +10,7 @@ import { fsPlugin } from "./fsPlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { Plugin } from 'esbuild-wasm';
export interface BuildProjectOptions {
fs: JSRuntimeFS;
@@ -20,6 +21,115 @@ export interface BuildProjectOptions {
esmUrl: string;
}
export interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
export interface PackageLock {
packages: {
[key: string]: {
name?: string;
version: string;
dependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
} | undefined;
};
}
export interface TsConfig {
compilerOptions?: {
baseUrl?: string;
paths?: Record<string, string[]>;
};
}
export interface BuildContext {
packageJson: PackageJson;
packageLock: PackageLock;
tsconfig?: TsConfig;
}
/**
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
* Exported for use by deployment adapters that need to bundle workers
*/
export async function readBuildContext(
fs: JSRuntimeFS,
projectPath: string,
): Promise<BuildContext> {
// Read package.json
let packageJson: PackageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig: TsConfig | undefined;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock: PackageLock;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
console.log(`Building with npm (package-lock.json)`);
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
console.log(`Building with yarn (yarn.lock)`);
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
console.log(`Building with package.json only (no lock file)`);
}
}
return { packageJson, packageLock, tsconfig };
}
/**
* Create the common esbuild plugins for both project and worker builds
* Exported for use by deployment adapters that need to bundle workers
*/
export function createPlugins(
fs: JSRuntimeFS,
projectPath: string,
context: BuildContext,
esmUrl: string,
target?: string,
): Plugin[] {
return [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
];
}
async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
@@ -31,58 +141,8 @@ async function bundle(
"utf8",
);
// Read package.json
let packageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
console.log(`Building with ${buildMode}`);
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(fs, projectPath);
const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
@@ -128,11 +188,7 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
define: {
"import.meta.env": JSON.stringify({}),
},
+7 -4
View File
@@ -1,7 +1,7 @@
import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl } from './imageUtils';
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
@@ -41,8 +41,11 @@ export async function buildMessageContent(
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
// Resize image if needed before processing
const processedFile = await resizeImageIfNeeded(file);
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
const savedPath = await saveFileToTmp(fs, processedFile, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
@@ -51,10 +54,10 @@ export async function buildMessageContent(
};
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = file.type.startsWith('image/');
const isImage = processedFile.type.startsWith('image/');
if (isImage) {
try {
const imageUrl = await fileToUrl(file);
const imageUrl = await fileToUrl(processedFile);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
+1 -1
View File
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
// Prepare request
const requestInit: RequestInit = {
+1 -1
View File
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
// Create the directory
await this.fs.mkdir(absolutePath);
} else {
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ export class TouchCommand implements ShellCommand {
await this.fs.writeFile(absolutePath, '', 'utf8');
} else {
// Other error (permission, etc.)
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
+8
View File
@@ -37,6 +37,7 @@ const aiProviderSchema = z.object({
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
proxy: z.boolean().optional(),
openSecret: z.string().url().optional(),
});
const providerModelSchema = z.string().regex(
@@ -129,6 +130,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
baseDomain: z.string().optional(),
});
const railwayProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('railway'),
apiKey: z.string(),
baseURL: z.string().optional(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
@@ -136,6 +143,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
railwayProviderSchema,
]);
const deploySettingsSchema = z.object({
+150 -23
View File
@@ -1,6 +1,10 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
import { parse as parseJsonc } from 'jsonc-parser';
import { join } from 'path-browserify';
import { readBuildContext, createPlugins } from '../build';
import { getEsbuild } from '../esbuild';
interface AssetManifest {
[path: string]: { hash: string; size: number };
@@ -24,6 +28,16 @@ interface WorkerScript {
has_assets: boolean;
}
interface WranglerConfig {
compatibility_date?: string;
main?: string;
assets?: {
directory?: string;
html_handling?: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none';
not_found_handling?: 'single-page-application' | '404-page' | 'none';
};
}
interface FileInfo {
hash: string;
content: Uint8Array;
@@ -49,6 +63,7 @@ export class CloudflareAdapter implements DeployAdapter {
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
private esmUrl: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
@@ -58,11 +73,15 @@ export class CloudflareAdapter implements DeployAdapter {
this.baseDomain = config.baseDomain || 'workers.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
this.esmUrl = config.esmUrl;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Try to read wrangler.jsonc configuration
const wranglerConfig = await this.readWranglerConfig(projectPath);
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
@@ -115,7 +134,7 @@ export class CloudflareAdapter implements DeployAdapter {
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt);
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
@@ -140,7 +159,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -160,7 +179,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -185,7 +204,7 @@ export class CloudflareAdapter implements DeployAdapter {
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -211,7 +230,7 @@ export class CloudflareAdapter implements DeployAdapter {
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const formData = new FormData();
@@ -249,37 +268,105 @@ export class CloudflareAdapter implements DeployAdapter {
return data.result || {};
}
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
const esbuild = await getEsbuild();
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
const workerScript = `
export default {
async fetch(request, env) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(this.fs, projectPath);
// Resolve the entry point path
const entryPointPath = entryPoint.startsWith('/')
? entryPoint
: join(projectPath, entryPoint);
// Build the worker with dependencies bundled
const results = await esbuild.build({
entryPoints: [entryPointPath],
bundle: true,
write: false,
format: "esm",
target: "esnext",
outdir: "/",
metafile: true,
sourcemap: false, // Workers typically don't need sourcemaps
plugins: createPlugins(this.fs, projectPath, context, this.esmUrl),
define: {
"import.meta.env": JSON.stringify({}),
},
});
if (results.outputFiles.length === 0) {
throw new Error(`Failed to bundle worker: no output files generated`);
}
// Return the bundled worker code as a string
return results.outputFiles[0].text;
}
};
`;
private async deployWorker(
scriptName: string,
assetsJwt: string,
projectPath: string,
wranglerConfig?: WranglerConfig
): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Determine the main module name from wrangler.jsonc or try defaults
let mainModuleName = 'worker.js';
let workerScript = this.getDefaultWorkerScript();
if (wranglerConfig?.main) {
// Use explicitly configured main module
const configuredModule = wranglerConfig.main;
try {
const workerExists = await this.fileExists(join(projectPath, configuredModule));
if (workerExists) {
mainModuleName = configuredModule;
workerScript = await this.bundleWorker(configuredModule, projectPath);
} else {
throw new Error(`Configured worker file not found: ${configuredModule}`);
}
} catch (error) {
console.warn(`Failed to bundle configured worker script, using default:`, error);
// Keep default values
}
} else {
// Try default worker files in order: worker.ts -> worker.mjs -> worker.js
const defaultWorkerFiles = ['worker.ts', 'worker.mjs', 'worker.js'];
for (const filename of defaultWorkerFiles) {
try {
const workerExists = await this.fileExists(join(projectPath, filename));
if (workerExists) {
mainModuleName = filename;
workerScript = await this.bundleWorker(filename, projectPath);
break; // Successfully bundled, stop searching
}
} catch (error) {
console.warn(`Failed to bundle ${filename}:`, error);
// Continue to next file
}
}
// If no custom worker found, use default values already set
}
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append('worker.js', scriptBlob, 'worker.js');
formData.append(mainModuleName, scriptBlob, mainModuleName);
// Add metadata with assets configuration
const metadata = {
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
main_module: mainModuleName,
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
},
},
};
@@ -303,6 +390,27 @@ export default {
return data.result;
}
private async readWranglerConfig(projectPath: string): Promise<WranglerConfig | undefined> {
// Try wrangler.jsonc first, then wrangler.json
const configPaths = [
join(projectPath, 'wrangler.jsonc'),
join(projectPath, 'wrangler.json'),
];
for (const configPath of configPaths) {
try {
const configContent = await this.fs.readFile(configPath, 'utf8');
// Parse JSONC (JSON with comments) using jsonc-parser
return parseJsonc(configContent) as WranglerConfig;
} catch {
// Continue to next path
}
}
// No wrangler config found, return undefined
return undefined;
}
private async collectFiles(
dirPath: string,
relativePath: string,
@@ -403,4 +511,23 @@ export default {
};
return mimeTypes[ext] || 'application/octet-stream';
}
private async fileExists(path: string): Promise<boolean> {
try {
const stat = await this.fs.stat(path);
return stat.isFile();
} catch {
return false;
}
}
private getDefaultWorkerScript(): string {
return `export default {
async fetch(request) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
}
};`;
}
}
+3 -3
View File
@@ -96,7 +96,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -116,7 +116,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -143,7 +143,7 @@ export class DenoDeployAdapter implements DeployAdapter {
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
+198 -29
View File
@@ -11,11 +11,13 @@ interface NetlifySite {
admin_url: string;
}
interface NetlifyBuildResponse {
interface NetlifyDeployResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
required?: string[];
required_functions?: string[];
}
/**
@@ -65,31 +67,47 @@ export class NetlifyAdapter implements DeployAdapter {
siteUrl = site.url;
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Collect files and their SHA1 hashes
const files: Record<string, string> = {};
const fileContents = new Map<string, Uint8Array>();
await this.collectFiles(distPath, '', files, fileContents);
// Ensure _redirects file exists for SPA routing
await this.ensureRedirectsFile(distPath, zip);
await this.ensureRedirectsInFiles(distPath, files, fileContents);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Collect functions and their SHA256 hashes
const functions: Record<string, string> = {};
const functionZips = new Map<string, Blob>();
const functionsPath = `${projectPath}/netlify/functions`;
await this.collectFunctions(functionsPath, functions, functionZips);
// Deploy to Netlify
await this.triggerDeploy(activeSiteId, zipBlob);
// Create deploy with file and function digests
const deployResponse = await this.createDeployWithDigest(activeSiteId, files, functions);
// Upload required files
if (deployResponse.required && deployResponse.required.length > 0) {
await this.uploadFiles(deployResponse.id, files, fileContents, deployResponse.required);
}
// Upload required functions
if (deployResponse.required_functions && deployResponse.required_functions.length > 0) {
await this.uploadFunctions(deployResponse.id, functions, functionZips, deployResponse.required_functions);
}
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
deployId: deployResponse.id,
provider: 'netlify',
functionsDeployed: Object.keys(functions).length,
},
};
}
private async createSite(name: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -113,7 +131,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async getSite(siteId: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites/${siteId}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -130,45 +148,57 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json();
}
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
private async createDeployWithDigest(
siteId: string,
files: Record<string, string>,
functions: Record<string, string>
): Promise<NetlifyDeployResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const body: { files: Record<string, string>; functions?: Record<string, string> } = { files };
if (Object.keys(functions).length > 0) {
body.functions = functions;
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/zip',
'Content-Type': 'application/json',
},
body: zipBlob,
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
private async collectFiles(
dirPath: string,
relativePath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
await this.collectFiles(fullPath, relPath, files, fileContents);
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
const sha1 = await this.calculateSHA1(fileContent);
files[`/${relPath}`] = sha1;
fileContents.set(sha1, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
@@ -181,9 +211,13 @@ export class NetlifyAdapter implements DeployAdapter {
/**
* Ensures _redirects file exists in the deployment for SPA routing
* If not present in dist directory, adds it to the ZIP with default content
* If not present in dist directory, adds it to the files manifest
*/
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
private async ensureRedirectsInFiles(
distPath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
const redirectsPath = `${distPath}/_redirects`;
try {
@@ -192,11 +226,146 @@ export class NetlifyAdapter implements DeployAdapter {
if (!stat.isFile()) {
throw new Error('_redirects is not a file');
}
// File exists, no need to add it (already added by addDirectoryToZip)
// File exists, already collected by collectFiles
} catch {
// File doesn't exist, add default _redirects to ZIP
// File doesn't exist, add default _redirects
const defaultRedirects = '/* /index.html 200';
zip.file('_redirects', defaultRedirects);
const content = new TextEncoder().encode(defaultRedirects);
const sha1 = await this.calculateSHA1(content);
files['/_redirects'] = sha1;
fileContents.set(sha1, content);
}
}
private async collectFunctions(
functionsPath: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>
): Promise<void> {
try {
// Check if functions directory exists
const stat = await this.fs.stat(functionsPath);
if (!stat.isDirectory()) {
return;
}
const entries = await this.fs.readdir(functionsPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile()) {
const fullPath = `${functionsPath}/${entry.name}`;
// Only process .mjs files (ES modules)
// Note: .js and .ts files require bundling which is not supported in this adapter
if (entry.name.endsWith('.mjs')) {
try {
const functionContent = await this.fs.readFile(fullPath);
// Create a zip for this function
const zip = new JSZip();
zip.file(entry.name, functionContent);
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Calculate SHA256 hash
const sha256 = await this.calculateSHA256FromBlob(zipBlob);
// Function name without extension
const functionName = entry.name.replace(/\.mjs$/, '');
functions[functionName] = sha256;
functionZips.set(sha256, zipBlob);
} catch (error) {
console.warn(`Failed to process function ${entry.name}:`, error);
}
}
}
}
} catch {
// Functions directory doesn't exist, skip
}
}
private async uploadFiles(
deployId: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [filePath, sha1] of Object.entries(files)) {
if (requiredSet.has(sha1)) {
const content = fileContents.get(sha1);
if (!content) {
console.warn(`Content not found for ${filePath} (${sha1})`);
continue;
}
// Escape file path for URL
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/');
const url = `${this.baseURL}/deploys/${deployId}/files${encodedPath}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: content,
});
if (!response.ok) {
console.warn(`Failed to upload file ${filePath}: ${response.status} ${response.statusText}`);
}
}
}
}
private async uploadFunctions(
deployId: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [functionName, sha256] of Object.entries(functions)) {
if (requiredSet.has(sha256)) {
const zipBlob = functionZips.get(sha256);
if (!zipBlob) {
console.warn(`Zip not found for function ${functionName} (${sha256})`);
continue;
}
const url = `${this.baseURL}/deploys/${deployId}/functions/${encodeURIComponent(functionName)}?runtime=js`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: zipBlob,
});
if (!response.ok) {
console.warn(`Failed to upload function ${functionName}: ${response.status} ${response.statusText}`);
}
}
}
}
private async calculateSHA1(data: Uint8Array): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
private async calculateSHA256FromBlob(blob: Blob): Promise<string> {
const arrayBuffer = await blob.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
}
+627
View File
@@ -0,0 +1,627 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, RailwayDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface Workspace {
id: string;
name: string;
team: {
id: string;
} | null;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: Environment;
}>;
};
services: {
edges: Array<{
node: Service;
}>;
};
}
interface Environment {
id: string;
name: string;
}
interface Service {
id: string;
name: string;
}
interface DeploymentResponse {
deploymentId: string;
url: string;
logsUrl?: string;
deploymentDomain: string;
}
/**
* Railway Deploy Adapter
* Uses Railway GraphQL API and REST upload endpoint
*
* Implements the Railway deployment workflow:
* 1. Query for workspaces and projects (or use provided IDs)
* 2. Create project if needed
* 3. Create service if needed
* 4. Create tarball of entire source code (excluding common dev files)
* 5. Upload tarball to Railway via multipart/form-data
*/
export class RailwayAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string;
private workspaceId?: string;
private projectId?: string;
private environmentId?: string;
private serviceId?: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: RailwayDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://backboard.railway.com';
this.workspaceId = config.workspaceId;
this.projectId = config.projectId;
this.environmentId = config.environmentId;
this.serviceId = config.serviceId;
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Step 1: Ensure we have a workspace
if (!this.workspaceId) {
const workspaces = await this.getWorkspaces();
if (workspaces.length === 0) {
throw new Error('No workspaces found. Please create a workspace on Railway first.');
}
this.workspaceId = workspaces[0].id;
}
// Step 2: Get or create project
let activeProjectId = this.projectId;
let activeEnvironmentId = this.environmentId;
if (!activeProjectId) {
const project = await this.createProject(this.projectName || projectId);
activeProjectId = project.id;
// Get the default production environment
activeEnvironmentId = project.environments.edges[0]?.node.id;
} else if (!activeEnvironmentId) {
// If we have project ID but no environment, fetch the project to get the environment
const project = await this.getProject(activeProjectId);
activeEnvironmentId = project.environments.edges[0]?.node.id;
}
if (!activeEnvironmentId) {
throw new Error('No environment found for project');
}
// Step 3: Get or create service
let activeServiceId = this.serviceId;
if (!activeServiceId) {
const service = await this.createService(activeProjectId, projectId);
activeServiceId = service.id;
}
// Step 4: Create tarball of source code
const tarball = await this.createTarball(projectPath);
// Step 5: Upload to Railway
const deployment = await this.uploadDeployment(
activeProjectId,
activeEnvironmentId,
activeServiceId,
tarball
);
// Step 6: Wait for deployment to complete
await this.waitForDeployment(deployment.deploymentId);
// Step 7: Check for existing domains and create one if needed
const domain = await this.ensureServiceDomain(
activeProjectId,
activeEnvironmentId,
activeServiceId
);
return {
url: domain ? `https://${domain}` : deployment.url,
metadata: {
deploymentId: deployment.deploymentId,
projectId: activeProjectId,
environmentId: activeEnvironmentId,
serviceId: activeServiceId,
provider: 'railway',
deploymentDomain: domain || deployment.deploymentDomain,
},
};
}
private async graphqlRequest<T>(query: string, variables?: Record<string, unknown>): Promise<T> {
const url = `${this.baseURL}/graphql/v2`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Railway GraphQL request failed: ${response.status} ${response.statusText}. ${errorText}`);
}
const result = await response.json();
if (result.errors) {
const errorMessages = result.errors.map((e: { message: string }) => e.message).join(', ');
throw new Error(`Railway GraphQL error: ${errorMessages}`);
}
return result.data;
}
private async getWorkspaces(): Promise<Workspace[]> {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
team {
id
}
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ me: { workspaces: Workspace[] } }>(query);
return data.me.workspaces;
}
private async getProject(projectId: string): Promise<Project> {
const query = `
query GetProject($projectId: String!) {
project(id: $projectId) {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ project: Project }>(query, { projectId });
return data.project;
}
private async createProject(name: string): Promise<Project> {
const query = `
mutation ProjectCreate($name: String, $workspaceId: String) {
projectCreate(input: {
name: $name,
workspaceId: $workspaceId
}) {
id
name
environments {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ projectCreate: Project }>(query, {
name,
workspaceId: this.workspaceId,
});
return data.projectCreate;
}
private async createService(projectId: string, name: string): Promise<Service> {
const query = `
mutation ServiceCreate($input: ServiceCreateInput!) {
serviceCreate(input: $input) {
id
name
}
}
`;
const data = await this.graphqlRequest<{ serviceCreate: Service }>(query, {
input: {
name,
projectId,
source: {
image: null,
repo: null,
},
},
});
return data.serviceCreate;
}
private async createTarball(projectPath: string): Promise<Blob> {
// Import tar library dynamically (needs to be available in the project)
// For browser environment, we'll need to use a tar implementation
// Using a simpler approach: collect files and create a tar-like structure
// Collect all files excluding common dev files
const files = new Map<string, Uint8Array>();
await this.collectFilesForTarball(projectPath, '', files);
// Create a simple tar.gz equivalent using browser APIs
// Since we're in a browser environment, we'll create a structure that Railway can accept
const tarData = await this.createTarGzBlob(files);
return tarData;
}
private async collectFilesForTarball(
dirPath: string,
relativePath: string,
files: Map<string, Uint8Array>
): Promise<void> {
// Directories to exclude
const excludeDirs = new Set([
'.git',
'node_modules',
'dist',
'build',
'.next',
'.nuxt',
'.output',
'.vite',
'.cache',
'__pycache__',
'.pytest_cache',
'.venv',
'venv',
'env',
'.DS_Store',
'coverage',
'.nyc_output',
]);
// Files to exclude
const excludeFiles = new Set([
'.env',
'.env.local',
'.env.development',
'.env.production',
'.env.test',
'npm-debug.log',
'yarn-debug.log',
'yarn-error.log',
'.DS_Store',
]);
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
// Skip excluded directories and files
if (excludeDirs.has(entry.name) || excludeFiles.has(entry.name)) {
continue;
}
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFilesForTarball(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
let bytes: Uint8Array;
if (typeof fileContent === 'string') {
bytes = new TextEncoder().encode(fileContent);
} else {
bytes = fileContent;
}
files.set(entryRelativePath, bytes);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private async createTarGzBlob(files: Map<string, Uint8Array>): Promise<Blob> {
// Create a simple tar structure
// TAR format: 512-byte header + file data (padded to 512 bytes)
const blocks: Uint8Array[] = [];
for (const [filePath, content] of files) {
// Create tar header (simplified)
const header = new Uint8Array(512);
const encoder = new TextEncoder();
// File name (offset 0, 100 bytes)
const nameBytes = encoder.encode(filePath);
header.set(nameBytes.slice(0, 100), 0);
// File mode (offset 100, 8 bytes) - "0000644\0"
header.set(encoder.encode('0000644\0'), 100);
// Owner UID (offset 108, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 108);
// Group GID (offset 116, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 116);
// File size in octal (offset 124, 12 bytes)
const sizeOctal = content.length.toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(sizeOctal), 124);
// Modification time (offset 136, 12 bytes)
const mtime = Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(mtime), 136);
// Checksum (offset 148, 8 bytes) - calculate after setting type flag
header.set(encoder.encode(' '), 148);
// Type flag (offset 156, 1 byte) - '0' for regular file
header.set(encoder.encode('0'), 156);
// Calculate checksum
let checksum = 0;
for (let i = 0; i < 512; i++) {
checksum += header[i];
}
const checksumOctal = checksum.toString(8).padStart(6, '0') + '\0 ';
header.set(encoder.encode(checksumOctal), 148);
blocks.push(header);
// Add file content, padded to 512-byte boundary
const paddedSize = Math.ceil(content.length / 512) * 512;
const paddedContent = new Uint8Array(paddedSize);
paddedContent.set(content);
blocks.push(paddedContent);
}
// Add two empty 512-byte blocks to mark end of archive
blocks.push(new Uint8Array(512));
blocks.push(new Uint8Array(512));
// Combine all blocks
const totalSize = blocks.reduce((sum, block) => sum + block.length, 0);
const tarData = new Uint8Array(totalSize);
let offset = 0;
for (const block of blocks) {
tarData.set(block, offset);
offset += block.length;
}
// Compress with gzip (using CompressionStream API)
const stream = new Blob([tarData]).stream();
const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
const compressedBlob = await new Response(compressedStream).blob();
return compressedBlob;
}
private async uploadDeployment(
projectId: string,
environmentId: string,
serviceId: string,
tarball: Blob
): Promise<DeploymentResponse> {
const url = `${this.baseURL}/project/${projectId}/environment/${environmentId}/up?serviceId=${serviceId}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Railway expects the raw tarball bytes with Content-Type: multipart/form-data
// NOT wrapped in FormData
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'multipart/form-data',
},
body: tarball,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to upload deployment to Railway: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async ensureServiceDomain(
projectId: string,
environmentId: string,
serviceId: string
): Promise<string | null> {
try {
// First, check if a domain already exists
const domainsQuery = `
query Domains($environmentId: String!, $projectId: String!, $serviceId: String!) {
domains(environmentId: $environmentId, projectId: $projectId, serviceId: $serviceId) {
serviceDomains {
id
domain
}
customDomains {
id
domain
}
}
}
`;
const domainsResult = await this.graphqlRequest<{
domains: {
serviceDomains: Array<{ id: string; domain: string }>;
customDomains: Array<{ id: string; domain: string }>;
};
}>(domainsQuery, {
environmentId,
projectId,
serviceId,
});
// If a domain already exists, return it
if (domainsResult.domains.serviceDomains.length > 0) {
return domainsResult.domains.serviceDomains[0].domain;
}
if (domainsResult.domains.customDomains.length > 0) {
return domainsResult.domains.customDomains[0].domain;
}
// No domain exists, create a Railway-provided domain
const createDomainMutation = `
mutation ServiceDomainCreate($environmentId: String!, $serviceId: String!) {
serviceDomainCreate(input: { environmentId: $environmentId, serviceId: $serviceId }) {
id
domain
}
}
`;
const createResult = await this.graphqlRequest<{
serviceDomainCreate: {
id: string;
domain: string;
};
}>(createDomainMutation, {
environmentId,
serviceId,
});
return createResult.serviceDomainCreate.domain;
} catch (error) {
console.warn('Failed to create/get service domain:', error);
// Return null to fall back to the dashboard URL
return null;
}
}
private async waitForDeployment(deploymentId: string): Promise<void> {
const query = `
query Deployment($id: String!) {
deployment(id: $id) {
id
status
}
}
`;
const maxAttempts = 180; // 15 minutes max (5 second intervals)
let attempts = 0;
while (attempts < maxAttempts) {
attempts++;
try {
const result = await this.graphqlRequest<{
deployment: {
id: string;
status: string;
};
}>(query, { id: deploymentId });
const status = result.deployment.status;
if (status === 'SUCCESS') {
return; // Deployment successful
}
if (status === 'FAILED') {
throw new Error('Deployment failed. Check the Railway dashboard for build logs.');
}
if (status === 'CRASHED') {
throw new Error('Deployment crashed. Check the Railway dashboard for logs.');
}
// Status is BUILDING, DEPLOYING, or other in-progress state
// Wait 5 seconds before checking again
await new Promise(resolve => setTimeout(resolve, 5000));
} catch (error) {
// If it's our thrown error, re-throw it
if (error instanceof Error && (error.message.includes('failed') || error.message.includes('crashed'))) {
throw error;
}
// Otherwise, wait and retry
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
throw new Error('Deployment timed out after 15 minutes. Check the Railway dashboard for status.');
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ export class ShakespeareAdapter implements DeployAdapter {
// Apply proxy if configured
if (this.corsProxy) {
request = new Request(proxyUrl(this.corsProxy, request.url), request);
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
}
// Deploy
+1 -1
View File
@@ -68,7 +68,7 @@ export class VercelAdapter implements DeployAdapter {
}
// Apply proxy if configured
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: apiUrl }) : apiUrl;
// Deploy to Vercel
const response = await fetch(targetUrl, {
+1
View File
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './RailwayAdapter';
+14 -1
View File
@@ -63,6 +63,7 @@ export interface CloudflareDeployConfig {
baseDomain?: string;
projectName?: string;
corsProxy?: string;
esmUrl: string;
}
export interface DenoDeployConfig {
@@ -75,9 +76,21 @@ export interface DenoDeployConfig {
corsProxy?: string;
}
export interface RailwayDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
baseURL?: string;
workspaceId?: string;
projectId?: string;
environmentId?: string;
serviceId?: string;
projectName?: string;
corsProxy?: string;
}
export interface PresetDeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
name: string;
description: string;
baseURL?: string;
+10
View File
@@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
{
id: 'railway',
type: 'railway',
name: 'Railway',
description: 'Deploy to Railway',
baseURL: 'https://backboard.railway.com',
apiKeyLabel: 'API Token',
apiKeyURL: 'https://railway.app/account/tokens',
proxy: true,
},
];
+11 -5
View File
@@ -1,15 +1,21 @@
import UriTemplate from 'uri-templates';
export interface FaviconUrlOpts {
template: string;
url: string | URL;
}
/**
* Generate a favicon URL from a template and input URL
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
* @param url - The URL to extract parts from
* @param opts - Options object
* @param opts.template - URL template with placeholders like {hostname}, {origin}, etc.
* @param opts.url - The URL to extract parts from
* @returns The hydrated favicon URL
*/
export function faviconUrl(template: string, url: string | URL): string {
const u = new URL(url);
export function faviconUrl(opts: FaviconUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+2 -2
View File
@@ -1107,7 +1107,7 @@ class GitHttp implements HttpClient {
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
this.proxy = proxy;
this.fetch = fetch ?? globalThis.fetch;
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
}
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
@@ -1115,7 +1115,7 @@ class GitHttp implements HttpClient {
const url = new URL(request.url);
const target = this.proxy
? proxyUrl(this.proxy, url)
? proxyUrl({ template: this.proxy, url })
: url.href;
const init: RequestInit = {
+140
View File
@@ -1,3 +1,143 @@
export interface ResizeOptions {
/** Maximum width or height in pixels (default: 2048) */
maxDimension?: number;
/** Maximum file size in bytes (default: 5MB) */
maxFileSize?: number;
/** JPEG quality 0-1 (default: 0.92) */
quality?: number;
}
/**
* Resizes an image file if it exceeds size or dimension limits.
*
* @param file - The image file to potentially resize
* @param opts - Resize options with defaults
* @returns Promise resolving to the original or resized File
*/
export async function resizeImageIfNeeded(file: File, opts: ResizeOptions = {}): Promise<File> {
const {
maxDimension = 2048,
maxFileSize = 5 * 1024 * 1024, // 5MB
quality = 0.92,
} = opts;
// Only process image files
if (!file.type.startsWith('image/')) {
return file;
}
// Check if resize is needed based on file size
const needsResize = file.size > maxFileSize;
if (!needsResize) {
// Still need to check dimensions
const dimensions = await getImageDimensions(file);
if (dimensions.width <= maxDimension && dimensions.height <= maxDimension) {
return file;
}
}
// Resize the image
return await resizeImage(file, maxDimension, quality);
}
/**
* Gets the dimensions of an image file.
*
* @param file - The image file
* @returns Promise resolving to width and height
*/
async function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
resolve({ width: img.width, height: img.height });
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image'));
};
img.src = url;
});
}
/**
* Resizes an image to fit within maxDimension while maintaining aspect ratio.
*
* @param file - The image file to resize
* @param maxDimension - Maximum width or height
* @param quality - JPEG quality 0-1
* @returns Promise resolving to resized File
*/
async function resizeImage(file: File, maxDimension: number, quality: number): Promise<File> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
// Calculate new dimensions maintaining aspect ratio
let { width, height } = img;
if (width > maxDimension || height > maxDimension) {
if (width > height) {
height = (height / width) * maxDimension;
width = maxDimension;
} else {
width = (width / height) * maxDimension;
height = maxDimension;
}
}
// Create canvas and draw resized image
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('Failed to get canvas context'));
return;
}
ctx.drawImage(img, 0, 0, width, height);
// Convert canvas to blob
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('Failed to create blob from canvas'));
return;
}
// Create new File from blob with original name
const resizedFile = new File([blob], file.name, {
type: file.type || 'image/jpeg',
lastModified: Date.now(),
});
resolve(resizedFile);
},
file.type || 'image/jpeg',
quality
);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image for resizing'));
};
img.src = url;
});
}
/**
* Converts a File to a base64-encoded data URL for API consumption.
*
+6 -6
View File
@@ -9,7 +9,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
});
@@ -20,7 +20,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1/);
});
@@ -31,7 +31,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe(`https://example.com/${pubkey}`);
});
@@ -42,7 +42,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe('https://example.com/my-repo');
});
@@ -53,7 +53,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1[^/]+\/my-repo$/);
});
@@ -65,7 +65,7 @@ describe('ngitWebUrl', () => {
const relay = 'wss://relay.example.com/';
const nostrURI = new NostrURI({ pubkey, identifier, relay });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
// The naddr should be longer when it includes relay information
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
+14 -8
View File
@@ -2,20 +2,26 @@ import UriTemplate from 'uri-templates';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
export interface NgitWebUrlOpts {
template: string;
nostrURI: NostrURI;
}
/**
* Generate a Nostr Git web URL from a template and Nostr URI
* @param template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @param opts - Options object
* @param opts.template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param opts.nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @returns The hydrated web URL
*/
export function ngitWebUrl(template: string, nostrURI: NostrURI): string {
const naddr = nostrURI.toNaddr();
const npub = nip19.npubEncode(nostrURI.pubkey);
export function ngitWebUrl(opts: NgitWebUrlOpts): string {
const naddr = opts.nostrURI.toNaddr();
const npub = nip19.npubEncode(opts.nostrURI.pubkey);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
naddr,
npub,
pubkey: nostrURI.pubkey,
identifier: nostrURI.identifier,
pubkey: opts.nostrURI.pubkey,
identifier: opts.nostrURI.identifier,
});
}
+1 -386
View File
@@ -1,14 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './plugins';
import { getPlugins } from './plugins';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
@@ -164,24 +156,6 @@ describe('plugins', () => {
fs = new MockFS();
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names with hyphens', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
expect(isValidSkillName('test-name')).toBe(true);
expect(isValidSkillName('test-123')).toBe(true);
expect(isValidSkillName('condition-based-waiting')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('Test-Name')).toBe(false);
});
});
describe('getPlugins', () => {
it('should return empty array when plugins directory does not exist', async () => {
const plugins = await getPlugins(fs, '/plugins');
@@ -199,363 +173,4 @@ describe('plugins', () => {
expect(plugins).not.toContain('file.txt');
});
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
});
});
-169
View File
@@ -1,38 +1,13 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
import * as git from 'isomorphic-git';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
export interface PluginGitInfo {
commitHash: string;
commitDate: Date;
commitMessage: string;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get all plugins from the plugins directory
*/
@@ -55,150 +30,6 @@ export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<
}
}
/**
* Get all skills from a single plugin
*/
function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a project's skills directory
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(projectPath, 'skills'), 'project');
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
/**
* Get git information for a plugin
*/
+8 -3
View File
@@ -1,8 +1,13 @@
import UriTemplate from 'uri-templates';
export function proxyUrl(template: string, url: string | URL): string {
const u = new URL(url);
return UriTemplate(template).fill({
export interface ProxyUrlOpts {
template: string;
url: string | URL;
}
export function proxyUrl(opts: ProxyUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(opts.template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+705
View File
@@ -0,0 +1,705 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './skills';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string | Uint8Array> = new Map();
private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (!content) throw new Error(`ENOENT: ${path}`);
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8') {
return typeof content === 'string' ? content : new TextDecoder().decode(content);
}
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
this.files.set(path, data);
// Auto-create parent directories
const parts = path.split('/');
for (let i = 1; i < parts.length; i++) {
this.dirs.add(parts.slice(0, i).join('/') || '/');
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]> {
if (!this.dirs.has(path)) throw new Error(`ENOENT: ${path}`);
const entries = new Set<string>();
const prefix = path === '/' ? '/' : path + '/';
// Check files
for (const filePath of this.files.keys()) {
if (filePath.startsWith(prefix)) {
const relativePath = filePath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
// Check directories
for (const dirPath of this.dirs) {
if (dirPath.startsWith(prefix) && dirPath !== path) {
const relativePath = dirPath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
const names = Array.from(entries);
if (options?.withFileTypes) {
return names.map(name => {
const fullPath = path === '/' ? `/${name}` : `${path}/${name}`;
const isDir = this.dirs.has(fullPath);
return {
name,
isDirectory: () => isDir,
isFile: () => !isDir,
};
});
}
return names;
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
if (options?.recursive) {
const parts = path.split('/');
for (let i = 1; i <= parts.length; i++) {
const dir = parts.slice(0, i).join('/') || '/';
this.dirs.add(dir);
}
} else {
this.dirs.add(path);
}
}
async stat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
const isDir = this.dirs.has(path);
const isFile = this.files.has(path);
if (!isDir && !isFile) throw new Error(`ENOENT: ${path}`);
return {
isDirectory: () => isDir,
isFile: () => isFile,
};
}
async rm(path: string, options?: { recursive?: boolean }): Promise<void> {
this.files.delete(path);
this.dirs.delete(path);
if (options?.recursive) {
const prefix = path + '/';
for (const filePath of Array.from(this.files.keys())) {
if (filePath.startsWith(prefix)) {
this.files.delete(filePath);
}
}
for (const dirPath of Array.from(this.dirs)) {
if (dirPath.startsWith(prefix)) {
this.dirs.delete(dirPath);
}
}
}
}
async rmdir(path: string, options?: { recursive?: boolean }): Promise<void> {
return this.rm(path, options);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
const content = this.files.get(oldPath);
if (content) {
this.files.set(newPath, content);
this.files.delete(oldPath);
}
}
async lstat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
return this.stat(path);
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in MockFS');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in MockFS');
}
}
describe('skills', () => {
let fs: MockFS;
beforeEach(() => {
fs = new MockFS();
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names with hyphens', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
expect(isValidSkillName('test-name')).toBe(true);
expect(isValidSkillName('test-123')).toBe(true);
expect(isValidSkillName('condition-based-waiting')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('Test-Name')).toBe(false);
});
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
it('should check .agents/skills first', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
it('should check .opencode/skills second', async () => {
const projectPath = '/projects/myproject';
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .opencode/skills
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('opencode-skill');
expect(skills[0].description).toBe('Skill from .opencode/skills');
});
it('should check .claude/skills third', async () => {
const projectPath = '/projects/myproject';
const claudeSkillPath = `${projectPath}/.claude/skills/claude-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .claude/skills
await fs.mkdir(claudeSkillPath, { recursive: true });
await fs.writeFile(
`${claudeSkillPath}/SKILL.md`,
`---
name: claude-skill
description: Skill from .claude/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('claude-skill');
expect(skills[0].description).toBe('Skill from .claude/skills');
});
it('should fall back to skills directory if no other directories exist', async () => {
const projectPath = '/projects/myproject';
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in skills directory only
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('regular-skill');
expect(skills[0].description).toBe('Skill from skills directory');
});
it('should prioritize .agents/skills over .opencode/skills', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in .opencode/skills (should be ignored)
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
});
+194
View File
@@ -0,0 +1,194 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a single plugin
*/
export function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get all skills from a project's skills directory
* Checks for skills in order: .agents/skills, .opencode/skills, .claude/skills, skills
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
const skillsPaths = [
join(projectPath, '.agents', 'skills'),
join(projectPath, '.opencode', 'skills'),
join(projectPath, '.claude', 'skills'),
join(projectPath, 'skills'),
];
// Try each path in order and return skills from the first one that exists
for (const skillsPath of skillsPaths) {
try {
const stat = await fs.stat(skillsPath);
if (stat.isDirectory()) {
return getSkillsFromDirectory(fs, skillsPath, 'project');
}
} catch {
// Directory doesn't exist, try next one
continue;
}
}
// No skills directory found
return [];
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const { getPlugins } = await import('./plugins');
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
+28 -26
View File
@@ -6,8 +6,8 @@ import { NostrMetadata } from '@nostrify/nostrify';
import { AppConfig } from '@/contexts/AppContext';
import OpenAI from 'openai';
// Mock the plugins module
vi.mock('./plugins', () => ({
// Mock the skills module
vi.mock('./skills', () => ({
getAllSkills: vi.fn(),
}));
@@ -16,7 +16,7 @@ vi.mock('path-browserify', () => ({
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
}));
import { getAllSkills } from './plugins';
import { getAllSkills } from './skills';
// Test configuration
const testConfig: AppConfig = {
@@ -196,14 +196,14 @@ describe('makeSystemPrompt', () => {
});
describe('tools section', () => {
it('should show no tools message when no tools are provided', async () => {
it('should pass tools to template context when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Available Tools');
expect(result).toContain('There are no tools available to you.');
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should list available tools with descriptions', async () => {
it('should pass tools to template context when tools are provided', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
@@ -225,49 +225,54 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('## Available Tools');
expect(result).toContain('**read_file**: Read contents of a file');
expect(result).toContain('**write_file**: Write contents to a file');
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should handle tools without descriptions', async () => {
it('should render tools with custom template', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'some_tool',
description: 'A test tool',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
const customTemplate = '## Available Tools\n{% for tool in tools %}**{{ tool.function.name }}**: {{ tool.function.description or "No description available" }}\n{% endfor %}';
expect(result).toContain('**some_tool**: No description available');
const result = await makeSystemPrompt({ ...baseOpts, tools, template: customTemplate });
expect(result).toContain('## Available Tools');
expect(result).toContain('**some_tool**: A test tool');
});
});
describe('skills section', () => {
it('should show no skills message when pluginsPath is not provided', async () => {
it('should not call getAllSkills when pluginsPath is not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, fsPathPlugins: '' },
});
expect(result).toContain('## Skills');
expect(result).toContain('No skills are currently configured');
// Skills are not fetched when pluginsPath is empty
expect(result).toBeTruthy();
expect(getAllSkills).not.toHaveBeenCalled();
});
it('should show no skills message when getAllSkills returns empty array', async () => {
it('should fetch skills when pluginsPath is provided but return empty array', async () => {
vi.mocked(getAllSkills).mockResolvedValue([]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
});
it('should list available skills when they exist', async () => {
it('should pass skills to template context when they exist', async () => {
vi.mocked(getAllSkills).mockResolvedValue([
{
name: 'create_component',
@@ -285,11 +290,8 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Skills');
expect(result).toContain('**create_component**: Create a new React component');
expect(result).toContain('Plugin: react-plugin');
expect(result).toContain('**setup_routing**: Setup React Router');
expect(result).toContain('Skills MUST be used whenever applicable');
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should handle getAllSkills errors gracefully', async () => {
@@ -297,7 +299,8 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
// Should continue with empty skills array
expect(result).toBeTruthy();
});
});
@@ -429,7 +432,6 @@ describe('makeSystemPrompt', () => {
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Project Templates');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
});
+48 -23
View File
@@ -5,7 +5,7 @@ import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import nunjucks from "nunjucks";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./plugins";
import { getAllSkills } from "./skills";
import type { AppConfig } from "@/contexts/AppContext";
export interface ModelInfo {
@@ -181,13 +181,6 @@ When a project is first created, you (the AI) choose an appropriate template fro
- URL: {{ template.url }}
{% endfor %}
## Available Tools
{% if tools.length > 0 %}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
There are no tools available to you.{% endif %}
## Image Generation
Shakespeare supports AI-powered image generation. Users can configure an image model in **Settings > AI** under the "Advanced" section.
@@ -200,21 +193,6 @@ Shakespeare supports AI-powered image generation. Users can configure an image m
- When generating images for projects, prefer "jpeg" or "webp" output formats with compression set between 70-90. You must supply these parameters when calling the generate_image tool to ensure optimal image quality and file size for web usage.
- **Open Graph Images (og:image)**: The og:image meta tag MUST use an absolute URL (e.g., \`https://example.com/og-image.jpg\`). Relative paths will not work for social media sharing. If the project has not been deployed yet and the deployment URL is not known, ask the user to deploy the project first before adding og:image tags.
## Skills
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
Available skills:
{% for skill in skills %}
- **{{ skill.name }}**: {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: {{ skill.path }}
{% endfor %}
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI (\`{{ location.origin }}/settings/ai\`) by adding plugins that contain skills.
## Working Around CORS Issues
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
@@ -223,6 +201,53 @@ If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching exter
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.
## Deployment Options
**CRITICAL**: Do NOT assume any deployment options are available or configured. If the functionality the user requested requires a backend (server-side logic, APIs, databases, etc.), you MUST explain this to the user before proceeding.
### Backend Requirements Process
When backend functionality is needed:
1. **Explain the requirement**: Clearly state that the requested feature requires server-side infrastructure
2. **Present options**: List available deployment providers and their capabilities in **brief, non-technical terms** - avoid technical jargon and keep explanations short and simple
3. **Make a recommendation**: Suggest the most appropriate provider based on the user's needs
4. **Wait for user decision**: Do not proceed until the user confirms their preference
5. **Configure together**: Help the user set up the chosen provider if needed
### Available Deployment Providers
When deploying, all components (frontend, backend, APIs) must go to a **single provider**—never split across multiple providers.
#### Cloudflare Workers
- **wrangler.jsonc** (optional): Configuration file in project root
- **worker.ts** (optional): Custom worker script in project root
- Supports \`.ts\`, \`.mjs\`, and \`.js\` extensions (defaults to \`worker.ts\`)
- Worker scripts are automatically bundled with their dependencies before deployment
- Static assets are handled automatically by Cloudflare's asset handler
- Add this only if you need server-side logic (APIs, edge functions, middleware, etc.)
#### Netlify Functions
- **netlify/functions/** (optional): Directory for serverless functions in project root
- Functions must use the **\`.mjs\` extension** for ES modules
- \`.js\` and \`.ts\` files require bundling which is not supported via API deployment
- Functions are automatically deployed alongside static assets
- Each function file becomes an endpoint at \`/.netlify/functions/<function-name>\`
#### Railway
- **railway.json** (optional): Configuration file in project root
- Supports Node.js, Python, Go, and other runtimes
### General Guidelines
- Most functionality can be achieved with static hosting + Nostr/client-side storage
- Only suggest backend platforms when the user explicitly requests server-side features or when static hosting is truly insufficient
- **Never assume the user has any deployment provider configured**—always ask first and offer to help with setup
- Do not create backend configuration files (wrangler.jsonc, railway.json, netlify/functions/, etc.) until the user has explicitly chosen and confirmed a deployment provider
## "Vibed with Shakespeare"
When building a site for the first time, include "Vibed with Shakespeare" somewhere in the UI, linked to this URL: https://shakespeare.diy
+609
View File
@@ -0,0 +1,609 @@
// The approaches in this edit tool are sourced from OpenCode which credits:
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-23-25.ts
// https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/editCorrector.ts
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-26-25.ts
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface EditParams {
filePath: string;
oldString: string;
newString: string;
replaceAll?: boolean;
}
interface EditToolOptions {
projectsPath?: string;
tmpPath?: string;
onFileChanged?: (filePath: string) => void;
singleCandidateSimilarityThreshold?: number;
multipleCandidatesSimilarityThreshold?: number;
}
export class EditTool implements Tool<EditParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
private singleCandidateSimilarityThreshold: number;
private multipleCandidatesSimilarityThreshold: number;
readonly description = `Performs exact string replacements in files.
Usage:
- You must use your \`read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- The edit will FAIL if \`oldString\` is not found in the file with an error "oldString not found in content".
- The edit will FAIL if \`oldString\` is found multiple times in the file with an error "oldString found multiple times and requires more code context to uniquely identify the intended match". Either provide a larger string with more surrounding context to make it unique or use \`replaceAll\` to change every instance of \`oldString\`.
- Use \`replaceAll\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
readonly inputSchema = z.object({
filePath: z.string().describe("The absolute path to the file to modify"),
oldString: z.string().describe("The text to replace"),
newString: z.string().describe("The text to replace it with (must be different from oldString)"),
replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: EditToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
this.singleCandidateSimilarityThreshold = options?.singleCandidateSimilarityThreshold ?? 0.0;
this.multipleCandidatesSimilarityThreshold = options?.multipleCandidatesSimilarityThreshold ?? 0.3;
}
async execute(args: EditParams): Promise<ToolResult> {
if (!args.filePath) {
throw new Error("filePath is required");
}
if (args.oldString === args.newString) {
throw new Error("oldString and newString must be different");
}
let filepath = args.filePath;
// Convert to absolute path if needed
if (!isAbsolutePath(filepath)) {
filepath = join(this.cwd, filepath);
}
// Check write permissions
if (!isWriteAllowed(filepath, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(filepath, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
if (
filepath === "package.json" ||
filepath.endsWith("/package.json") ||
filepath.endsWith("\\package.json")
) {
const depKeys = [
'"dependencies"',
'"devDependencies"',
'"peerDependencies"',
'"optionalDependencies"',
];
if (
depKeys.some((key) =>
args.oldString.includes(key) || args.newString.includes(key)
)
) {
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
}
}
try {
// Handle empty oldString as a special case (write new file)
if (args.oldString === "") {
await this.fs.writeFile(filepath, args.newString, "utf8");
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `File successfully created at ${filepath}` };
}
// Check if file exists
const stats = await this.fs.stat(filepath).catch(() => null);
if (!stats) {
throw new Error(`File ${filepath} not found`);
}
if (stats.isDirectory()) {
throw new Error(`Path is a directory, not a file: ${filepath}`);
}
// Read file content
const contentOld = await this.fs.readFile(filepath, "utf8");
// Perform replacement using fuzzy matching strategies
const contentNew = this.replace(contentOld, args.oldString, args.newString, args.replaceAll);
// Write updated content
await this.fs.writeFile(filepath, contentNew, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `Edit applied successfully.` };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Main replace function that tries multiple fuzzy matching strategies
*/
private replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different");
}
let notFound = true;
for (const replacer of [
this.SimpleReplacer,
this.LineTrimmedReplacer,
this.BlockAnchorReplacer,
this.WhitespaceNormalizedReplacer,
this.IndentationFlexibleReplacer,
this.EscapeNormalizedReplacer,
this.TrimmedBoundaryReplacer,
this.ContextAwareReplacer,
this.MultiOccurrenceReplacer,
]) {
for (const search of replacer.call(this, content, oldString)) {
const index = content.indexOf(search);
if (index === -1) continue;
notFound = false;
if (replaceAll) {
return content.replaceAll(search, newString);
}
const lastIndex = content.lastIndexOf(search);
if (index !== lastIndex) continue;
return content.substring(0, index) + newString + content.substring(index + search.length);
}
}
if (notFound) {
throw new Error("oldString not found in content");
}
throw new Error(
"oldString found multiple times and requires more code context to uniquely identify the intended match",
);
}
private *SimpleReplacer(_content: string, find: string): Generator<string, void, unknown> {
yield find;
}
private *LineTrimmedReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
let matches = true;
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim();
const searchTrimmed = searchLines[j].trim();
if (originalTrimmed !== searchTrimmed) {
matches = false;
break;
}
}
if (matches) {
let matchStartIndex = 0;
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length;
if (k < searchLines.length - 1) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
}
private *BlockAnchorReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines.length < 3) {
return;
}
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
const firstLineSearch = searchLines[0].trim();
const lastLineSearch = searchLines[searchLines.length - 1].trim();
const searchBlockSize = searchLines.length;
// Collect all candidate positions where both anchors match
const candidates: Array<{ startLine: number; endLine: number }> = [];
for (let i = 0; i < originalLines.length; i++) {
if (originalLines[i].trim() !== firstLineSearch) {
continue;
}
// Look for the matching last line after this first line
for (let j = i + 2; j < originalLines.length; j++) {
if (originalLines[j].trim() === lastLineSearch) {
candidates.push({ startLine: i, endLine: j });
break; // Only match the first occurrence of the last line
}
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return;
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const { startLine, endLine } = candidates[0];
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += (1 - distance / maxLen) / linesToCheck;
// Exit early when threshold is reached
if (similarity >= this.singleCandidateSimilarityThreshold) {
break;
}
}
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity >= this.singleCandidateSimilarityThreshold) {
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
return;
}
// Calculate similarity for multiple candidates
let bestMatch: { startLine: number; endLine: number } | null = null;
let maxSimilarity = -1;
for (const candidate of candidates) {
const { startLine, endLine } = candidate;
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += 1 - distance / maxLen;
}
similarity /= linesToCheck; // Average similarity
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestMatch = candidate;
}
}
// Threshold judgment
if (maxSimilarity >= this.multipleCandidatesSimilarityThreshold && bestMatch) {
const { startLine, endLine } = bestMatch;
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1;
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
private *WhitespaceNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim();
const normalizedFind = normalizeWhitespace(find);
// Handle single line matches
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (normalizeWhitespace(line) === normalizedFind) {
yield line;
} else {
// Only check for substring matches if the full line doesn't match
const normalizedLine = normalizeWhitespace(line);
if (normalizedLine.includes(normalizedFind)) {
// Find the actual substring in the original line that matches
const words = find.trim().split(/\s+/);
if (words.length > 0) {
const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
try {
const regex = new RegExp(pattern);
const match = line.match(regex);
if (match) {
yield match[0];
}
} catch {
// Invalid regex pattern, skip
}
}
}
}
}
// Handle multi-line matches
const findLines = find.split("\n");
if (findLines.length > 1) {
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length);
if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
yield block.join("\n");
}
}
}
}
private *IndentationFlexibleReplacer(content: string, find: string): Generator<string, void, unknown> {
const removeIndentation = (text: string) => {
const lines = text.split("\n");
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
if (nonEmptyLines.length === 0) return text;
const minIndent = Math.min(
...nonEmptyLines.map((line) => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}),
);
return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n");
};
const normalizedFind = removeIndentation(find);
const contentLines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= contentLines.length - findLines.length; i++) {
const block = contentLines.slice(i, i + findLines.length).join("\n");
if (removeIndentation(block) === normalizedFind) {
yield block;
}
}
}
private *EscapeNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const unescapeString = (str: string): string => {
return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (match, capturedChar) => {
switch (capturedChar) {
case "n":
return "\n";
case "t":
return "\t";
case "r":
return "\r";
case "'":
return "'";
case '"':
return '"';
case "`":
return "`";
case "\\":
return "\\";
case "\n":
return "\n";
case "$":
return "$";
default:
return match;
}
});
};
const unescapedFind = unescapeString(find);
// Try direct match with unescaped find string
if (content.includes(unescapedFind)) {
yield unescapedFind;
}
// Also try finding escaped versions in content that match unescaped find
const lines = content.split("\n");
const findLines = unescapedFind.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
const unescapedBlock = unescapeString(block);
if (unescapedBlock === unescapedFind) {
yield block;
}
}
}
private *MultiOccurrenceReplacer(content: string, find: string): Generator<string, void, unknown> {
// This replacer yields all exact matches, allowing the replace function
// to handle multiple occurrences based on replaceAll parameter
let startIndex = 0;
while (true) {
const index = content.indexOf(find, startIndex);
if (index === -1) break;
yield find;
startIndex = index + find.length;
}
}
private *TrimmedBoundaryReplacer(content: string, find: string): Generator<string, void, unknown> {
const trimmedFind = find.trim();
if (trimmedFind === find) {
// Already trimmed, no point in trying
return;
}
// Try to find the trimmed version
if (content.includes(trimmedFind)) {
yield trimmedFind;
}
// Also try finding blocks where trimmed content matches
const lines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
if (block.trim() === trimmedFind) {
yield block;
}
}
}
private *ContextAwareReplacer(content: string, find: string): Generator<string, void, unknown> {
const findLines = find.split("\n");
if (findLines.length < 3) {
// Need at least 3 lines to have meaningful context
return;
}
// Remove trailing empty line if present
if (findLines[findLines.length - 1] === "") {
findLines.pop();
}
const contentLines = content.split("\n");
// Extract first and last lines as context anchors
const firstLine = findLines[0].trim();
const lastLine = findLines[findLines.length - 1].trim();
// Find blocks that start and end with the context anchors
for (let i = 0; i < contentLines.length; i++) {
if (contentLines[i].trim() !== firstLine) continue;
// Look for the matching last line
for (let j = i + 2; j < contentLines.length; j++) {
if (contentLines[j].trim() === lastLine) {
// Found a potential context block
const blockLines = contentLines.slice(i, j + 1);
const block = blockLines.join("\n");
// Check if the middle content has reasonable similarity
// (simple heuristic: at least 50% of non-empty lines should match when trimmed)
if (blockLines.length === findLines.length) {
let matchingLines = 0;
let totalNonEmptyLines = 0;
for (let k = 1; k < blockLines.length - 1; k++) {
const blockLine = blockLines[k].trim();
const findLine = findLines[k].trim();
if (blockLine.length > 0 || findLine.length > 0) {
totalNonEmptyLines++;
if (blockLine === findLine) {
matchingLines++;
}
}
}
if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
yield block;
break; // Only match the first occurrence
}
}
break;
}
}
}
}
}
/**
* Levenshtein distance algorithm implementation
*/
function levenshtein(a: string, b: string): number {
// Handle empty strings
if (a === "" || b === "") {
return Math.max(a.length, b.length);
}
const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
);
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
}
}
return matrix[a.length][b.length];
}
+1 -1
View File
@@ -137,7 +137,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
}
} else if (firstImage.url) {
// Fetch the image from the URL
const imageUrl = this.corsProxy ? proxyUrl(this.corsProxy, firstImage.url) : firstImage.url;
const imageUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: firstImage.url }) : firstImage.url;
const imageResponse = await fetch(imageUrl);
if (!imageResponse.ok) {
+219
View File
@@ -0,0 +1,219 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GlobParams {
pattern: string;
path?: string;
}
interface GlobToolOptions {
resultLimit?: number;
}
export class GlobTool implements Tool<GlobParams> {
private fs: JSRuntimeFS;
private cwd: string;
private resultLimit: number;
readonly description = `- Fast file pattern matching tool that works with any codebase size
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`;
readonly inputSchema = z.object({
pattern: z.string().describe("The glob pattern to match files against"),
path: z
.string()
.optional()
.describe(
`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.`,
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GlobToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GlobParams): Promise<ToolResult> {
try {
// Determine the search path and pattern
// If args.path is provided, use it as the base directory
// Otherwise, extract any leading directory path from the pattern itself
let searchPath: string;
let pattern: string;
if (args.path) {
// User explicitly specified a path parameter
// If path is absolute, use it directly; otherwise join with cwd
searchPath = args.path.startsWith('/') ? args.path : join(this.cwd, args.path);
pattern = args.pattern;
} else {
// Parse the pattern to extract base directory
const parsed = this.parsePatternPath(args.pattern);
searchPath = parsed.basePath ? join(this.cwd, parsed.basePath) : this.cwd;
pattern = parsed.globPattern;
}
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Perform the search
const files = await this.searchFiles(searchPath, pattern);
// Sort by modification time (most recent first)
files.sort((a, b) => b.mtime - a.mtime);
// Truncate results if needed
const truncated = files.length > this.resultLimit;
const finalFiles = truncated ? files.slice(0, this.resultLimit) : files;
// Format output
const output: string[] = [];
if (finalFiles.length === 0) {
output.push("No files found");
} else {
output.push(...finalFiles.map((f) => f.path));
if (truncated) {
output.push("");
output.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
}
return { content: output.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
private parsePatternPath(pattern: string): { basePath: string; globPattern: string } {
const segments = pattern.split('/');
// Find the first segment that contains glob characters
const firstGlobIndex = segments.findIndex(seg =>
seg.includes('*') || seg.includes('?') || seg.includes('[')
);
if (firstGlobIndex === -1) {
// No glob characters found - treat entire pattern as base path
return { basePath: pattern, globPattern: '**/*' };
}
if (firstGlobIndex === 0) {
// Pattern starts with glob - no base path
return { basePath: '', globPattern: pattern };
}
// Split into base path and glob pattern
const basePath = segments.slice(0, firstGlobIndex).join('/');
const globPattern = segments.slice(firstGlobIndex).join('/');
return { basePath, globPattern };
}
private async searchFiles(
dirPath: string,
pattern: string
): Promise<Array<{ path: string; mtime: number }>> {
const results: Array<{ path: string; mtime: number }> = [];
// Parse the glob pattern into segments
const segments = pattern.split('/');
await this.searchRecursive(dirPath, dirPath, segments, 0, results);
return results;
}
private async searchRecursive(
basePath: string,
currentPath: string,
segments: string[],
segmentIndex: number,
results: Array<{ path: string; mtime: number }>
): Promise<void> {
// If we've matched all segments, we're done
if (segmentIndex >= segments.length) {
return;
}
const segment = segments[segmentIndex];
try {
const entries = await this.fs.readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(currentPath, entry.name);
// Handle ** (recursive wildcard)
if (segment === '**') {
// ** can match zero or more directories
if (entry.isDirectory()) {
// Continue matching with ** at current level
await this.searchRecursive(basePath, entryPath, segments, segmentIndex, results);
}
// Try matching the next segment
if (segmentIndex + 1 < segments.length) {
if (this.matchesPattern(entry.name, segments[segmentIndex + 1])) {
if (segmentIndex + 2 === segments.length) {
// This is the final match
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// Continue matching subsequent segments
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 2, results);
}
}
}
}
} else if (this.matchesPattern(entry.name, segment)) {
// Regular segment match
if (segmentIndex === segments.length - 1) {
// This is the final segment - add matching files
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// More segments to match - continue into directories
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 1, results);
}
}
}
}
} catch {
// Skip directories we can't read
return;
}
}
private matchesPattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*\*/g, '\u00A7\u00A7\u00A7')
.replace(/\*/g, '[^/]*')
.replace(/\u00A7\u00A7\u00A7/g, '.*')
.replace(/\?/g, '[^/]');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
+244
View File
@@ -0,0 +1,244 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GrepParams {
pattern: string;
path?: string;
include?: string;
}
interface GrepToolOptions {
maxLineLength?: number;
resultLimit?: number;
}
export class GrepTool implements Tool<GrepParams> {
private fs: JSRuntimeFS;
private cwd: string;
private maxLineLength: number;
private resultLimit: number;
readonly description = `- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths and line numbers with at least one match sorted by modification time
- Use this tool when you need to find files containing specific patterns
- If you need to identify/count the number of matches within files, use the shell tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead`;
readonly inputSchema = z.object({
pattern: z.string().describe("The regex pattern to search for in file contents"),
path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."),
include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GrepToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.maxLineLength = options?.maxLineLength || 2000;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GrepParams): Promise<ToolResult> {
if (!args.pattern) {
throw new Error("pattern is required");
}
// If path is absolute, use it directly; otherwise join with cwd
const searchPath = args.path
? (args.path.startsWith('/') ? args.path : join(this.cwd, args.path))
: this.cwd;
try {
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Create regex from pattern
let regex: RegExp;
try {
regex = new RegExp(args.pattern, 'g');
} catch {
throw new Error(`Invalid regex pattern: ${args.pattern}`);
}
// Perform the search
const matches = await this.searchFiles(searchPath, regex, args.include);
// Sort by modification time (most recent first)
matches.sort((a, b) => b.modTime - a.modTime);
// Truncate results if needed
const truncated = matches.length > this.resultLimit;
const finalMatches = truncated ? matches.slice(0, this.resultLimit) : matches;
if (finalMatches.length === 0) {
return { content: "No files found" };
}
// Format output
const outputLines = [`Found ${finalMatches.length} matches`];
let currentFile = "";
for (const match of finalMatches) {
if (currentFile !== match.path) {
if (currentFile !== "") {
outputLines.push("");
}
currentFile = match.path;
outputLines.push(`${match.path}:`);
}
const truncatedLineText =
match.lineText.length > this.maxLineLength
? match.lineText.substring(0, this.maxLineLength) + "..."
: match.lineText;
outputLines.push(` Line ${match.lineNum}: ${truncatedLineText}`);
}
if (truncated) {
outputLines.push("");
outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
return { content: outputLines.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Search for files containing the pattern
*/
private async searchFiles(
dirPath: string,
regex: RegExp,
includePattern?: string
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
const results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
await this.searchRecursive(dirPath, regex, includePattern, results);
return results;
}
/**
* Recursively search directories for pattern matches
*/
private async searchRecursive(
dirPath: string,
regex: RegExp,
includePattern: string | undefined,
results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
// Skip common directories that should be ignored
if (entry.name === 'node_modules' || entry.name === '.git') {
continue;
}
// Recursively search subdirectory
await this.searchRecursive(entryPath, regex, includePattern, results);
} else if (entry.isFile()) {
// Check if file matches include pattern
if (includePattern && !this.matchesIncludePattern(entry.name, includePattern)) {
continue;
}
// Search file content
const fileMatches = await this.searchFileContent(entryPath, regex);
results.push(...fileMatches);
}
}
} catch {
// Skip directories we can't read
return;
}
}
/**
* Search a single file for pattern matches
*/
private async searchFileContent(
filePath: string,
regex: RegExp
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
try {
// Get file modification time
const stats = await this.fs.stat(filePath);
const modTime = stats.mtimeMs || 0;
// Read file content
const content = await this.fs.readFile(filePath, 'utf8');
const lines = content.split('\n');
const matches: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Reset regex lastIndex for global regex
regex.lastIndex = 0;
if (regex.test(line)) {
matches.push({
path: filePath,
lineNum: i + 1,
lineText: line,
modTime,
});
}
}
return matches;
} catch {
// Skip files we can't read (likely binary)
return [];
}
}
/**
* Check if a filename matches the include pattern
*/
private matchesIncludePattern(filename: string, includePattern: string): boolean {
// Handle brace expansion like "*.{ts,tsx}"
if (includePattern.includes('{') && includePattern.includes('}')) {
const braceStart = includePattern.indexOf('{');
const braceEnd = includePattern.indexOf('}');
const prefix = includePattern.substring(0, braceStart);
const suffix = includePattern.substring(braceEnd + 1);
const options = includePattern.substring(braceStart + 1, braceEnd).split(',');
return options.some(option => {
const fullPattern = prefix + option + suffix;
return this.matchesSimplePattern(filename, fullPattern);
});
}
return this.matchesSimplePattern(filename, includePattern);
}
/**
* Check if a filename matches a simple glob pattern
*/
private matchesSimplePattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*/g, '.*') // * matches anything
.replace(/\?/g, '.'); // ? matches single character
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
+359
View File
@@ -0,0 +1,359 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface ReadParams {
filePath: string;
offset?: number;
limit?: number;
}
interface ReadToolOptions {
projectsPath?: string;
defaultReadLimit?: number;
maxLineLength?: number;
}
export class ReadTool implements Tool<ReadParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private defaultReadLimit: number;
private maxLineLength: number;
readonly description = `Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
Usage:
- The filePath parameter must be an absolute path, not a relative path
- By default, it reads up to 2000 lines starting from the beginning of the file
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
- Any lines longer than 2000 characters will be truncated
- Results are returned using cat -n format, with line numbers starting at 1
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.
- You can read image files using this tool.`;
readonly inputSchema = z.object({
filePath: z.string().describe("The path to the file to read"),
offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(),
limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: ReadToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.defaultReadLimit = options?.defaultReadLimit || 2000;
this.maxLineLength = options?.maxLineLength || 2000;
}
async execute(args: ReadParams): Promise<ToolResult> {
let filepath = args.filePath;
// Handle both absolute and relative paths
if (!filepath.startsWith('/') && !filepath.startsWith('\\') && !/^[A-Za-z]:[\\/]/.test(filepath)) {
filepath = join(this.cwd, filepath);
}
try {
const file = await this.fs.stat(filepath);
// Handle directory viewing
if (file.isDirectory()) {
// Special handling for projects directory - only show project directories, not their contents
const normalizedPath = filepath.replace(/\/$/, ''); // Remove trailing slash
if (normalizedPath === this.projectsPath) {
const tree = await this.generateDirectoryTree(filepath, "", 1); // Only show immediate children
return { content: tree };
}
// Check if we're starting from a .git directory
const isGitRoot = filepath.endsWith('/.git') || filepath === '.git';
// If it's a directory, generate a tree-like listing
const tree = await this.generateDirectoryTree(filepath, "", 3, 0, isGitRoot);
return { content: tree };
}
// Check if it's an image file
const isImage = this.isImageFile(filepath);
if (isImage) {
// Read image as base64
const bytes = await this.fs.readFile(filepath);
const base64 = this.arrayBufferToBase64(bytes);
const ext = this.getFileExtension(filepath).toLowerCase();
const mimeType = this.getMimeType(ext);
// Return base64 data URL in the content
return {
content: `[Image file: ${ext.toUpperCase()} file]\n\nImage read successfully.\n\nData URL: data:${mimeType};base64,${base64}`,
};
}
// Check if it's binary
if (await this.isBinaryFile(filepath)) {
const stats = await this.fs.stat(filepath);
const fileSize = this.formatFileSize(stats.size || 0);
const fileExtension = this.getFileExtension(filepath);
return {
content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`
};
}
// Read text file
const content = await this.fs.readFile(filepath, "utf8");
const limit = args.limit ?? this.defaultReadLimit;
const offset = args.offset || 0;
const lines = content.split("\n");
// Apply line filtering
const raw: string[] = [];
for (let i = offset; i < Math.min(lines.length, offset + limit); i++) {
const line = lines[i].length > this.maxLineLength
? lines[i].substring(0, this.maxLineLength) + "..."
: lines[i];
raw.push(line);
}
// Format with line numbers (cat -n format, 1-indexed)
const formatted = raw.map((line, index) => {
return `${(index + offset + 1).toString().padStart(5, " ")}| ${line}`;
});
let output = "<file>\n";
output += formatted.join("\n");
const totalLines = lines.length;
const lastReadLine = offset + raw.length;
const hasMoreLines = totalLines > lastReadLine;
if (hasMoreLines) {
output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${lastReadLine})`;
} else {
output += `\n\n(End of file - total ${totalLines} lines)`;
}
output += "\n</file>";
return { content: output };
} catch {
// File not found - try to suggest similar files
try {
const dir = filepath.split('/').slice(0, -1).join('/') || '/';
const base = filepath.split('/').pop() || '';
const dirEntries = await this.fs.readdir(dir);
const suggestions = dirEntries
.filter(entry =>
entry.toLowerCase().includes(base.toLowerCase()) ||
base.toLowerCase().includes(entry.toLowerCase())
)
.map(entry => join(dir, entry))
.slice(0, 3);
if (suggestions.length > 0) {
throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`);
}
} catch {
// Ignore suggestion errors
}
throw new Error(`File not found: ${filepath}`);
}
}
/**
* Generate a tree-like directory listing
*/
private async generateDirectoryTree(
dirPath: string,
prefix: string = "",
maxDepth: number = 3,
currentDepth: number = 0,
isGitRoot: boolean = false,
): Promise<string> {
if (currentDepth >= maxDepth) {
return prefix + "...\n";
}
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
// Sort entries: directories first, then files, both alphabetically
entries.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
let result = "";
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!
const isLastEntry = i === entries.length - 1;
const connector = isLastEntry ? "└── " : "├── ";
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
if (entry.isDirectory()) {
result += prefix + connector + entry.name + "/\n";
// Special handling for .git directories - don't traverse unless we started from .git
if (entry.name === '.git' && !isGitRoot) {
result += nextPrefix + "...\n";
} else {
const subPath = join(dirPath, entry.name);
result += await this.generateDirectoryTree(
subPath,
nextPrefix,
maxDepth,
currentDepth + 1,
isGitRoot,
);
}
} else {
result += prefix + connector + entry.name + "\n";
}
}
return result;
} catch (error) {
return prefix + `[Error reading directory: ${error}]\n`;
}
}
/**
* Check if a file is an image based on extension
*/
private isImageFile(filePath: string): boolean {
const extension = this.getFileExtension(filePath).toLowerCase();
const imageExtensions = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'ico', 'avif']);
return imageExtensions.has(extension);
}
/**
* Get MIME type for image extensions
*/
private getMimeType(extension: string): string {
const mimeTypes: Record<string, string> = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'bmp': 'image/bmp',
'webp': 'image/webp',
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'avif': 'image/avif',
};
return mimeTypes[extension] || 'application/octet-stream';
}
/**
* Convert ArrayBuffer to base64
*/
private arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
/**
* Check if a file is likely to be binary based on file extension and content sampling
*/
private async isBinaryFile(filePath: string): Promise<boolean> {
// Check file extension first for known binary types
const extension = this.getFileExtension(filePath).toLowerCase();
const binaryExtensions = new Set([
// Images (already handled separately)
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'ico', 'avif',
// Videos
'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v',
// Audio
'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus',
// Archives
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst',
// Executables
'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi',
// Documents (binary formats)
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp',
// Fonts
'ttf', 'otf', 'woff', 'woff2', 'eot',
// Other binary formats
'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear', 'wasm',
]);
if (binaryExtensions.has(extension)) {
return true;
}
try {
// For files without clear binary extensions, sample the first chunk of content
const bytes = await this.fs.readFile(filePath);
// Check first 1024 bytes (or entire file if smaller)
const sampleSize = Math.min(1024, bytes.length);
// Count null bytes and non-printable characters
let nullBytes = 0;
let nonPrintableBytes = 0;
for (let i = 0; i < sampleSize; i++) {
const byte = bytes[i];
if (byte === 0) {
nullBytes++;
}
// Consider bytes outside printable ASCII range (except common whitespace)
// Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13)
if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) {
nonPrintableBytes++;
}
}
// If more than 1% null bytes or more than 30% non-printable, consider it binary
const nullRatio = nullBytes / sampleSize;
const nonPrintableRatio = nonPrintableBytes / sampleSize;
return nullRatio > 0.01 || nonPrintableRatio > 0.3;
} catch {
// If we can't read the file, assume it might be binary
return true;
}
}
/**
* Get file extension from path
*/
private getFileExtension(filePath: string): string {
const lastDotIndex = filePath.lastIndexOf('.');
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
// If there's no dot, or the dot is before the last slash (hidden file), return empty string
if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) {
return '';
}
return filePath.slice(lastDotIndex + 1);
}
/**
* Format file size in human-readable format
*/
private formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`;
}
}
-236
View File
@@ -1,236 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { JSDOM } from "jsdom";
import { ReadWebpageTool } from "./ReadWebpageTool";
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("ReadWebpageTool", () => {
let tool: ReadWebpageTool;
let domParser: DOMParser;
beforeEach(() => {
// Create a JSDOM instance for testing
const jsdom = new JSDOM();
domParser = new jsdom.window.DOMParser();
tool = new ReadWebpageTool(domParser);
mockFetch.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("inputSchema", () => {
it("should validate valid URL", () => {
const result = tool.inputSchema.safeParse({
url: "https://example.com",
});
expect(result.success).toBe(true);
});
it("should reject invalid URL", () => {
const result = tool.inputSchema.safeParse({
url: "not-a-url",
});
expect(result.success).toBe(false);
});
});
describe("execute", () => {
it("should extract and convert article content to markdown", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Test Article</title>
</head>
<body>
<article>
<h1>Main Article Title</h1>
<p>This is the main content of the article.</p>
<p>It has multiple paragraphs with <strong>bold text</strong> and <em>italic text</em>.</p>
<h2>Subsection</h2>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</article>
<div class="sidebar">
<p>This is sidebar content that should be ignored.</p>
</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html; charset=utf-8"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article",
});
expect(result.content).toContain("# Test Article");
expect(result.content).toContain("**Source:** https://example.com/article");
expect(result.content).toContain("Main Article Title");
expect(result.content).toContain("**bold text**");
expect(result.content).toContain("*italic text*");
expect(result.content).toContain("## Subsection");
expect(result.content).toContain("* First item");
expect(result.content).toContain("* Second item");
});
it("should handle articles with metadata", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Article with Metadata</title>
<meta name="author" content="John Doe">
<meta name="description" content="This is a test article description">
</head>
<body>
<article>
<header>
<h1>Article with Metadata</h1>
<p class="byline">By John Doe</p>
<time datetime="2023-01-01">January 1, 2023</time>
</header>
<p>Main article content goes here.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article-with-metadata",
});
expect(result.content).toContain("# Article with Metadata");
expect(result.content).toContain("**Source:** https://example.com/article-with-metadata");
});
it("should handle code blocks properly", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<article>
<h1>Code Example</h1>
<p>Here's some code:</p>
<pre><code class="language-javascript">
function hello() {
console.log("Hello, world!");
}
</code></pre>
<p>And some inline <code>code</code> too.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/code-example",
});
expect(result.content).toContain("```");
expect(result.content).toContain("function hello()");
expect(result.content).toContain("`code`");
});
it("should handle HTTP errors", async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: "Not Found",
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://example.com/not-found",
})).rejects.toThrow("HTTP 404: Not Found");
});
it("should handle non-HTML content", async () => {
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("application/json"),
},
text: vi.fn().mockResolvedValue('{"data": "json"}'),
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://api.example.com/data.json",
})).rejects.toThrow("Expected HTML content, but received: application/json");
});
it("should handle network errors", async () => {
mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
await expect(tool.execute({
url: "https://example.com",
})).rejects.toThrow("Network error: Unable to fetch https://example.com");
});
it("should handle pages with minimal content", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<div class="navigation">Nav content</div>
<div class="footer">Footer content</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/minimal-content",
});
expect(result.content).toContain("# Untitled");
expect(result.content).toContain("**Source:** https://example.com/minimal-content");
});
it("should handle invalid URLs", async () => {
await expect(tool.execute({
url: "invalid-url",
})).rejects.toThrow("Failed to read webpage invalid-url");
});
});
});
-123
View File
@@ -1,123 +0,0 @@
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
interface ReadWebpageParams {
url: string;
}
export class ReadWebpageTool implements Tool<ReadWebpageParams> {
private domParser: DOMParser;
private turndownService: TurndownService;
readonly description = "Read and extract the main content from a webpage, converting it to markdown";
readonly inputSchema = z.object({
url: z.string().url().describe(
"The URL of the webpage to read and extract content from"
),
});
constructor(domParser: DOMParser) {
this.domParser = domParser;
this.turndownService = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
fence: "```",
emDelimiter: "*",
strongDelimiter: "**",
linkStyle: "inlined",
linkReferenceStyle: "full",
});
// Configure turndown to preserve code blocks and improve formatting
this.turndownService.addRule("preserveCodeBlocks", {
filter: ["pre"],
replacement: (content, node) => {
const codeElement = node.querySelector("code");
if (codeElement) {
const language = codeElement.className.match(/language-(\w+)/)?.[1] || "";
return `\n\n\`\`\`${language}\n${content}\n\`\`\`\n\n`;
}
return `\n\n\`\`\`\n${content}\n\`\`\`\n\n`;
},
});
// Improve table handling
this.turndownService.addRule("tables", {
filter: "table",
replacement: (content) => {
return `\n\n${content}\n\n`;
},
});
}
async execute(args: ReadWebpageParams): Promise<ToolResult> {
const { url } = args;
try {
// Validate URL format
new URL(url);
// Fetch the webpage
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("text/html")) {
throw new Error(`Expected HTML content, but received: ${contentType}`);
}
const html = await response.text();
// Parse the HTML
const doc = this.domParser.parseFromString(html, "text/html");
// Use Readability to extract the main content
const reader = new Readability(doc, {
debug: false,
maxElemsToParse: 0, // No limit
nbTopCandidates: 5,
charThreshold: 500,
classesToPreserve: ["highlight", "code", "pre"],
});
const article = reader.parse();
if (!article) {
throw new Error("Could not extract readable content from the webpage");
}
// Convert the extracted HTML content to markdown
const markdown = this.turndownService.turndown(article.content || "");
// Create a formatted result with metadata
const result = [
`# ${article.title || "Untitled"}`,
"",
article.excerpt ? `${article.excerpt}` : "",
article.excerpt ? "" : "",
`**Source:** ${url}`,
article.byline ? `**Author:** ${article.byline}` : "",
article.publishedTime ? `**Published:** ${article.publishedTime}` : "",
"",
"---",
"",
markdown,
].filter(Boolean).join("\n");
return { content: result };
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
throw new Error(`Network error: Unable to fetch ${url}. ${error.message}`);
}
throw new Error(`Failed to read webpage ${url}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
+39 -19
View File
@@ -1,7 +1,7 @@
import { z } from 'zod';
import type { Tool, ToolResult } from './Tool';
import type { JSRuntimeFS } from '../JSRuntime';
import { findSkill, readSkillContent } from '../plugins';
import { readSkillContent, type Skill } from '../skills';
interface SkillParams {
name: string;
@@ -9,45 +9,65 @@ interface SkillParams {
export class SkillTool implements Tool<SkillParams> {
private fs: JSRuntimeFS;
private pluginsPath: string;
private projectPath: string;
readonly description = 'Load and execute a skill from the configured plugins or project. Skills are reusable AI workflows that can be invoked by name.';
private availableSkills: Skill[];
readonly description: string;
readonly inputSchema = z.object({
name: z.string().describe('The name of the skill to execute (lowercase alphanumeric with hyphens)'),
name: z.string().describe('The skill identifier from available_skills'),
});
constructor(fs: JSRuntimeFS, pluginsPath: string, projectPath: string) {
/**
* Create a SkillTool instance.
* @param fs - Filesystem instance
* @param availableSkills - List of available skills (should be pre-loaded)
*/
constructor(fs: JSRuntimeFS, availableSkills: Skill[]) {
this.fs = fs;
this.pluginsPath = pluginsPath;
this.projectPath = projectPath;
this.availableSkills = availableSkills;
this.description = this.generateDescription(availableSkills);
}
/**
* Generate description text for SkillTool based on available skills.
*/
private generateDescription(skills: Skill[]): string {
if (skills.length === 0) {
return 'Load a skill to get detailed instructions for a specific task. No skills are currently available.';
}
return [
'Load a skill to get detailed instructions for a specific task.',
'Skills provide specialized knowledge and step-by-step guidance.',
'Use this when a task matches an available skill\'s description.',
'<available_skills>',
...skills.map(skill =>
` <skill>\n <name>${skill.name}</name>\n <description>${skill.description}</description>\n </skill>`
),
'</available_skills>',
].join('\n');
}
async execute(args: SkillParams): Promise<ToolResult> {
const { name } = args;
try {
// Find the skill across all plugins and project
const skill = await findSkill(this.fs, this.pluginsPath, this.projectPath, name);
// Find the skill in the pre-loaded list
const skill = this.availableSkills.find(s => s.name === name);
if (!skill) {
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
const available = this.availableSkills.map(s => s.name).join(', ');
throw new Error(`Skill "${name}" not found. Available skills: ${available || 'none'}`);
}
// Read and return the skill content
const content = await readSkillContent(this.fs, skill);
return {
content: `# Skill: ${skill.name}
content: `## Skill: ${skill.name}
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
**Description**: ${skill.description}
**Path**: ${skill.path}
**Base directory**: ${skill.path}
---
${content}`
${content.trim()}`
};
} catch (error) {
if (error instanceof Error) {
@@ -1,168 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorStrReplaceTool } from './TextEditorStrReplaceTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Simple mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
this.dirs.add('/project');
this.dirs.add('/project/src');
this.files.set('/project/src/test.ts', 'const message = "hello world";\nconsole.log(message);');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
if (this.dirs.has(path)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(path)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(path)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
// Helper method to get file content
getFileContent(path: string): string | undefined {
return this.files.get(path);
}
}
describe('TextEditorStrReplaceTool', () => {
let mockFS: MockFS;
let tool: TextEditorStrReplaceTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorStrReplaceTool(mockFS, '/project');
});
it('should replace string in file successfully', async () => {
const result = await tool.execute({
path: 'src/test.ts',
old_str: 'hello world',
new_str: 'hello universe'
});
expect(result.content).toContain('String successfully replaced in src/test.ts');
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('hello universe');
expect(mockFS.getFileContent('/project/src/test.ts')).not.toContain('hello world');
});
it('should handle string not found', async () => {
await expect(tool.execute({
path: 'src/test.ts',
old_str: 'nonexistent string',
new_str: 'replacement'
})).rejects.toThrow('The string to replace was not found in src/test.ts');
});
it('should reject absolute paths with helpful error message', async () => {
await expect(tool.execute({
path: '/absolute/path/test.ts',
old_str: 'old',
new_str: 'new'
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
// First create the file in /tmp/
await mockFS.writeFile('/tmp/temp-file.txt', 'original content');
const result = await tool.execute({
path: '/tmp/temp-file.txt',
old_str: 'original',
new_str: 'modified'
});
expect(result.content).toContain('String successfully replaced');
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content');
});
it('should handle whitespace normalization', async () => {
const result = await tool.execute({
path: 'src/test.ts',
old_str: 'const message = "hello world";',
new_str: 'const greeting = "hello universe";',
normalize_whitespace: true
});
expect(result.content).toContain('String successfully replaced');
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";');
});
});
-192
View File
@@ -1,192 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface TextEditorStrReplaceParams {
path: string;
old_str: string;
new_str: string;
normalize_whitespace?: boolean;
}
export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
readonly description = "Replace a string in a file with a new string";
readonly inputSchema = z.object({
path: z.string().describe('Path to the file, eg "src/index.ts"'),
old_str: z.string().describe("The string to replace"),
new_str: z.string().describe("The new string to insert"),
normalize_whitespace: z.boolean().optional().describe(
"If true, normalize whitespace and line endings for more flexible matching (default: true)"
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorStrReplaceParams): Promise<ToolResult> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
if (
path === "package.json" || path.endsWith("/package.json") ||
path.endsWith("\\package.json")
) {
const depKeys = [
'"dependencies"',
'"devDependencies"',
'"peerDependencies"',
'"optionalDependencies"',
];
if (
depKeys.some((key) =>
old_str.includes(key) || new_str.includes(key)
)
) {
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
}
}
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
const content = await this.fs.readFile(absolutePath, "utf8");
// Helper function to normalize whitespace
const normalizeWhitespace = (str: string): string => {
return str
.replace(/\r\n/g, '\n') // Convert CRLF to LF
.replace(/\r/g, '\n') // Convert CR to LF
.split('\n')
.map(line => line.trimEnd()) // Remove trailing whitespace from each line
.join('\n');
};
let searchContent = content;
let searchOldStr = old_str;
let searchNewStr = new_str;
if (normalize_whitespace) {
searchContent = normalizeWhitespace(content);
searchOldStr = normalizeWhitespace(old_str);
searchNewStr = normalizeWhitespace(new_str);
}
if (!searchContent.includes(searchOldStr)) {
// Try to provide helpful debugging information
const lines = searchContent.split('\n');
const oldLines = searchOldStr.split('\n');
// Find potential matches by looking for the first line of old_str
const firstLine = oldLines[0];
const matchingLineNumbers: number[] = [];
if (firstLine) {
lines.forEach((line, index) => {
if (line.includes(firstLine)) {
matchingLineNumbers.push(index + 1);
}
});
}
let errorMessage = `Error: The string to replace was not found in ${path}`;
if (matchingLineNumbers.length > 0) {
errorMessage += `\n\nPossible matches found at lines: ${matchingLineNumbers.join(', ')}`;
// Show context around the first potential match
const firstMatch = matchingLineNumbers[0]! - 1;
const contextStart = Math.max(0, firstMatch - 2);
const contextEnd = Math.min(lines.length, firstMatch + oldLines.length + 2);
const contextLines = lines.slice(contextStart, contextEnd);
errorMessage += `\n\nContext around line ${matchingLineNumbers[0]}:`;
contextLines.forEach((line, index) => {
const lineNum = contextStart + index + 1;
const marker = lineNum === matchingLineNumbers[0] ? '→ ' : ' ';
errorMessage += `\n${marker}${lineNum}: ${line}`;
});
}
if (normalize_whitespace) {
errorMessage += `\n\nNote: Whitespace normalization was applied. Try setting normalize_whitespace to false if the replacement still fails.`;
}
throw new Error(errorMessage);
}
// Count occurrences (simple string counting)
let occurrences = 0;
let pos = 0;
while ((pos = searchContent.indexOf(searchOldStr, pos)) !== -1) {
occurrences++;
pos += searchOldStr.length;
}
// Perform the replacement
let newContent: string;
if (normalize_whitespace) {
// Apply the replacement to the normalized content, then restore original line endings
const normalizedResult = searchContent.replace(searchOldStr, searchNewStr);
// Try to preserve the original line ending style
const hasCarriageReturn = content.includes('\r');
if (hasCarriageReturn) {
if (content.includes('\r\n')) {
// Original had CRLF
newContent = normalizedResult.replace(/\n/g, '\r\n');
} else {
// Original had CR only
newContent = normalizedResult.replace(/\n/g, '\r');
}
} else {
// Original had LF only
newContent = normalizedResult;
}
} else {
newContent = content.replace(old_str, new_str);
}
await this.fs.writeFile(absolutePath, newContent, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(path);
}
let successMessage = `String successfully replaced in ${path}`;
if (occurrences > 1) {
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
}
return { content: successMessage };
} catch (error) {
throw new Error(String(error));
}
}
}
-335
View File
@@ -1,335 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorViewTool } from './TextEditorViewTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
// Set up a basic project structure
this.dirs.add('/projects');
this.dirs.add('/projects/project1');
this.dirs.add('/projects/project1/src');
this.dirs.add('/projects/project1/.git');
this.dirs.add('/projects/project2');
this.dirs.add('/projects/project2/src');
this.dirs.add('/project');
this.dirs.add('/project/.git');
this.dirs.add('/project/src');
this.dirs.add('/project/node_modules');
this.dirs.add('/tmp');
this.files.set('/projects/project1/package.json', '{"name": "project1"}');
this.files.set('/projects/project1/src/index.ts', 'console.log("project1");');
this.files.set('/projects/project1/.git/config', '[core]\nrepositoryformatversion = 0');
this.files.set('/projects/project1/.git/HEAD', 'ref: refs/heads/main');
this.files.set('/projects/project2/package.json', '{"name": "project2"}');
this.files.set('/projects/project2/src/main.ts', 'console.log("project2");');
this.files.set('/project/package.json', '{"name": "test"}');
this.files.set('/project/src/index.ts', 'console.log("hello");');
this.files.set('/project/.gitignore', 'node_modules\n.git\n');
this.files.set('/project/.git/config', '[core]\nrepositoryformatversion = 0');
this.files.set('/project/.git/HEAD', 'ref: refs/heads/main');
this.files.set('/tmp/uploaded-file.txt', 'This is an uploaded file');
// Add binary files for testing
this.files.set('/project/logo.png', 'BINARY_CONTENT_PNG');
this.files.set('/project/document.pdf', 'BINARY_CONTENT_PDF');
this.files.set('/tmp/image.jpg', 'BINARY_CONTENT_JPG');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
// If no encoding specified, return Uint8Array
if (!encoding) {
// For binary files, return mock binary data with null bytes
if (content.startsWith('BINARY_CONTENT')) {
const binaryData = new Uint8Array(100);
binaryData[0] = 0; // Add null byte to make it appear binary
binaryData[1] = 255; // Add some non-printable bytes
binaryData[2] = 0;
// Fill rest with some pattern
for (let i = 3; i < 100; i++) {
binaryData[i] = i % 256;
}
return binaryData;
}
return new TextEncoder().encode(content);
}
return content;
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
// Normalize path by removing trailing slash
const normalizedPath = path.replace(/\/$/, '') || '/';
const entries: string[] = [];
// Find all files and directories that are direct children of this path
for (const filePath of this.files.keys()) {
if (filePath.startsWith(normalizedPath + '/')) {
const relativePath = filePath.slice(normalizedPath.length + 1);
const parts = relativePath.split('/');
if (parts.length === 1) {
entries.push(parts[0]);
}
}
}
for (const dirPath of this.dirs) {
if (dirPath.startsWith(normalizedPath + '/')) {
const relativePath = dirPath.slice(normalizedPath.length + 1);
const parts = relativePath.split('/');
if (parts.length === 1) {
entries.push(parts[0]);
}
}
}
if (options?.withFileTypes) {
return entries.map(name => ({
name,
isDirectory: () => this.dirs.has(`${normalizedPath}/${name}`),
isFile: () => this.files.has(`${normalizedPath}/${name}`)
}));
}
return entries;
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
// Normalize path by removing trailing slash for directories
const normalizedPath = path.replace(/\/$/, '') || '/';
if (this.dirs.has(normalizedPath)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(normalizedPath)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(normalizedPath)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
}
describe('TextEditorViewTool', () => {
let mockFS: MockFS;
let tool: TextEditorViewTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorViewTool(mockFS, '/project');
});
it('should handle viewing current directory', async () => {
const result = await tool.execute({ path: '.' });
expect(result.content).toContain('src/');
expect(result.content).toContain('package.json');
expect(result.content).toContain('.gitignore');
expect(result.content).toContain('.git/'); // .git directory should now be visible
});
it('should handle viewing subdirectory', async () => {
const result = await tool.execute({ path: 'src' });
expect(result.content).toContain('index.ts');
});
it('should handle viewing a file', async () => {
const result = await tool.execute({ path: 'src/index.ts' });
expect(result.content).toBe('console.log("hello");');
});
it('should handle line filtering', async () => {
const result = await tool.execute({
path: 'src/index.ts',
start_line: 1,
end_line: 1
});
expect(result.content).toBe('console.log("hello");');
});
it('should handle absolute paths', async () => {
const result = await tool.execute({ path: '/tmp/uploaded-file.txt' });
expect(result.content).toBe('This is an uploaded file');
});
it('should handle absolute directory paths', async () => {
const result = await tool.execute({ path: '/tmp' });
expect(result.content).toContain('uploaded-file.txt');
});
it('should handle absolute paths with line filtering', async () => {
const result = await tool.execute({
path: '/tmp/uploaded-file.txt',
start_line: 1,
end_line: 1
});
expect(result.content).toBe('This is an uploaded file');
});
it('should detect binary files by extension and show placeholder', async () => {
const result = await tool.execute({ path: 'logo.png' });
expect(result.content).toContain('[Binary file: PNG file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
expect(result.content).not.toContain('BINARY_CONTENT_PNG');
});
it('should detect PDF files as binary', async () => {
const result = await tool.execute({ path: 'document.pdf' });
expect(result.content).toContain('[Binary file: PDF file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
});
it('should detect binary files with absolute paths', async () => {
const result = await tool.execute({ path: '/tmp/image.jpg' });
expect(result.content).toContain('[Binary file: JPG file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
});
it('should show only project directories when viewing /projects', async () => {
const result = await tool.execute({ path: '/projects' });
// Should show the project directories
expect(result.content).toContain('project1/');
expect(result.content).toContain('project2/');
// Should NOT show the contents of the project directories (depth 1 only)
expect(result.content).not.toContain('package.json');
expect(result.content).not.toContain('src/');
expect(result.content).not.toContain('index.ts');
expect(result.content).not.toContain('main.ts');
});
it('should show only project directories when viewing /projects/', async () => {
const result = await tool.execute({ path: '/projects/' });
// Should show the project directories
expect(result.content).toContain('project1/');
expect(result.content).toContain('project2/');
// Should NOT show the contents of the project directories (depth 1 only)
expect(result.content).not.toContain('package.json');
expect(result.content).not.toContain('src/');
expect(result.content).not.toContain('index.ts');
expect(result.content).not.toContain('main.ts');
});
it('should show .git directory but not traverse its contents when viewing project root', async () => {
const result = await tool.execute({ path: '/project' });
// Should show the .git directory
expect(result.content).toContain('.git/');
// Should show "..." under .git instead of its contents
expect(result.content).toContain('...');
// Should NOT show .git file contents
expect(result.content).not.toContain('config');
expect(result.content).not.toContain('HEAD');
expect(result.content).not.toContain('repositoryformatversion');
// Should still show other directory contents normally
expect(result.content).toContain('src/');
expect(result.content).toContain('package.json');
});
it('should show .git contents when explicitly viewing .git directory', async () => {
const result = await tool.execute({ path: '/project/.git' });
// Should show the .git file contents when explicitly requested
expect(result.content).toContain('config');
expect(result.content).toContain('HEAD');
// Should NOT show "..." when explicitly viewing .git
expect(result.content).not.toContain('...');
});
it('should show .git contents when explicitly viewing .git with relative path', async () => {
const result = await tool.execute({ path: '.git' });
// Should show the .git file contents when explicitly requested
expect(result.content).toContain('config');
expect(result.content).toContain('HEAD');
// Should NOT show "..." when explicitly viewing .git
expect(result.content).not.toContain('...');
});
});
-276
View File
@@ -1,276 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface TextEditorViewParams {
path: string;
start_line?: number;
end_line?: number;
}
export class TextEditorViewTool implements Tool<TextEditorViewParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
readonly description = "View the contents of a text file or directory";
readonly inputSchema = z.object({
path: z.string().describe(
'Path of the file or directory to view, eg "src/index.ts" or "src/" for relative paths, or "/tmp/file.txt" for absolute paths',
),
start_line: z.number().min(1).optional().describe(
"Starting line number (1-indexed, inclusive). If provided, only show lines from this line onwards.",
),
end_line: z.number().min(1).optional().describe(
"Ending line number (1-indexed, inclusive). If provided, only show lines up to this line.",
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(args: TextEditorViewParams): Promise<ToolResult> {
const { path, start_line, end_line } = args;
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
// It's an absolute path - use it directly
absolutePath = path;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(this.cwd, path);
}
// Check if the path is a directory
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
// Special handling for projects directory - only show project directories, not their contents
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
if (normalizedPath === this.projectsPath) {
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
return { content: tree };
}
// Check if we're starting from a .git directory
const isGitRoot = absolutePath.endsWith('/.git') || absolutePath === '.git';
// If it's a directory, generate a tree-like listing
// Note: start_line and end_line are ignored for directories
const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot);
return { content: tree };
}
// If it's a file, check if it's binary first
if (await this.isBinaryFile(absolutePath)) {
const stats = await this.fs.stat(absolutePath);
const fileSize = this.formatFileSize(stats.size || 0);
const fileExtension = this.getFileExtension(absolutePath);
return {
content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`
};
}
// If it's a text file, read and return its contents
let content = await this.fs.readFile(absolutePath, "utf8");
// Apply line filtering if start_line or end_line are provided
if (start_line !== undefined || end_line !== undefined) {
const lines = content.split('\n');
// Validate line numbers first
if (start_line !== undefined && start_line < 1) {
throw new Error("Error: start_line must be >= 1");
}
if (end_line !== undefined && end_line < 1) {
throw new Error("Error: end_line must be >= 1");
}
if (start_line !== undefined && end_line !== undefined && start_line > end_line) {
throw new Error("Error: start_line cannot be greater than end_line");
}
if (start_line !== undefined && start_line > lines.length) {
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;
const endIdx = end_line !== undefined ? Math.min(lines.length, end_line) : lines.length;
content = lines.slice(startIdx, endIdx).join('\n');
}
return { content };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Generate a tree-like directory listing
*/
private async generateDirectoryTree(
dirPath: string,
prefix: string = "",
maxDepth: number = 3,
currentDepth: number = 0,
isGitRoot: boolean = false,
): Promise<string> {
if (currentDepth >= maxDepth) {
return prefix + "...\n";
}
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
// Sort entries: directories first, then files, both alphabetically
entries.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
let result = "";
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!
const isLastEntry = i === entries.length - 1;
const connector = isLastEntry ? "└── " : "├── ";
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
if (entry.isDirectory()) {
result += prefix + connector + entry.name + "/\n";
// Special handling for .git directories - don't traverse unless we started from .git
if (entry.name === '.git' && !isGitRoot) {
result += nextPrefix + "...\n";
} else {
const subPath = join(dirPath, entry.name);
result += await this.generateDirectoryTree(
subPath,
nextPrefix,
maxDepth,
currentDepth + 1,
isGitRoot,
);
}
} else {
result += prefix + connector + entry.name + "\n";
}
}
return result;
} catch (error) {
return prefix + `[Error reading directory: ${error}]\n`;
}
}
/**
* Check if a file is likely to be binary based on file extension and content sampling
*/
private async isBinaryFile(filePath: string): Promise<boolean> {
// Check file extension first for known binary types
const extension = this.getFileExtension(filePath).toLowerCase();
const binaryExtensions = new Set([
// Images
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'svg', 'ico', 'avif',
// Videos
'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v',
// Audio
'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus',
// Archives
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst',
// Executables
'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi',
// Documents (binary formats)
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp',
// Fonts
'ttf', 'otf', 'woff', 'woff2', 'eot',
// Other binary formats
'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear',
// Development
'node_modules', 'git', 'gitignore', 'lock'
]);
if (binaryExtensions.has(extension)) {
return true;
}
try {
// For files without clear binary extensions, sample the first chunk of content
// Read as Uint8Array to check for null bytes and non-printable characters
const bytes = await this.fs.readFile(filePath);
// Check first 1024 bytes (or entire file if smaller)
const sampleSize = Math.min(1024, bytes.length);
// Count null bytes and non-printable characters
let nullBytes = 0;
let nonPrintableBytes = 0;
for (let i = 0; i < sampleSize; i++) {
const byte = bytes[i];
if (byte === 0) {
nullBytes++;
}
// Consider bytes outside printable ASCII range (except common whitespace)
// Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13)
if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) {
nonPrintableBytes++;
}
}
// If more than 1% null bytes or more than 30% non-printable, consider it binary
const nullRatio = nullBytes / sampleSize;
const nonPrintableRatio = nonPrintableBytes / sampleSize;
return nullRatio > 0.01 || nonPrintableRatio > 0.3;
} catch {
// If we can't read the file, assume it might be binary
return true;
}
}
/**
* Get file extension from path
*/
private getFileExtension(filePath: string): string {
const lastDotIndex = filePath.lastIndexOf('.');
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
// If there's no dot, or the dot is before the last slash (hidden file), return empty string
if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) {
return '';
}
return filePath.slice(lastDotIndex + 1);
}
/**
* Format file size in human-readable format
*/
private formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`;
}
};
-154
View File
@@ -1,154 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorWriteTool } from './TextEditorWriteTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Simple mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
this.dirs.add('/project');
this.dirs.add('/project/src');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
if (this.dirs.has(path)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(path)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(path)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
// Helper method to check if file exists
hasFile(path: string): boolean {
return this.files.has(path);
}
// Helper method to get file content
getFileContent(path: string): string | undefined {
return this.files.get(path);
}
}
describe('TextEditorWriteTool', () => {
let mockFS: MockFS;
let tool: TextEditorWriteTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorWriteTool(mockFS, '/project');
});
it('should write a file successfully', async () => {
const result = await tool.execute({
path: 'src/test.ts',
file_text: 'console.log("test");'
});
expect(result.content).toContain('File successfully written to src/test.ts');
expect(mockFS.hasFile('/project/src/test.ts')).toBe(true);
expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");');
});
it('should reject absolute paths outside allowed directories', async () => {
await expect(tool.execute({
path: '/absolute/path/test.ts',
file_text: 'test content'
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
const result = await tool.execute({
path: '/tmp/temp-file.txt',
file_text: 'temporary content'
});
expect(result.content).toContain('File successfully written to /tmp/temp-file.txt');
expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true);
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content');
});
it('should reject package.json writes', async () => {
await expect(tool.execute({
path: 'package.json',
file_text: '{"name": "test"}'
})).rejects.toThrow('🔒 Direct writes to package.json are disallowed');
});
});
-74
View File
@@ -1,74 +0,0 @@
import { join, dirname } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface TextEditorWriteParams {
path: string;
file_text: string;
}
export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
readonly description = "Create or overwrite a file with new content";
readonly inputSchema = z.object({
path: z.string().describe(
'Path of the file to write, eg "src/index.ts"',
),
file_text: z.string().describe("Content to write to the file"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorWriteParams): Promise<ToolResult> {
const { path, file_text } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
if (
path === "package.json" || path.endsWith("/package.json") ||
path.endsWith("\\package.json")
) {
throw new Error(`🔒 Direct writes to package.json are disallowed.\n👉 Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`);
}
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
await this.fs.mkdir(dirname(absolutePath), { recursive: true });
await this.fs.writeFile(absolutePath, file_text, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(path);
}
return { content: `File successfully written to ${path}` };
} catch (error) {
throw new Error(String(error));
}
}
}
+143
View File
@@ -0,0 +1,143 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TodoReadTool } from './TodoReadTool';
import { TodoWriteTool } from './TodoWriteTool';
import { MockFS } from '@/test/MockFS';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TodoReadTool', () => {
let fs: JSRuntimeFS;
let readTool: TodoReadTool;
let writeTool: TodoWriteTool;
const projectId = 'test-project';
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
readTool = new TodoReadTool(fs, projectId);
writeTool = new TodoWriteTool(fs, projectId);
});
it('should have a description', () => {
expect(readTool.description).toBeDefined();
expect(readTool.description.length).toBeGreaterThan(0);
});
it('should have an input schema', () => {
expect(readTool.inputSchema).toBeDefined();
});
it('should return empty message when no todos exist', async () => {
const result = await readTool.execute({});
// Should return empty JSON array
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should read todos from .git/ai/TODO file', async () => {
const todos = [
{
id: '1',
content: 'Test task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Test task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
];
// Write todos first
await writeTool.execute({ todos });
// Read them back
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(1);
expect(completed.length).toBe(1);
});
it('should count active and completed tasks correctly', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
{
id: '3',
content: 'Task 3',
status: 'in_progress' as const,
priority: 'low' as const,
},
{
id: '4',
content: 'Task 4',
status: 'cancelled' as const,
priority: 'low' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(2);
expect(completed.length).toBe(1);
});
it('should handle invalid JSON in TODO file', async () => {
// Write invalid JSON
await fs.mkdir(`/projects/${projectId}/.git/ai`, { recursive: true });
await fs.writeFile(`/projects/${projectId}/.git/ai/TODO`, 'invalid json');
const result = await readTool.execute({});
// Should return empty JSON array when file is invalid
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should display full todo information', async () => {
const todos = [
{
id: 'abc123',
content: 'Implement new feature',
status: 'in_progress' as const,
priority: 'high' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const parsed = JSON.parse(result.content);
expect(parsed[0].id).toBe('abc123');
expect(parsed[0].content).toBe('Implement new feature');
expect(parsed[0].status).toBe('in_progress');
expect(parsed[0].priority).toBe('high');
});
});
+46
View File
@@ -0,0 +1,46 @@
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import type { TodoInfo } from "./TodoWriteTool";
import { join } from "path-browserify";
type TodoReadParams = Record<string, never>;
export class TodoReadTool implements Tool<TodoReadParams> {
private fs: JSRuntimeFS;
private projectId: string;
private projectsPath: string;
readonly description = "Use this tool to read your todo list";
readonly inputSchema = z.object({});
constructor(fs: JSRuntimeFS, projectId: string, options?: { projectsPath?: string }) {
this.fs = fs;
this.projectId = projectId;
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(_args: TodoReadParams): Promise<ToolResult> {
try {
// Read todos from .git/ai/TODO file
const todoPath = join(this.projectsPath, this.projectId, ".git", "ai", "TODO");
let todos: TodoInfo[] = [];
try {
const content = await this.fs.readFile(todoPath, "utf8");
todos = JSON.parse(content);
} catch {
// File doesn't exist or is invalid - return empty array
todos = [];
}
return {
content: JSON.stringify(todos, null, 2),
};
} catch (error) {
throw new Error(`Failed to read todos: ${String(error)}`);
}
}
}
+137
View File
@@ -0,0 +1,137 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TodoWriteTool } from './TodoWriteTool';
import { MockFS } from '@/test/MockFS';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TodoWriteTool', () => {
let fs: JSRuntimeFS;
let tool: TodoWriteTool;
const projectId = 'test-project';
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
tool = new TodoWriteTool(fs, projectId);
});
it('should have a description', () => {
expect(tool.description).toBeDefined();
expect(tool.description.length).toBeGreaterThan(0);
});
it('should have an input schema', () => {
expect(tool.inputSchema).toBeDefined();
});
it('should write todos to .git/ai/TODO file', async () => {
const todos = [
{
id: '1',
content: 'Test task',
status: 'pending' as const,
priority: 'medium' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Check file was written
const content = await fs.readFile(`/projects/${projectId}/.git/ai/TODO`, 'utf8');
const savedTodos = JSON.parse(content);
expect(savedTodos).toEqual(todos);
});
it('should count active and completed tasks correctly', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
{
id: '3',
content: 'Task 3',
status: 'in_progress' as const,
priority: 'low' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(2);
expect(completed.length).toBe(1);
});
it('should handle cancelled tasks', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'cancelled' as const,
priority: 'low' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(0);
expect(completed.length).toBe(1);
});
it('should handle empty todo list', async () => {
const todos: Array<{ id: string; content: string; status: 'pending' | 'in_progress' | 'completed' | 'cancelled'; priority: 'high' | 'medium' | 'low' }> = [];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should create .git/ai directory if it does not exist', async () => {
const todos = [
{
id: '1',
content: 'Test task',
status: 'pending' as const,
priority: 'medium' as const,
},
];
await tool.execute({ todos });
// Verify directory was created
const stat = await fs.stat(`/projects/${projectId}/.git/ai`);
expect(stat.isDirectory()).toBe(true);
});
});
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more