mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f1b3e6b7e | ||
|
|
749d173cf4 | ||
|
|
a7b45b5068 | ||
|
|
d26d1051f1 | ||
|
|
d99a9e1c46 | ||
|
|
8be2ef7b22 | ||
|
|
75a0d637ce | ||
|
|
a84ba7385b | ||
|
|
2fdd9e6a49 | ||
|
|
67a77419df | ||
|
|
4676738a14 | ||
|
|
444dfbc5dd |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
image: node:25
|
||||
image: node:22
|
||||
|
||||
default:
|
||||
interruptible: true
|
||||
|
||||
@@ -41,8 +41,7 @@ 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
|
||||
- **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
|
||||
- **ReadWebpageTool**: Fetch and read web pages
|
||||
- **NostrReadNipTool**: Read Nostr protocol NIP documents
|
||||
- **NostrReadKindTool**: Read Nostr event kind documentation
|
||||
- **NostrReadTagTool**: Read Nostr tag documentation
|
||||
@@ -52,33 +51,6 @@ 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.
|
||||
@@ -260,7 +232,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: `WebFetchTool`, `WebSearchTool`
|
||||
- Web access: `ReadWebpageTool`
|
||||
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
|
||||
- `/src/contexts/`: React context providers
|
||||
- `AppContext`: Global app configuration and theme
|
||||
|
||||
+1
-1
@@ -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({ template: corsProxy, url: 'https://api.provider.com/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
{ ignores: ["dist", "electron/dist"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
|
||||
+1
-1
@@ -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' blob:; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
|
||||
Generated
+68
-386
@@ -20,7 +20,6 @@
|
||||
"@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",
|
||||
@@ -71,7 +70,7 @@
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^6.16.0",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
"qrcode": "^1.5.4",
|
||||
@@ -96,7 +95,7 @@
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^4.3.6"
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.9.0",
|
||||
@@ -106,7 +105,6 @@
|
||||
"@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",
|
||||
@@ -197,6 +195,7 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1832,6 +1831,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -1855,6 +1855,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -1876,6 +1877,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -3004,15 +3006,6 @@
|
||||
"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",
|
||||
@@ -3031,182 +3024,6 @@
|
||||
"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",
|
||||
@@ -4675,6 +4492,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4688,6 +4506,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4701,6 +4520,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4714,6 +4534,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4727,6 +4548,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4740,6 +4562,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4753,6 +4576,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4766,6 +4590,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4779,6 +4604,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4792,6 +4618,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4805,6 +4632,7 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4818,6 +4646,7 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4831,6 +4660,7 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4844,6 +4674,7 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4857,6 +4688,7 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4870,6 +4702,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4883,6 +4716,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4896,6 +4730,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4909,6 +4744,7 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4922,6 +4758,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5202,89 +5039,6 @@
|
||||
"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",
|
||||
@@ -5692,8 +5446,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/chrome": {
|
||||
"version": "0.0.74",
|
||||
@@ -5815,18 +5568,6 @@
|
||||
"@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",
|
||||
@@ -5917,6 +5658,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
|
||||
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5928,6 +5670,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -5939,13 +5682,6 @@
|
||||
"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",
|
||||
@@ -6018,6 +5754,7 @@
|
||||
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.31.1",
|
||||
"@typescript-eslint/types": "8.31.1",
|
||||
@@ -6377,6 +6114,7 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6586,20 +6324,6 @@
|
||||
"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",
|
||||
@@ -6905,6 +6629,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -7065,15 +6790,6 @@
|
||||
],
|
||||
"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",
|
||||
@@ -7143,6 +6859,7 @@
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
@@ -7902,8 +7619,7 @@
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dom-helpers": {
|
||||
"version": "5.2.1",
|
||||
@@ -7968,7 +7684,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -8254,6 +7971,7 @@
|
||||
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -8519,6 +8237,7 @@
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
|
||||
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.0",
|
||||
@@ -9492,9 +9211,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.11.4",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz",
|
||||
"integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==",
|
||||
"version": "4.11.1",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz",
|
||||
"integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
@@ -9616,6 +9335,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -10409,6 +10129,7 @@
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
@@ -10703,9 +10424,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.23",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
|
||||
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.castarray": {
|
||||
@@ -10793,7 +10514,6 @@
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
@@ -12229,16 +11949,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/openai": {
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/openai/-/openai-6.16.0.tgz",
|
||||
"integrity": "sha512-fZ1uBqjFUjXzbGc35fFtYKEOxd20kd9fDpFeqWtsOZWiubY8CZ1NAlXHW3iathaFvqmNtCWMIsosCuyeI7Joxg==",
|
||||
"version": "5.15.0",
|
||||
"resolved": "https://registry.npmjs.org/openai/-/openai-5.15.0.tgz",
|
||||
"integrity": "sha512-kcUdws8K/A8m02I+IqFBwO51gS+87GP89yWEufGbzEi8anBz4FB/bti2QxaJdGwwY4mwJGzx85XO7TuL/Tpu1w==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"openai": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ws": "^8.18.0",
|
||||
"zod": "^3.25 || ^4.0"
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ws": {
|
||||
@@ -12547,6 +12267,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.8",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -12714,7 +12435,6 @@
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
@@ -12730,7 +12450,6 @@
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
@@ -12741,7 +12460,6 @@
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -12754,8 +12472,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
@@ -12822,24 +12539,6 @@
|
||||
"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",
|
||||
@@ -12947,6 +12646,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -12973,6 +12673,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -12998,6 +12699,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -13046,6 +12748,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -13291,12 +12994,6 @@
|
||||
"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",
|
||||
@@ -13594,6 +13291,7 @@
|
||||
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.7"
|
||||
},
|
||||
@@ -14648,6 +14346,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -14851,6 +14550,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -15014,24 +14714,6 @@
|
||||
"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",
|
||||
@@ -15041,12 +14723,6 @@
|
||||
"@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",
|
||||
@@ -15170,6 +14846,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -15697,6 +15374,7 @@
|
||||
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -15841,6 +15519,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -16312,6 +15991,7 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -16388,6 +16068,7 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
@@ -16832,10 +16513,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
+2
-4
@@ -31,7 +31,6 @@
|
||||
"@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",
|
||||
@@ -82,7 +81,7 @@
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^6.16.0",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
"qrcode": "^1.5.4",
|
||||
@@ -107,7 +106,7 @@
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^4.3.6"
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.9.0",
|
||||
@@ -117,7 +116,6 @@
|
||||
"@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",
|
||||
|
||||
@@ -48,11 +48,6 @@ 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`);
|
||||
},
|
||||
|
||||
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -142,6 +143,7 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<NWCProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
@@ -161,6 +163,7 @@ export function App() {
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
|
||||
+10
-3
@@ -1,16 +1,18 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Explore from "./pages/Explore";
|
||||
import Settings from "./pages/Settings";
|
||||
import Preferences from "./pages/Preferences";
|
||||
import NostrSettings from "./pages/NostrSettings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DeploySettings from "./pages/DeploySettings";
|
||||
import WalletSettings from "./pages/WalletSettings";
|
||||
import SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
@@ -25,8 +27,11 @@ 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 (
|
||||
<BrowserRouter>
|
||||
<Router>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
@@ -34,6 +39,7 @@ export function AppRouter() {
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/explore" element={<Explore />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
@@ -45,6 +51,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="wallet" element={<WalletSettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
@@ -55,7 +62,7 @@ export function AppRouter() {
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
export default AppRouter;
|
||||
@@ -19,14 +19,12 @@ 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);
|
||||
@@ -73,7 +71,6 @@ export const AIMessageItem = memo(({
|
||||
toolArgs={toolArgs}
|
||||
state="completed"
|
||||
result={content}
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1041,31 +1041,12 @@ export function AIProviderConfigDialog({
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-auth">{t('authentication')}</Label>
|
||||
<Select
|
||||
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
|
||||
});
|
||||
}
|
||||
}}
|
||||
value={localProvider.nostr ? 'nostr' : 'api-key'}
|
||||
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
|
||||
...localProvider,
|
||||
nostr: value === 'nostr' || undefined,
|
||||
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
|
||||
})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
@@ -1073,25 +1054,10 @@ 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>
|
||||
@@ -1173,7 +1139,7 @@ export function AIProviderConfigDialog({
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} 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" />
|
||||
|
||||
@@ -50,8 +50,7 @@ export function AddCustomAIProviderDialog({
|
||||
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
|
||||
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
|
||||
const handleAdd = () => {
|
||||
@@ -67,11 +66,6 @@ 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) {
|
||||
@@ -87,7 +81,6 @@ export function AddCustomAIProviderDialog({
|
||||
setCustomBaseURL('');
|
||||
setCustomApiKey('');
|
||||
setCustomAuthMethod('api-key');
|
||||
setCustomOpenSecretUrl('');
|
||||
setCustomProxy(false);
|
||||
|
||||
onOpenChange(false);
|
||||
@@ -96,7 +89,6 @@ 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());
|
||||
@@ -164,7 +156,7 @@ export function AddCustomAIProviderDialog({
|
||||
<Label htmlFor="custom-auth">{t('authentication')}</Label>
|
||||
<Select
|
||||
value={customAuthMethod}
|
||||
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
|
||||
onValueChange={(value: 'api-key' | 'nostr') => {
|
||||
setCustomAuthMethod(value);
|
||||
if (value === 'nostr') {
|
||||
setCustomApiKey(''); // Clear API key when switching to Nostr auth
|
||||
@@ -177,26 +169,11 @@ 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 === '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') && (
|
||||
{customAuthMethod === 'api-key' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
|
||||
<PasswordInput
|
||||
|
||||
@@ -28,7 +28,6 @@ import type {
|
||||
NsiteProvider,
|
||||
CloudflareProvider,
|
||||
DenoDeployProvider,
|
||||
RailwayProvider,
|
||||
} from '@/contexts/DeploySettingsContext';
|
||||
|
||||
// Type for provider without the 'id' field (will be generated)
|
||||
@@ -38,8 +37,7 @@ type DeployProviderInput =
|
||||
| Omit<VercelProvider, 'id'>
|
||||
| Omit<NsiteProvider, 'id'>
|
||||
| Omit<CloudflareProvider, 'id'>
|
||||
| Omit<DenoDeployProvider, 'id'>
|
||||
| Omit<RailwayProvider, 'id'>;
|
||||
| Omit<DenoDeployProvider, 'id'>;
|
||||
|
||||
interface AddCustomProviderDialogProps {
|
||||
open: boolean;
|
||||
@@ -53,7 +51,7 @@ export function AddCustomProviderDialog({
|
||||
onAdd,
|
||||
}: AddCustomProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAccountId, setCustomAccountId] = useState('');
|
||||
@@ -131,15 +129,6 @@ 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
|
||||
}
|
||||
@@ -167,8 +156,7 @@ export function AddCustomProviderDialog({
|
||||
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
|
||||
(customApiKey.trim() &&
|
||||
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
|
||||
(customProviderType !== 'railway' || true)));
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim())));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -187,7 +175,7 @@ export function AddCustomProviderDialog({
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
@@ -212,7 +200,6 @@ 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>
|
||||
@@ -312,8 +299,7 @@ export function AddCustomProviderDialog({
|
||||
{customProviderType === 'netlify' ? 'Personal Access Token' :
|
||||
customProviderType === 'cloudflare' ? 'API Token' :
|
||||
customProviderType === 'deno' ? 'Access Token' :
|
||||
customProviderType === 'railway' ? 'API Token' :
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="custom-apikey"
|
||||
@@ -333,9 +319,7 @@ export function AddCustomProviderDialog({
|
||||
? 'https://api.vercel.com'
|
||||
: customProviderType === 'deno'
|
||||
? 'https://api.deno.com/v1'
|
||||
: customProviderType === 'railway'
|
||||
? 'https://backboard.railway.com'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
}
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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\.|enclave\.)/, '');
|
||||
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
|
||||
return faviconUrl(config.faviconUrl, parsedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -327,7 +327,6 @@ 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" />
|
||||
@@ -368,6 +367,13 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigateAndClose('/explore')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Compass className="h-4 w-4" />
|
||||
{t('exploreApps')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLabelsDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
|
||||
@@ -27,6 +27,7 @@ interface ProjectTitleMenuProps {
|
||||
onDuplicate: () => void;
|
||||
onDelete: () => void;
|
||||
onProjectDetails: () => void;
|
||||
isAILoading: boolean;
|
||||
isAnyLoading: boolean;
|
||||
className?: string;
|
||||
}
|
||||
@@ -39,6 +40,7 @@ export function ProjectTitleMenu({
|
||||
onDuplicate,
|
||||
onDelete,
|
||||
onProjectDetails,
|
||||
isAILoading,
|
||||
isAnyLoading,
|
||||
className = '',
|
||||
}: ProjectTitleMenuProps) {
|
||||
@@ -109,7 +111,7 @@ export function ProjectTitleMenu({
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isAnyLoading}
|
||||
disabled={isAILoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
|
||||
@@ -212,8 +212,6 @@ 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 });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -229,8 +227,7 @@ 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' :
|
||||
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
|
||||
'Base URL'
|
||||
'Base URL'
|
||||
}
|
||||
value={localProvider.baseURL || ''}
|
||||
onChange={(e) => {
|
||||
@@ -242,8 +239,6 @@ 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 });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useRef, useEffect, memo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
@@ -23,13 +30,26 @@ import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useOGImage } from '@/hooks/useOGImage';
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: Repository;
|
||||
/** Pre-fetched author metadata to avoid individual fetches */
|
||||
authorMetadata?: NostrMetadata;
|
||||
/** Callback when a tag is clicked - receives the tag value */
|
||||
onTagClick?: (tag: string) => void;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const { data: authorData } = useAuthor(repo.pubkey);
|
||||
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
|
||||
// Only fetch author data if not preloaded
|
||||
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
|
||||
const metadata = preloadedMetadata ?? authorData?.metadata;
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const navigate = useNavigate();
|
||||
@@ -39,10 +59,41 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isCloning, setIsCloning] = useState(false);
|
||||
const [editRepoOpen, setEditRepoOpen] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [eventViewerOpen, setEventViewerOpen] = useState(false);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = authorData?.metadata?.picture;
|
||||
// Lazy load OG images - only fetch when card is in viewport
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsInViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '100px' } // Start loading slightly before visible
|
||||
);
|
||||
|
||||
if (cardRef.current) {
|
||||
observer.observe(cardRef.current);
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const displayName = metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
const isOwnRepo = user?.pubkey === repo.pubkey;
|
||||
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
|
||||
const canZap = user && !isOwnRepo && hasLightning;
|
||||
|
||||
// Get OG metadata from first web URL - only when in viewport
|
||||
const firstWebUrl = repo.webUrls?.[0];
|
||||
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
|
||||
const ogImageUrl = ogMetadata?.image ?? null;
|
||||
const ogDescription = ogMetadata?.description ?? null;
|
||||
|
||||
// Construct Nostr clone URL
|
||||
const nostrURI = new NostrURI({
|
||||
@@ -109,52 +160,117 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
|
||||
};
|
||||
|
||||
// Check if we have a valid OG image to show
|
||||
const hasValidImage = ogImageUrl && !imageError;
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
{/* Preview Image or Placeholder */}
|
||||
{hasValidImage && firstWebUrl ? (
|
||||
<a
|
||||
href={firstWebUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<img
|
||||
src={ogImageUrl}
|
||||
alt={`${repo.name} preview`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
</a>
|
||||
) : (
|
||||
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
|
||||
<Code className="h-12 w-12 text-white" />
|
||||
</div>
|
||||
)}
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
{/* Header with name and menu */}
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<div className="flex items-end gap-2 mb-2">
|
||||
<h3 className="font-semibold text-lg leading-tight truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<span className="text-sm text-muted-foreground shrink-0">
|
||||
{formatRelativeTime(repo.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{isOwnRepo && (
|
||||
<div className="flex items-center -mt-1 -mr-2 shrink-0">
|
||||
{canZap && (
|
||||
<ZapDialog target={repo as unknown as Event}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
|
||||
<Zap className="h-4 w-4" />
|
||||
</Button>
|
||||
</ZapDialog>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
<DropdownMenuContent align="end">
|
||||
{firstWebUrl && (
|
||||
<DropdownMenuItem asChild className="gap-2">
|
||||
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Open Website
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
|
||||
<Code className="h-4 w-4" />
|
||||
View Event
|
||||
</DropdownMenuItem>
|
||||
{isOwnRepo && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Author */}
|
||||
<div className="mb-4">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="h-4 w-4">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<Avatar className="h-10 w-10">
|
||||
{profileImage && (
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
)}
|
||||
<AvatarFallback className="text-[8px]">
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{displayName}</span>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(displayName);
|
||||
}}
|
||||
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
|
||||
>
|
||||
{displayName}
|
||||
</button>
|
||||
{metadata?.nip05 && (
|
||||
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{repo.description && (
|
||||
{(repo.description || ogDescription) && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
|
||||
{repo.description}
|
||||
{repo.description || ogDescription}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -162,14 +278,21 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
{repo.repoTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-4">
|
||||
{repo.repoTags.slice(0, 3).map((tag, index) => (
|
||||
<Badge key={index} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
<button
|
||||
key={index}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(tag);
|
||||
}}
|
||||
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
|
||||
>
|
||||
#{tag}
|
||||
</button>
|
||||
))}
|
||||
{repo.repoTags.length > 3 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
+{repo.repoTags.length - 3}
|
||||
</Badge>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -212,6 +335,31 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
repoIdentifier={repo.repoId}
|
||||
onSuccess={handleRepoEditSuccess}
|
||||
/>
|
||||
|
||||
{/* Event Viewer Dialog */}
|
||||
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Repository Event</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto flex-1 min-h-0">
|
||||
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
|
||||
{JSON.stringify({
|
||||
id: repo.id,
|
||||
pubkey: repo.pubkey,
|
||||
created_at: repo.created_at,
|
||||
kind: repo.kind,
|
||||
tags: repo.tags,
|
||||
content: repo.content,
|
||||
sig: repo.sig,
|
||||
}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Memoize to prevent re-renders when parent re-renders with same props
|
||||
export const RepositoryCard = memo(RepositoryCardInner);
|
||||
@@ -1,20 +1,13 @@
|
||||
import { useState, useCallback, memo, useRef, useEffect } from 'react';
|
||||
import { useState, useCallback, memo } 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;
|
||||
@@ -36,7 +29,6 @@ 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({
|
||||
@@ -60,15 +52,10 @@ 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]);
|
||||
@@ -91,110 +78,16 @@ 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, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
|
||||
}, [handleSend]);
|
||||
|
||||
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
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]);
|
||||
setInput(e.target.value);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="border-t p-4">
|
||||
@@ -206,61 +99,35 @@ export const ChatInput = memo(function ChatInput({
|
||||
onDragEnter={onDragEnter}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={handleDrop}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<div className="relative">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: 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>
|
||||
: 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';
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
|
||||
@@ -15,15 +15,12 @@ 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 { 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 { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
@@ -42,11 +39,7 @@ 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';
|
||||
@@ -54,13 +47,11 @@ import OpenAI from 'openai';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
|
||||
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage } from '@/lib/SessionManager';
|
||||
import { getAllSkills } from '@/lib/skills';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -100,15 +91,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const queryClient = useQueryClient();
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const scrolledProjectsRef = useRef(new Set<string>());
|
||||
const shouldScrollToBottomRef = useRef(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
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
|
||||
@@ -179,45 +167,16 @@ 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),
|
||||
@@ -231,11 +190,7 @@ 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, availableSkills),
|
||||
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
|
||||
websearch: new WebSearchTool(),
|
||||
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
|
||||
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
|
||||
skill: new SkillTool(fs, pluginsPath, cwd),
|
||||
};
|
||||
|
||||
// Add generate_image tool if imageModel is configured
|
||||
@@ -287,21 +242,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
|
||||
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
|
||||
|
||||
// MCP tools wrapped for execution
|
||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||
|
||||
// Combined tool executors (for SessionManager to call)
|
||||
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]);
|
||||
const customTools = useMemo(() => ({
|
||||
...builtInTools,
|
||||
...mcpToolWrappers,
|
||||
}), [builtInTools, mcpToolWrappers]);
|
||||
|
||||
// Convert tools to OpenAI format for AI provider
|
||||
const tools = useMemo(() => {
|
||||
@@ -312,18 +262,11 @@ 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, projectTools, mcpOpenAITools]);
|
||||
}, [builtInTools, mcpOpenAITools]);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
@@ -546,46 +489,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||
// Check if user was already at or near the bottom (within 100px threshold)
|
||||
const threshold = 100;
|
||||
const container = scrollAreaRef.current;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||
|
||||
// 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
|
||||
// Only auto-scroll if user was already near the bottom
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [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 && !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);
|
||||
});
|
||||
});
|
||||
if (projectId && !scrolledProjects.has(projectId)) {
|
||||
// Small delay to ensure messages have loaded
|
||||
const timer = setTimeout(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjects.add(projectId);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
|
||||
}, [projectId, scrolledProjects, scrollToBottom]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragEnter = useCallback((e: React.DragEvent) => {
|
||||
@@ -650,9 +577,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// 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]);
|
||||
|
||||
@@ -675,23 +599,6 @@ 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: () => {
|
||||
@@ -711,7 +618,6 @@ 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 */}
|
||||
@@ -727,7 +633,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
})()}
|
||||
state="calling"
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
@@ -764,7 +669,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
})()}
|
||||
state="waiting"
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -896,7 +800,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -969,7 +872,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
slashCommands={slashCommands}
|
||||
/>
|
||||
|
||||
{/* Onboarding Dialog */}
|
||||
@@ -977,13 +879,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
open={showOnboarding}
|
||||
onOpenChange={setShowOnboarding}
|
||||
/>
|
||||
|
||||
{/* Tools Dialog */}
|
||||
<ToolsDialog
|
||||
open={showToolsDialog}
|
||||
onOpenChange={setShowToolsDialog}
|
||||
tools={tools}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -10,14 +10,17 @@ 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, RefreshCw } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } 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 { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||
import type { ImperativePanelHandle } from 'react-resizable-panels';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -74,18 +77,14 @@ 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();
|
||||
@@ -178,7 +177,19 @@ 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) {
|
||||
@@ -429,7 +440,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
setBuildError(null);
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
@@ -454,13 +464,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
console.log('Build completed for project, refreshing preview');
|
||||
// Check for built project and refresh iframe
|
||||
checkForBuiltProject();
|
||||
refreshIframe();
|
||||
refreshIframeLegacy();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
}, [projectId, checkForBuiltProject, refreshIframe]);
|
||||
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
|
||||
|
||||
const handleFileSelect = (filePath: string) => {
|
||||
setSelectedFile(filePath);
|
||||
@@ -490,48 +500,106 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}
|
||||
};
|
||||
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
const [copiedAll, setCopiedAll] = useState(false);
|
||||
const [copiedBuildError, setCopiedBuildError] = useState(false);
|
||||
const ConsoleDropdown = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const messages = isLogsOpen ? getConsoleMessages() : [];
|
||||
const messages = isOpen ? 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 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 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">
|
||||
@@ -588,7 +656,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
})}
|
||||
disabled={isBuildLoading}
|
||||
className="h-8 gap-2"
|
||||
title={t('buildButtonTooltip')}
|
||||
title="Build project"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
@@ -603,249 +671,45 @@ 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>
|
||||
)}
|
||||
<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>
|
||||
<ConsoleDropdown />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content area */}
|
||||
<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"
|
||||
<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="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>
|
||||
)}
|
||||
<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>
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Build loading overlay */}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,15 +26,12 @@ 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;
|
||||
@@ -48,7 +45,6 @@ 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
|
||||
@@ -81,95 +77,21 @@ 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>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
|
||||
function getToolInfo(toolName: string, args: Record<string, unknown>): 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 rawPath = args.path ? String(args.path) : 'File';
|
||||
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
|
||||
const path = args.path ? String(args.path) : 'File';
|
||||
const hasLineRange = args.start_line || args.end_line;
|
||||
const lineInfo = hasLineRange
|
||||
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
@@ -182,27 +104,21 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
};
|
||||
}
|
||||
|
||||
case 'text_editor_write': {
|
||||
const rawPath = args.path ? String(args.path) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
case 'text_editor_write':
|
||||
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',
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
case 'text_editor_str_replace': {
|
||||
const rawPath = args.path ? String(args.path) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
case 'text_editor_str_replace':
|
||||
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',
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
case 'npm_add_package': {
|
||||
const name = args.name ? String(args.name) : 'Package';
|
||||
@@ -218,25 +134,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
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':
|
||||
@@ -244,55 +160,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
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 ? `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',
|
||||
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',
|
||||
};
|
||||
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
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',
|
||||
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',
|
||||
};
|
||||
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: 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',
|
||||
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',
|
||||
};
|
||||
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
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',
|
||||
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',
|
||||
};
|
||||
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Viewed NIPs index',
|
||||
callingTitle: 'Viewing NIPs index',
|
||||
errorTitle: 'Failed to view NIPs index',
|
||||
title: 'Read NIPs Index',
|
||||
callingTitle: 'Reading NIPs Index',
|
||||
errorTitle: 'Failed to Read 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': {
|
||||
@@ -301,117 +217,58 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
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: 'Viewed console',
|
||||
callingTitle: 'Viewing console',
|
||||
errorTitle: 'Failed to view console',
|
||||
title: 'Read Console',
|
||||
callingTitle: 'Reading Console',
|
||||
errorTitle: 'Failed to Read 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 {
|
||||
@@ -442,13 +299,12 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
|
||||
/**
|
||||
* Unified component for displaying tool calls in all states
|
||||
*/
|
||||
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
|
||||
export function ToolCallDisplay({ toolName, toolArgs, state, result }: 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, projectId, projectsPath, result);
|
||||
const toolInfo = getToolInfo(toolName, toolArgs);
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Check if this is an error result
|
||||
@@ -486,26 +342,19 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
{toolArgs.file_text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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');
|
||||
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');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
@@ -538,56 +387,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
@@ -597,58 +396,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// 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">
|
||||
|
||||
@@ -35,6 +35,7 @@ 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);
|
||||
|
||||
@@ -251,7 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
setComment('Zapped from Shakespeare!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
|
||||
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
|
||||
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
|
||||
|
||||
const [subdomainResponse, workersResponse] = await Promise.all([
|
||||
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -56,7 +56,7 @@ export function DenoDeployForm({
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
|
||||
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
|
||||
@@ -4,7 +4,6 @@ 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;
|
||||
@@ -15,7 +14,6 @@ interface DeployButtonProps {
|
||||
|
||||
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
@@ -26,7 +24,6 @@ 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>
|
||||
|
||||
@@ -13,6 +13,10 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
@@ -23,7 +27,6 @@ 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';
|
||||
@@ -32,7 +35,6 @@ 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
|
||||
@@ -103,14 +105,6 @@ 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();
|
||||
@@ -120,6 +114,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { git } = useGit();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
@@ -148,13 +144,6 @@ 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(() => {
|
||||
@@ -259,7 +248,6 @@ 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;
|
||||
@@ -279,23 +267,6 @@ 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');
|
||||
}
|
||||
@@ -355,20 +326,68 @@ 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);
|
||||
|
||||
// Update repository announcement with deployment URL if using Nostr git
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||
|
||||
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
|
||||
// Query for existing repository announcement
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
const existingEvent = existingRepos[0];
|
||||
|
||||
// Extract existing data from the event
|
||||
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const existingWebUrls = webTag ? webTag.slice(1) : [];
|
||||
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
|
||||
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1) : [];
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
|
||||
|
||||
// Add deployment URL if not already present
|
||||
const deploymentUrl = result.url;
|
||||
const updatedWebUrls = existingWebUrls.includes(deploymentUrl)
|
||||
? existingWebUrls
|
||||
: [...existingWebUrls, deploymentUrl];
|
||||
|
||||
// Create updated repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: nostrURI.identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls: updatedWebUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
await publishEvent(eventTemplate);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - updating web tag is not critical for deployment
|
||||
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
@@ -387,7 +406,6 @@ 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();
|
||||
};
|
||||
|
||||
@@ -419,16 +437,6 @@ 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;
|
||||
|
||||
@@ -534,30 +542,6 @@ 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;
|
||||
};
|
||||
|
||||
@@ -734,8 +718,7 @@ 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 === 'railway' && !railwayForm.workspaceId)
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
|
||||
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/sites`;
|
||||
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
|
||||
@@ -1,382 +0,0 @@
|
||||
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,7 +7,6 @@ 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;
|
||||
@@ -19,7 +18,6 @@ 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();
|
||||
@@ -131,7 +129,6 @@ 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,6 +2,7 @@ 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';
|
||||
@@ -19,8 +20,6 @@ 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 {
|
||||
@@ -42,8 +41,7 @@ export function ConfigureRepoStep({
|
||||
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
|
||||
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { git } = useGit();
|
||||
@@ -76,10 +74,9 @@ export function ConfigureRepoStep({
|
||||
setIsRepoNameManuallyEdited(true);
|
||||
};
|
||||
|
||||
// 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;
|
||||
const handlePushInitial = async () => {
|
||||
setIsPushing(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedProvider.id === 'nostr') {
|
||||
@@ -199,14 +196,12 @@ 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
|
||||
@@ -221,14 +216,12 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -245,45 +238,8 @@ export function ConfigureRepoStep({
|
||||
// Show success state
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
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);
|
||||
const message = err instanceof Error ? err.message : 'Failed to push';
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
@@ -387,13 +343,9 @@ export function ConfigureRepoStep({
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
onDismiss={() => setError(null)}
|
||||
onForcePush={() => setShowForcePushDialog(true)}
|
||||
remoteName={selectedProvider.name}
|
||||
context="configure"
|
||||
/>
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
@@ -408,13 +360,6 @@ export function ConfigureRepoStep({
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ForcePushDialog
|
||||
open={showForcePushDialog}
|
||||
onOpenChange={setShowForcePushDialog}
|
||||
onConfirm={handleForcePush}
|
||||
remoteName={selectedProvider.name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -441,13 +386,9 @@ export function ConfigureRepoStep({
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
onDismiss={() => setError(null)}
|
||||
onForcePush={() => setShowForcePushDialog(true)}
|
||||
remoteName={selectedProvider.name}
|
||||
context="configure"
|
||||
/>
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
@@ -466,13 +407,6 @@ export function ConfigureRepoStep({
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ForcePushDialog
|
||||
open={showForcePushDialog}
|
||||
onOpenChange={setShowForcePushDialog}
|
||||
onConfirm={handleForcePush}
|
||||
remoteName={selectedProvider.name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
|
||||
|
||||
if (url.protocol === 'nostr:') {
|
||||
const nostrUri = await NostrURI.parse(url.href);
|
||||
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
|
||||
return ngitWebUrl(config.ngitWebUrl, nostrUri);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -8,16 +8,14 @@ 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, context = 'sync' }: SyncStepErrorProps) {
|
||||
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
|
||||
const renderForcePullButton = () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -106,23 +104,17 @@ 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">
|
||||
{message}
|
||||
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{/* Only show Pull button in sync context (not during initial configure) */}
|
||||
{context === 'sync' && onPull && renderPullButton()}
|
||||
{renderPullButton()}
|
||||
{renderForcePushButton()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -134,43 +126,17 @@ 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}`;
|
||||
|
||||
// Check if remoteUrl is a Nostr URL
|
||||
if (remoteUrl?.protocol === 'nostr:') {
|
||||
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 && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
|
||||
// Handle standard HTTP errors based on status code
|
||||
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
|
||||
switch (error.data.statusCode) {
|
||||
case 401:
|
||||
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>.</>;
|
||||
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>.</>
|
||||
break;
|
||||
case 403:
|
||||
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.</>;
|
||||
}
|
||||
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>.</>;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ export interface AIProvider {
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
proxy?: boolean;
|
||||
openSecret?: string;
|
||||
}
|
||||
|
||||
export interface MCPServer {
|
||||
|
||||
@@ -50,14 +50,7 @@ export interface DenoDeployProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface RailwayProvider extends BaseDeployProvider {
|
||||
type: 'railway';
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
+5
-11
@@ -46,10 +46,8 @@ export function useAIChat({
|
||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||
|
||||
const initSession = useCallback(async (showLoading = true) => {
|
||||
if (showLoading) {
|
||||
setIsLoadingHistory(true);
|
||||
}
|
||||
const initSession = useCallback(async () => {
|
||||
setIsLoadingHistory(true);
|
||||
try {
|
||||
// Load or update session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||
@@ -61,9 +59,7 @@ export function useAIChat({
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
setLastFinishReason(session.lastFinishReason ?? null);
|
||||
} finally {
|
||||
if (showLoading) {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
}, [sessionManager, projectId, tools, customTools, maxSteps]);
|
||||
|
||||
@@ -133,8 +129,7 @@ export function useAIChat({
|
||||
providerModel: string
|
||||
) => {
|
||||
try {
|
||||
// Ensure session is loaded (without showing loading state)
|
||||
await initSession(false);
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
@@ -147,8 +142,7 @@ export function useAIChat({
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
try {
|
||||
// Ensure session is loaded (without showing loading state)
|
||||
await initSession(false);
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
|
||||
@@ -13,7 +13,7 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys],
|
||||
queryFn: async (): Promise<Repository[]> => {
|
||||
if (followedPubkeys.length === 0) {
|
||||
return [];
|
||||
@@ -50,10 +50,19 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
@@ -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({ template: corsProxy, url: 'https://api.github.com/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -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({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -5,14 +5,12 @@ import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
import type { NostrEvent } from "@nostrify/nostrify";
|
||||
|
||||
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
|
||||
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (t: NostrEventInput) => {
|
||||
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
||||
if (user) {
|
||||
const tags = t.tags ?? [];
|
||||
|
||||
|
||||
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
|
||||
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
|
||||
const tokenResponse = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OGMetadata {
|
||||
image: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch Open Graph metadata from a web URL using CORS proxy
|
||||
* @param webUrl - The web URL to fetch OG metadata from
|
||||
* @returns Query result with OG image URL and description
|
||||
*/
|
||||
export function useOGImage(webUrl?: string) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['og-metadata', webUrl],
|
||||
queryFn: async (): Promise<OGMetadata> => {
|
||||
if (!webUrl) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
try {
|
||||
// Use CORS proxy to fetch the HTML
|
||||
const proxiedUrl = proxyUrl(config.corsProxy, webUrl);
|
||||
const response = await fetch(proxiedUrl, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
|
||||
// Extract OG image
|
||||
let ogImage: string | null = null;
|
||||
const ogImageMeta = doc.querySelector('meta[property="og:image"]')?.getAttribute('content');
|
||||
if (ogImageMeta) {
|
||||
try {
|
||||
ogImage = new URL(ogImageMeta, webUrl).href;
|
||||
} catch {
|
||||
ogImage = ogImageMeta.startsWith('http') ? ogImageMeta : null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to twitter:image if og:image not found
|
||||
if (!ogImage) {
|
||||
const twitterImage = doc.querySelector('meta[name="twitter:image"]')?.getAttribute('content');
|
||||
if (twitterImage) {
|
||||
try {
|
||||
ogImage = new URL(twitterImage, webUrl).href;
|
||||
} catch {
|
||||
ogImage = twitterImage.startsWith('http') ? twitterImage : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract OG description
|
||||
let ogDescription: string | null = null;
|
||||
const ogDescriptionMeta = doc.querySelector('meta[property="og:description"]')?.getAttribute('content');
|
||||
if (ogDescriptionMeta) {
|
||||
ogDescription = ogDescriptionMeta.trim();
|
||||
}
|
||||
|
||||
// Fallback to twitter:description if og:description not found
|
||||
if (!ogDescription) {
|
||||
const twitterDescription = doc.querySelector('meta[name="twitter:description"]')?.getAttribute('content');
|
||||
if (twitterDescription) {
|
||||
ogDescription = twitterDescription.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
image: ogImage,
|
||||
description: ogDescription || null,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch OG metadata:', error);
|
||||
return { image: null, description: null };
|
||||
}
|
||||
},
|
||||
enabled: !!webUrl,
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { getPluginSkills } from '@/lib/skills';
|
||||
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { useGit } from './useGit';
|
||||
import { join } from 'path-browserify';
|
||||
|
||||
|
||||
@@ -52,17 +52,6 @@ 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,
|
||||
@@ -70,7 +59,6 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
vercelProjectConfigSchema,
|
||||
cloudflareProjectConfigSchema,
|
||||
denoDeployProjectConfigSchema,
|
||||
railwayProjectConfigSchema,
|
||||
]);
|
||||
|
||||
const projectDeploySettingsSchema = z.object({
|
||||
@@ -84,7 +72,6 @@ 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>;
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useFS } from './useFS';
|
||||
import { loadProjectTools } from '@/lib/tools/project-tools-loader';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
/**
|
||||
* Hook to load project-specific tools from .opencode/tools directory
|
||||
*/
|
||||
export function useProjectTools(projectPath: string, esmUrl: string): Record<string, Tool<unknown>> {
|
||||
const { fs } = useFS();
|
||||
const [tools, setTools] = useState<Record<string, Tool<unknown>>>({});
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
|
||||
async function load() {
|
||||
console.log(`[useProjectTools] Loading tools for project: ${projectPath}`);
|
||||
try {
|
||||
// Use static IDs since project tools don't need to be session-specific
|
||||
const loadedTools = await loadProjectTools(fs, projectPath, 'shakespeare', 'project-tools', esmUrl);
|
||||
if (mounted) {
|
||||
const toolCount = Object.keys(loadedTools).length;
|
||||
console.log(`[useProjectTools] Setting ${toolCount} tool(s) in state`);
|
||||
setTools(loadedTools);
|
||||
} else {
|
||||
console.log(`[useProjectTools] Component unmounted, not setting tools`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[useProjectTools] Failed to load project tools:', error);
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [fs, projectPath, esmUrl]);
|
||||
|
||||
console.log(`[useProjectTools] Current tools in state: ${Object.keys(tools).length} tool(s) - ${Object.keys(tools).join(', ')}`);
|
||||
|
||||
return tools;
|
||||
}
|
||||
@@ -55,10 +55,19 @@ export function useUserRepositories(userPubkey?: string) {
|
||||
try {
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
@@ -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({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -661,7 +661,7 @@ export class SessionManager {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle user cancellation
|
||||
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
@@ -720,50 +720,13 @@ 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: finalContent,
|
||||
content,
|
||||
tool_call_id: toolCallId
|
||||
};
|
||||
|
||||
|
||||
@@ -12,19 +12,15 @@ 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 openai = new OpenAI({
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
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
|
||||
@@ -51,7 +47,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({ template: corsProxy, url: request.url }), request);
|
||||
request = new Request(proxyUrl(corsProxy, request.url), request);
|
||||
}
|
||||
|
||||
return fetch(request);
|
||||
|
||||
@@ -6,7 +6,6 @@ export interface PresetProvider {
|
||||
nostr?: boolean;
|
||||
tosURL?: string;
|
||||
proxy?: boolean;
|
||||
openSecret?: string;
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
@@ -17,6 +16,13 @@ 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",
|
||||
@@ -25,21 +31,6 @@ 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",
|
||||
|
||||
@@ -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: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
|
||||
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
|
||||
if (next === current) break;
|
||||
current = next;
|
||||
const candidate = `${current}/node_modules/${name}`;
|
||||
@@ -226,11 +226,6 @@ 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}` }],
|
||||
@@ -265,19 +260,6 @@ 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);
|
||||
|
||||
@@ -448,8 +430,6 @@ 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") {
|
||||
|
||||
+13
-94
@@ -10,21 +10,14 @@ 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, packageJson } = options;
|
||||
const { fs, cwd, tsconfig } = options;
|
||||
return {
|
||||
name: "fs",
|
||||
|
||||
@@ -37,66 +30,27 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
// Skip resolving paths from external URLs (but not fs: namespace)
|
||||
// Skip resolving paths from external URLs
|
||||
if (/^https?:\/\//.test(args.importer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolved: string | undefined;
|
||||
|
||||
// Handle absolute paths
|
||||
let resolved: string;
|
||||
if (args.path.startsWith("/")) {
|
||||
resolved = args.path;
|
||||
}
|
||||
// Handle @/ alias
|
||||
else if (args.path.startsWith("@/")) {
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, "src", args.path.slice(2));
|
||||
}
|
||||
// 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) {
|
||||
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
||||
}
|
||||
// Nothing matched, let other plugins handle it
|
||||
else {
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resolved) {
|
||||
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}`);
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
@@ -160,43 +114,8 @@ async function tryFileVariants(
|
||||
return basePath;
|
||||
}
|
||||
|
||||
// If it's a directory, try package.json first, then index files
|
||||
// If it's a directory, try 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);
|
||||
|
||||
@@ -130,7 +130,7 @@ describe('buildProject', () => {
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.readdir)
|
||||
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
|
||||
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
|
||||
if (path === '/test/project/public') {
|
||||
return [
|
||||
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
|
||||
@@ -535,63 +535,4 @@ 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');
|
||||
});
|
||||
});
|
||||
+57
-113
@@ -10,7 +10,6 @@ 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;
|
||||
@@ -21,115 +20,6 @@ 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>> {
|
||||
@@ -141,8 +31,58 @@ async function bundle(
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Read build context (package.json, package-lock.json, tsconfig.json)
|
||||
const context = await readBuildContext(fs, projectPath);
|
||||
// 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}`);
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
const entryPoints: string[] = [];
|
||||
@@ -188,7 +128,11 @@ async function bundle(
|
||||
entryNames: "[name]-[hash]",
|
||||
chunkNames: "[name]-[hash]",
|
||||
assetNames: "[name]-[hash]",
|
||||
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
|
||||
plugins: [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig }),
|
||||
esmPlugin({ packageJson, packageLock, target, esmUrl }),
|
||||
],
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { saveFileToTmp } from './fileUtils';
|
||||
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
|
||||
import { fileToUrl } from './imageUtils';
|
||||
|
||||
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||
|
||||
@@ -41,11 +41,8 @@ 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, processedFile, tmpPath);
|
||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||
|
||||
// Always add text part with VFS path
|
||||
const textPart: ContentPart = {
|
||||
@@ -54,10 +51,10 @@ export async function buildMessageContent(
|
||||
};
|
||||
|
||||
// For all image types, also add as image_url for UI display with base64 encoding
|
||||
const isImage = processedFile.type.startsWith('image/');
|
||||
const isImage = file.type.startsWith('image/');
|
||||
if (isImage) {
|
||||
try {
|
||||
const imageUrl = await fileToUrl(processedFile);
|
||||
const imageUrl = await fileToUrl(file);
|
||||
// Return both parts: image_url for UI display and text for VFS path
|
||||
return [textPart, {
|
||||
type: 'image_url' as const,
|
||||
|
||||
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
|
||||
|
||||
// Proxy the URL through configured CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
|
||||
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
|
||||
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
|
||||
// Create the directory
|
||||
await this.fs.mkdir(absolutePath);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 instanceof Error ? error.message : String(error)}`);
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ 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(
|
||||
@@ -130,12 +129,6 @@ 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,
|
||||
@@ -143,7 +136,6 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
|
||||
nsiteProviderSchema,
|
||||
cloudflareProviderSchema,
|
||||
denoDeployProviderSchema,
|
||||
railwayProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
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 };
|
||||
@@ -28,16 +24,6 @@ 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;
|
||||
@@ -63,7 +49,6 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
private baseDomain: string;
|
||||
private projectName?: string;
|
||||
private corsProxy?: string;
|
||||
private esmUrl: string;
|
||||
|
||||
constructor(config: CloudflareDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
@@ -73,15 +58,11 @@ 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 {
|
||||
@@ -134,7 +115,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
}
|
||||
|
||||
// Step 4: Deploy the worker with assets
|
||||
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
|
||||
const deployment = await this.deployWorker(scriptName, completionJwt);
|
||||
|
||||
// Step 5: Enable the workers.dev subdomain for this script
|
||||
await this.enableWorkersDevSubdomain(scriptName);
|
||||
@@ -159,7 +140,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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
@@ -179,7 +160,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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -204,7 +185,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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -230,7 +211,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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -268,105 +249,37 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
return data.result || {};
|
||||
}
|
||||
|
||||
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
// 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> {
|
||||
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(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
|
||||
}
|
||||
// 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 });
|
||||
}
|
||||
};
|
||||
`;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
// Add the worker script as the main module
|
||||
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
|
||||
formData.append(mainModuleName, scriptBlob, mainModuleName);
|
||||
formData.append('worker.js', scriptBlob, 'worker.js');
|
||||
|
||||
// Add metadata with assets configuration
|
||||
const metadata = {
|
||||
main_module: mainModuleName,
|
||||
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
|
||||
main_module: 'worker.js',
|
||||
compatibility_date: new Date().toISOString().split('T')[0],
|
||||
assets: {
|
||||
jwt: assetsJwt,
|
||||
config: {
|
||||
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
|
||||
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
|
||||
html_handling: 'auto-trailing-slash',
|
||||
not_found_handling: 'single-page-application',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -390,27 +303,6 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
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,
|
||||
@@ -511,23 +403,4 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
};
|
||||
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 });
|
||||
}
|
||||
};`;
|
||||
}
|
||||
}
|
||||
@@ -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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
// Create a minimal server script that serves static files
|
||||
// For static sites, we use a simple file server entry point
|
||||
|
||||
@@ -11,13 +11,11 @@ interface NetlifySite {
|
||||
admin_url: string;
|
||||
}
|
||||
|
||||
interface NetlifyDeployResponse {
|
||||
interface NetlifyBuildResponse {
|
||||
id: string;
|
||||
deploy_id: string;
|
||||
state: string;
|
||||
error?: string;
|
||||
required?: string[];
|
||||
required_functions?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,47 +65,31 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
siteUrl = site.url;
|
||||
}
|
||||
|
||||
// Collect files and their SHA1 hashes
|
||||
const files: Record<string, string> = {};
|
||||
const fileContents = new Map<string, Uint8Array>();
|
||||
await this.collectFiles(distPath, '', files, fileContents);
|
||||
// Create ZIP of dist directory
|
||||
const zip = new JSZip();
|
||||
await this.addDirectoryToZip(distPath, zip);
|
||||
|
||||
// Ensure _redirects file exists for SPA routing
|
||||
await this.ensureRedirectsInFiles(distPath, files, fileContents);
|
||||
await this.ensureRedirectsFile(distPath, zip);
|
||||
|
||||
// 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);
|
||||
// Generate ZIP blob
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// 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);
|
||||
}
|
||||
// Deploy to Netlify
|
||||
await this.triggerDeploy(activeSiteId, zipBlob);
|
||||
|
||||
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({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -131,7 +113,7 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
|
||||
private async getSite(siteId: string): Promise<NetlifySite> {
|
||||
const url = `${this.baseURL}/sites/${siteId}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
@@ -148,57 +130,45 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async createDeployWithDigest(
|
||||
siteId: string,
|
||||
files: Record<string, string>,
|
||||
functions: Record<string, string>
|
||||
): Promise<NetlifyDeployResponse> {
|
||||
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
|
||||
const url = `${this.baseURL}/sites/${siteId}/deploys`;
|
||||
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 targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/zip',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: zipBlob,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
|
||||
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async collectFiles(
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
files: Record<string, string>,
|
||||
fileContents: Map<string, Uint8Array>
|
||||
): Promise<void> {
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): 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()) {
|
||||
await this.collectFiles(fullPath, relPath, files, fileContents);
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
const sha1 = await this.calculateSHA1(fileContent);
|
||||
files[`/${relPath}`] = sha1;
|
||||
fileContents.set(sha1, fileContent);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
@@ -211,13 +181,9 @@ 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 files manifest
|
||||
* If not present in dist directory, adds it to the ZIP with default content
|
||||
*/
|
||||
private async ensureRedirectsInFiles(
|
||||
distPath: string,
|
||||
files: Record<string, string>,
|
||||
fileContents: Map<string, Uint8Array>
|
||||
): Promise<void> {
|
||||
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
|
||||
const redirectsPath = `${distPath}/_redirects`;
|
||||
|
||||
try {
|
||||
@@ -226,146 +192,11 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
if (!stat.isFile()) {
|
||||
throw new Error('_redirects is not a file');
|
||||
}
|
||||
// File exists, already collected by collectFiles
|
||||
// File exists, no need to add it (already added by addDirectoryToZip)
|
||||
} catch {
|
||||
// File doesn't exist, add default _redirects
|
||||
// File doesn't exist, add default _redirects to ZIP
|
||||
const defaultRedirects = '/* /index.html 200';
|
||||
const content = new TextEncoder().encode(defaultRedirects);
|
||||
const sha1 = await this.calculateSHA1(content);
|
||||
files['/_redirects'] = sha1;
|
||||
fileContents.set(sha1, content);
|
||||
zip.file('_redirects', defaultRedirects);
|
||||
}
|
||||
}
|
||||
|
||||
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('');
|
||||
}
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
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.');
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ export class ShakespeareAdapter implements DeployAdapter {
|
||||
|
||||
// Apply proxy if configured
|
||||
if (this.corsProxy) {
|
||||
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
|
||||
request = new Request(proxyUrl(this.corsProxy, request.url), request);
|
||||
}
|
||||
|
||||
// Deploy
|
||||
|
||||
@@ -68,7 +68,7 @@ export class VercelAdapter implements DeployAdapter {
|
||||
}
|
||||
|
||||
// Apply proxy if configured
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: apiUrl }) : apiUrl;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
|
||||
|
||||
// Deploy to Vercel
|
||||
const response = await fetch(targetUrl, {
|
||||
|
||||
@@ -5,4 +5,3 @@ export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
export * from './CloudflareAdapter';
|
||||
export * from './DenoDeployAdapter';
|
||||
export * from './RailwayAdapter';
|
||||
+1
-14
@@ -63,7 +63,6 @@ export interface CloudflareDeployConfig {
|
||||
baseDomain?: string;
|
||||
projectName?: string;
|
||||
corsProxy?: string;
|
||||
esmUrl: string;
|
||||
}
|
||||
|
||||
export interface DenoDeployConfig {
|
||||
@@ -76,21 +75,9 @@ 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' | 'railway';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
|
||||
name: string;
|
||||
description: string;
|
||||
baseURL?: string;
|
||||
|
||||
@@ -60,14 +60,4 @@ 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,
|
||||
},
|
||||
];
|
||||
+5
-11
@@ -1,21 +1,15 @@
|
||||
import UriTemplate from 'uri-templates';
|
||||
|
||||
export interface FaviconUrlOpts {
|
||||
template: string;
|
||||
url: string | URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a favicon URL from a template and input URL
|
||||
* @param opts - Options object
|
||||
* @param opts.template - URL template with placeholders like {hostname}, {origin}, etc.
|
||||
* @param opts.url - The URL to extract parts from
|
||||
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
|
||||
* @param url - The URL to extract parts from
|
||||
* @returns The hydrated favicon URL
|
||||
*/
|
||||
export function faviconUrl(opts: FaviconUrlOpts): string {
|
||||
const u = new URL(opts.url);
|
||||
export function faviconUrl(template: string, url: string | URL): string {
|
||||
const u = new URL(url);
|
||||
|
||||
return UriTemplate(opts.template).fill({
|
||||
return UriTemplate(template).fill({
|
||||
href: u.href,
|
||||
origin: u.origin,
|
||||
protocol: u.protocol,
|
||||
|
||||
+2
-1
@@ -1107,6 +1107,7 @@ class GitHttp implements HttpClient {
|
||||
|
||||
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
|
||||
this.proxy = proxy;
|
||||
// Bind fetch to globalThis to preserve context when called as this.fetch()
|
||||
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
@@ -1115,7 +1116,7 @@ class GitHttp implements HttpClient {
|
||||
const url = new URL(request.url);
|
||||
|
||||
const target = this.proxy
|
||||
? proxyUrl({ template: this.proxy, url })
|
||||
? proxyUrl(this.proxy, url)
|
||||
: url.href;
|
||||
|
||||
const init: RequestInit = {
|
||||
|
||||
@@ -1,143 +1,3 @@
|
||||
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.
|
||||
*
|
||||
|
||||
@@ -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/);
|
||||
|
||||
+8
-14
@@ -2,26 +2,20 @@ 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 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
|
||||
* @param template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
|
||||
* @param nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
|
||||
* @returns The hydrated web URL
|
||||
*/
|
||||
export function ngitWebUrl(opts: NgitWebUrlOpts): string {
|
||||
const naddr = opts.nostrURI.toNaddr();
|
||||
const npub = nip19.npubEncode(opts.nostrURI.pubkey);
|
||||
export function ngitWebUrl(template: string, nostrURI: NostrURI): string {
|
||||
const naddr = nostrURI.toNaddr();
|
||||
const npub = nip19.npubEncode(nostrURI.pubkey);
|
||||
|
||||
return UriTemplate(opts.template).fill({
|
||||
return UriTemplate(template).fill({
|
||||
naddr,
|
||||
npub,
|
||||
pubkey: opts.nostrURI.pubkey,
|
||||
identifier: opts.nostrURI.identifier,
|
||||
pubkey: nostrURI.pubkey,
|
||||
identifier: nostrURI.identifier,
|
||||
});
|
||||
}
|
||||
+386
-1
@@ -1,6 +1,14 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import { getPlugins } from './plugins';
|
||||
import {
|
||||
getPlugins,
|
||||
getPluginSkills,
|
||||
getProjectSkills,
|
||||
getAllSkills,
|
||||
findSkill,
|
||||
readSkillContent,
|
||||
isValidSkillName,
|
||||
} from './plugins';
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS implements JSRuntimeFS {
|
||||
@@ -156,6 +164,24 @@ 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');
|
||||
@@ -173,4 +199,363 @@ 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([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
@@ -1,13 +1,38 @@
|
||||
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
|
||||
*/
|
||||
@@ -30,6 +55,150 @@ 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
|
||||
*/
|
||||
|
||||
+3
-8
@@ -1,13 +1,8 @@
|
||||
import UriTemplate from 'uri-templates';
|
||||
|
||||
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({
|
||||
export function proxyUrl(template: string, url: string | URL): string {
|
||||
const u = new URL(url);
|
||||
return UriTemplate(template).fill({
|
||||
href: u.href,
|
||||
origin: u.origin,
|
||||
protocol: u.protocol,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Wallet } from 'lucide-react';
|
||||
|
||||
export interface SettingsItem {
|
||||
id: string;
|
||||
@@ -59,6 +59,12 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
|
||||
title: t('nostrSettings'),
|
||||
href: '/settings/nostr',
|
||||
},
|
||||
{
|
||||
id: 'wallet',
|
||||
icon: Wallet,
|
||||
title: t('walletSettings'),
|
||||
href: '/settings/wallet',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,705 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,194 +0,0 @@
|
||||
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');
|
||||
}
|
||||
+26
-28
@@ -6,8 +6,8 @@ import { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
// Mock the skills module
|
||||
vi.mock('./skills', () => ({
|
||||
// Mock the plugins module
|
||||
vi.mock('./plugins', () => ({
|
||||
getAllSkills: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -16,7 +16,7 @@ vi.mock('path-browserify', () => ({
|
||||
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
|
||||
}));
|
||||
|
||||
import { getAllSkills } from './skills';
|
||||
import { getAllSkills } from './plugins';
|
||||
|
||||
// Test configuration
|
||||
const testConfig: AppConfig = {
|
||||
@@ -196,14 +196,14 @@ describe('makeSystemPrompt', () => {
|
||||
});
|
||||
|
||||
describe('tools section', () => {
|
||||
it('should pass tools to template context when no tools are provided', async () => {
|
||||
it('should show no tools message when no tools are provided', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
// Tools are passed to context but not rendered by default template
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toContain('## Available Tools');
|
||||
expect(result).toContain('There are no tools available to you.');
|
||||
});
|
||||
|
||||
it('should pass tools to template context when tools are provided', async () => {
|
||||
it('should list available tools with descriptions', async () => {
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{
|
||||
type: 'function',
|
||||
@@ -225,54 +225,49 @@ describe('makeSystemPrompt', () => {
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, tools });
|
||||
|
||||
// Tools are passed to context but not rendered by default template
|
||||
expect(result).toBeTruthy();
|
||||
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');
|
||||
});
|
||||
|
||||
it('should render tools with custom template', async () => {
|
||||
it('should handle tools without descriptions', async () => {
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'some_tool',
|
||||
description: 'A test tool',
|
||||
parameters: {},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const customTemplate = '## Available Tools\n{% for tool in tools %}**{{ tool.function.name }}**: {{ tool.function.description or "No description available" }}\n{% endfor %}';
|
||||
const result = await makeSystemPrompt({ ...baseOpts, tools });
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, tools, template: customTemplate });
|
||||
|
||||
expect(result).toContain('## Available Tools');
|
||||
expect(result).toContain('**some_tool**: A test tool');
|
||||
expect(result).toContain('**some_tool**: No description available');
|
||||
});
|
||||
});
|
||||
|
||||
describe('skills section', () => {
|
||||
it('should not call getAllSkills when pluginsPath is not provided', async () => {
|
||||
it('should show no skills message when pluginsPath is not provided', async () => {
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
config: { ...testConfig, fsPathPlugins: '' },
|
||||
});
|
||||
|
||||
// Skills are not fetched when pluginsPath is empty
|
||||
expect(result).toBeTruthy();
|
||||
expect(getAllSkills).not.toHaveBeenCalled();
|
||||
expect(result).toContain('## Skills');
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
});
|
||||
|
||||
it('should fetch skills when pluginsPath is provided but return empty array', async () => {
|
||||
it('should show no skills message when getAllSkills returns empty array', async () => {
|
||||
vi.mocked(getAllSkills).mockResolvedValue([]);
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
// Skills are passed to context but not rendered by default template
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
|
||||
});
|
||||
|
||||
it('should pass skills to template context when they exist', async () => {
|
||||
it('should list available skills when they exist', async () => {
|
||||
vi.mocked(getAllSkills).mockResolvedValue([
|
||||
{
|
||||
name: 'create_component',
|
||||
@@ -290,8 +285,11 @@ describe('makeSystemPrompt', () => {
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
// Skills are passed to context but not rendered by default template
|
||||
expect(result).toBeTruthy();
|
||||
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');
|
||||
});
|
||||
|
||||
it('should handle getAllSkills errors gracefully', async () => {
|
||||
@@ -299,8 +297,7 @@ describe('makeSystemPrompt', () => {
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
// Should continue with empty skills array
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -432,6 +429,7 @@ 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');
|
||||
});
|
||||
|
||||
+23
-48
@@ -5,7 +5,7 @@ import OpenAI from "openai";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import nunjucks from "nunjucks";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
import { getAllSkills } from "./skills";
|
||||
import { getAllSkills } from "./plugins";
|
||||
import type { AppConfig } from "@/contexts/AppContext";
|
||||
|
||||
export interface ModelInfo {
|
||||
@@ -181,6 +181,13 @@ 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.
|
||||
@@ -193,6 +200,21 @@ 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:
|
||||
@@ -201,53 +223,6 @@ 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
|
||||
|
||||
@@ -1,609 +0,0 @@
|
||||
// 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];
|
||||
}
|
||||
@@ -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({ template: this.corsProxy, url: firstImage.url }) : firstImage.url;
|
||||
const imageUrl = this.corsProxy ? proxyUrl(this.corsProxy, firstImage.url) : firstImage.url;
|
||||
const imageResponse = await fetch(imageUrl);
|
||||
|
||||
if (!imageResponse.ok) {
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
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]}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
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)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-39
@@ -1,7 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import { readSkillContent, type Skill } from '../skills';
|
||||
import { findSkill, readSkillContent } from '../plugins';
|
||||
|
||||
interface SkillParams {
|
||||
name: string;
|
||||
@@ -9,65 +9,45 @@ interface SkillParams {
|
||||
|
||||
export class SkillTool implements Tool<SkillParams> {
|
||||
private fs: JSRuntimeFS;
|
||||
private availableSkills: Skill[];
|
||||
readonly description: string;
|
||||
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.';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
name: z.string().describe('The skill identifier from available_skills'),
|
||||
name: z.string().describe('The name of the skill to execute (lowercase alphanumeric with hyphens)'),
|
||||
});
|
||||
|
||||
/**
|
||||
* Create a SkillTool instance.
|
||||
* @param fs - Filesystem instance
|
||||
* @param availableSkills - List of available skills (should be pre-loaded)
|
||||
*/
|
||||
constructor(fs: JSRuntimeFS, availableSkills: Skill[]) {
|
||||
constructor(fs: JSRuntimeFS, pluginsPath: string, projectPath: string) {
|
||||
this.fs = fs;
|
||||
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');
|
||||
this.pluginsPath = pluginsPath;
|
||||
this.projectPath = projectPath;
|
||||
}
|
||||
|
||||
async execute(args: SkillParams): Promise<ToolResult> {
|
||||
const { name } = args;
|
||||
|
||||
try {
|
||||
// Find the skill in the pre-loaded list
|
||||
const skill = this.availableSkills.find(s => s.name === name);
|
||||
// Find the skill across all plugins and project
|
||||
const skill = await findSkill(this.fs, this.pluginsPath, this.projectPath, name);
|
||||
|
||||
if (!skill) {
|
||||
const available = this.availableSkills.map(s => s.name).join(', ');
|
||||
throw new Error(`Skill "${name}" not found. Available skills: ${available || 'none'}`);
|
||||
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
|
||||
}
|
||||
|
||||
// Read and return the skill content
|
||||
const content = await readSkillContent(this.fs, skill);
|
||||
|
||||
return {
|
||||
content: `## Skill: ${skill.name}
|
||||
content: `# Skill: ${skill.name}
|
||||
|
||||
**Base directory**: ${skill.path}
|
||||
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
|
||||
**Description**: ${skill.description}
|
||||
**Path**: ${skill.path}
|
||||
|
||||
${content.trim()}`
|
||||
---
|
||||
|
||||
${content}`
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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";');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
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('...');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
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]}`;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,154 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user