mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Let system prompt be configurable in System Settings (EJS template)
This commit is contained in:
14 files changed
+271
-124
No files matched your search
Generated
+13
@@ -58,6 +58,7 @@
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"eta": "^4.4.1",
|
||||
"gray-matter": "^4.0.3",
|
||||
"i18next": "^25.5.2",
|
||||
"ignore": "^7.0.5",
|
||||
@@ -8120,6 +8121,18 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eta": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/eta/-/eta-4.4.1.tgz",
|
||||
"integrity": "sha512-4o6fYxhRmFmO9SJcU9PxBLYPGapvJ/Qha0ZE+Y6UE9QIUd0Wk1qaLISQ6J1bM7nOcWHhs1YmY3mfrfwkJRBTWQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/bgub/eta?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/eventemitter3": {
|
||||
"version": "4.0.7",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
|
||||
|
||||
+2
-1
@@ -71,6 +71,7 @@
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"eta": "^4.4.1",
|
||||
"gray-matter": "^4.0.3",
|
||||
"i18next": "^25.5.2",
|
||||
"ignore": "^7.0.5",
|
||||
@@ -141,4 +142,4 @@
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,8 +28,8 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, nostr, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
|
||||
}, [fs, nostr, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
|
||||
return new SessionManager(fs, nostr, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath, config.systemPrompt);
|
||||
}, [fs, nostr, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath, config.systemPrompt]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -44,6 +44,8 @@ export interface AppConfig {
|
||||
sentryDsn: string;
|
||||
/** Whether the user has enabled Sentry error reporting */
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
@@ -67,6 +67,7 @@ export class SessionManager {
|
||||
private corsProxy?: string;
|
||||
private projectsPath: string;
|
||||
private pluginsPath?: string;
|
||||
private systemPromptTemplate?: string;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
@@ -77,6 +78,7 @@ export class SessionManager {
|
||||
corsProxy?: string,
|
||||
projectsPath = '/projects',
|
||||
pluginsPath?: string,
|
||||
systemPromptTemplate?: string,
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.git = new Git({ fs, nostr, corsProxy });
|
||||
@@ -86,6 +88,7 @@ export class SessionManager {
|
||||
this.projectsPath = projectsPath;
|
||||
this.pluginsPath = pluginsPath;
|
||||
this.corsProxy = corsProxy;
|
||||
this.systemPromptTemplate = systemPromptTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -256,14 +259,13 @@ export class SessionManager {
|
||||
cwd: `${this.projectsPath}/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
pluginsPath: this.pluginsPath,
|
||||
user,
|
||||
metadata,
|
||||
corsProxy: this.corsProxy,
|
||||
repositoryUrl,
|
||||
template: this.systemPromptTemplate,
|
||||
});
|
||||
|
||||
// Prepare messages for AI
|
||||
|
||||
+54
-4
@@ -39,8 +39,6 @@ describe('makeSystemPrompt', () => {
|
||||
|
||||
// Base options for tests
|
||||
baseOpts = {
|
||||
name: 'TestBot',
|
||||
profession: 'software developer',
|
||||
tools: [],
|
||||
mode: 'agent',
|
||||
fs: mockFs,
|
||||
@@ -55,7 +53,7 @@ describe('makeSystemPrompt', () => {
|
||||
it('should generate a basic system prompt in agent mode', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('You are TestBot, an expert software developer');
|
||||
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
|
||||
expect(result).toContain('Your goal is to work on the project in the current directory');
|
||||
expect(result).toContain('explore and understand the project structure');
|
||||
});
|
||||
@@ -63,7 +61,7 @@ describe('makeSystemPrompt', () => {
|
||||
it('should generate a basic system prompt in init mode', async () => {
|
||||
const result = await makeSystemPrompt({ ...baseOpts, mode: 'init' });
|
||||
|
||||
expect(result).toContain('You are TestBot, an expert software developer');
|
||||
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
|
||||
expect(result).toContain('The files in the current directory are a template');
|
||||
expect(result).toContain('transform this template into a working project');
|
||||
});
|
||||
@@ -447,4 +445,56 @@ describe('makeSystemPrompt', () => {
|
||||
expect(result).toContain('Always commit your code changes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom template support', () => {
|
||||
it('should render a custom template when provided', async () => {
|
||||
const customTemplate = `Hello Shakespeare! Current directory: <%= ctx.cwd %>`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('Hello Shakespeare!');
|
||||
expect(result).toContain('Current directory: /projects/test-project');
|
||||
expect(result).not.toContain('# Your Environment'); // Should not include default template content
|
||||
});
|
||||
|
||||
it('should support conditional logic in custom templates', async () => {
|
||||
const customTemplate = `<% if (ctx.mode === 'init') { %>Initializing...<% } else { %>Working on project<% } %>`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
mode: 'agent',
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('Working on project');
|
||||
expect(result).not.toContain('Initializing');
|
||||
});
|
||||
|
||||
it('should provide access to all context variables in custom templates', async () => {
|
||||
const user = new NUser(
|
||||
'extension',
|
||||
'abc123def456',
|
||||
{} as NUser['signer']
|
||||
);
|
||||
|
||||
const customTemplate = `User: <%= ctx.user?.pubkey || 'none' %>
|
||||
CWD: <%= ctx.cwd %>
|
||||
Origin: <%= ctx.originUrl %>
|
||||
Skills: <%= ctx.skills.length %>`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
user,
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('User: abc123def456');
|
||||
expect(result).toContain('CWD: /projects/test-project');
|
||||
expect(result).toContain('Origin: http://localhost:3000');
|
||||
expect(result).toContain('Skills: 0');
|
||||
});
|
||||
});
|
||||
});
|
||||
+125
-115
@@ -3,12 +3,11 @@ import { NostrMetadata } from "@nostrify/nostrify";
|
||||
import { join } from "path-browserify";
|
||||
import OpenAI from "openai";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import { Eta } from "eta";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
import { getAllSkills } from "./plugins";
|
||||
|
||||
export interface MakeSystemPromptOpts {
|
||||
name: string;
|
||||
profession: string;
|
||||
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
|
||||
mode: "init" | "agent";
|
||||
fs: JSRuntimeFS;
|
||||
@@ -18,52 +17,23 @@ export interface MakeSystemPromptOpts {
|
||||
metadata?: NostrMetadata;
|
||||
corsProxy?: string;
|
||||
repositoryUrl?: string;
|
||||
template?: string;
|
||||
}
|
||||
|
||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata, corsProxy, repositoryUrl } = opts;
|
||||
/**
|
||||
* Default system prompt template.
|
||||
* This can be customized by users in Settings > System > System Prompt.
|
||||
*/
|
||||
export const defaultSystemPrompt = `<% if (ctx.mode === "init") { %>You are Shakespeare, an expert software extraordinaire. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.<% } else { %>You are Shakespeare, an expert software extraordinaire. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.<% } %>
|
||||
|
||||
let system = mode === "init"
|
||||
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
|
||||
: `You are ${name}, an expert ${profession}. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.`;
|
||||
|
||||
// Add current date
|
||||
const currentDate = new Date().toLocaleDateString("en-US", {
|
||||
weekday: "long",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
let userText: string;
|
||||
if (user) {
|
||||
userText = `The user is logged into Nostr with the following profile:
|
||||
|
||||
- **Nostr pubkey (hex)**: ${user.pubkey}
|
||||
- **Nostr npub**: ${nip19.npubEncode(user.pubkey)}`;
|
||||
|
||||
if (metadata?.name) userText += `\n- **Name**: ${metadata.name}`;
|
||||
if (metadata?.about) userText += `\n- **About**: ${metadata.about.replace(/[\r\n]+/g, ' ')}`;
|
||||
if (metadata?.website) userText += `\n- **Website**: ${metadata.website}`;
|
||||
if (metadata?.picture) userText += `\n- **Avatar**: ${metadata.picture}`;
|
||||
if (metadata?.banner) userText += `\n- **Banner**: ${metadata.banner}`;
|
||||
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
|
||||
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
|
||||
|
||||
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
} else {
|
||||
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
}
|
||||
|
||||
// Add Your Environment section
|
||||
system += `\n\n# Your Environment
|
||||
# Your Environment
|
||||
|
||||
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
|
||||
|
||||
- **Current Date**: ${currentDate}
|
||||
- **Current Page**: ${location.href}
|
||||
- **Current Working Directory**: ${cwd}
|
||||
- **Repository URL**: ${repositoryUrl}
|
||||
- **Current Date**: <%= ctx.currentDate %>
|
||||
- **Current Page**: <%= ctx.currentPage %>
|
||||
- **Current Working Directory**: <%= ctx.cwd %>
|
||||
- **Repository URL**: <%= ctx.repositoryUrl %>
|
||||
|
||||
## What Shakespeare Is
|
||||
|
||||
@@ -81,7 +51,19 @@ Shakespeare is a web-based development environment where users can build Nostr w
|
||||
|
||||
## The User
|
||||
|
||||
${userText}
|
||||
<% if (ctx.user) { %>The user is logged into Nostr with the following profile:
|
||||
|
||||
- **Nostr pubkey (hex)**: <%= ctx.user.pubkey %>
|
||||
- **Nostr npub**: <%= ctx.npub %><% if (ctx.metadata?.name) { %>
|
||||
- **Name**: <%= ctx.metadata.name %><% } %><% if (ctx.metadata?.about) { %>
|
||||
- **About**: <%= ctx.sanitizeNewlines(ctx.metadata.about) %><% } %><% if (ctx.metadata?.website) { %>
|
||||
- **Website**: <%= ctx.metadata.website %><% } %><% if (ctx.metadata?.picture) { %>
|
||||
- **Avatar**: <%= ctx.metadata.picture %><% } %><% if (ctx.metadata?.banner) { %>
|
||||
- **Banner**: <%= ctx.metadata.banner %><% } %><% if (ctx.metadata?.nip05) { %>
|
||||
- **NIP-05**: <%= ctx.metadata.nip05 %><% } %><% if (ctx.metadata?.lud16) { %>
|
||||
- **Lightning Address**: <%= ctx.metadata.lud16 %><% } %>
|
||||
|
||||
Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.<% } else { %>The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.<% } %>
|
||||
|
||||
## User Interface
|
||||
|
||||
@@ -166,121 +148,149 @@ As the AI assistant in Shakespeare, you help users by:
|
||||
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
|
||||
|
||||
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.`;
|
||||
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.<% if (ctx.tools.length > 0) { %>
|
||||
|
||||
// Add available tools to the system prompt
|
||||
const toolNames = tools
|
||||
.filter((tool) => tool.type === "function")
|
||||
.map((tool) => tool.function.name);
|
||||
## Available Tools
|
||||
|
||||
if (toolNames.length > 0) {
|
||||
system +=
|
||||
"\n\n## Available Tools\n\nYou have access to the following tools:\n";
|
||||
for (const tool of tools) {
|
||||
if (tool.type === "function") {
|
||||
system += `\n- **${tool.function.name}**: ${
|
||||
tool.function.description || "No description available"
|
||||
}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
You have access to the following tools:
|
||||
<% ctx.tools.forEach(function(tool) { if (tool.type === 'function') { %>
|
||||
- **<%= tool.function.name %>**: <%= tool.function.description || 'No description available' %><% } }); %><% } %>
|
||||
|
||||
// Add skills section
|
||||
system += "\n\n## Skills\n\n";
|
||||
## Skills
|
||||
|
||||
if (pluginsPath) {
|
||||
try {
|
||||
const skills = await getAllSkills(fs, pluginsPath);
|
||||
<% if (ctx.skills && ctx.skills.length > 0) { %>You have access to the following skills. **Skills MUST be used whenever applicable** by calling the <%= ctx.backtick %>skill<%= ctx.backtick %> tool with the skill name.
|
||||
|
||||
if (skills.length > 0) {
|
||||
system += "You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.\n\n";
|
||||
system += "Available skills:\n\n";
|
||||
Available skills:
|
||||
<% ctx.skills.forEach(function(skill) { %>
|
||||
- **<%= skill.name %>**: <%= skill.description %>
|
||||
- Plugin: <%= skill.plugin %>
|
||||
- Path: <%= skill.path %>
|
||||
<% }); %>
|
||||
|
||||
for (const skill of skills) {
|
||||
system += `- **${skill.name}**: ${skill.description}\n - Plugin: ${skill.plugin}\n - Path: ${skill.path}\n`;
|
||||
}
|
||||
**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.<% } %>
|
||||
|
||||
system += `\n**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.\n`;
|
||||
} else {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
}
|
||||
} catch {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
}
|
||||
} else {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
}
|
||||
|
||||
system += `\nUsers can configure skills in Settings > AI (${location.origin}/settings/ai) by adding plugins that contain skills.`;
|
||||
|
||||
// Add CORS proxy information
|
||||
if (corsProxy) {
|
||||
system += `
|
||||
Users can configure skills in Settings > AI (<%= ctx.originUrl %>/settings/ai) by adding plugins that contain skills.<% if (ctx.corsProxy) { %>
|
||||
|
||||
## Working Around CORS Issues
|
||||
|
||||
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
|
||||
|
||||
**CORS Proxy URL Template**: \`${corsProxy}\`
|
||||
**CORS Proxy URL Template**: <%= ctx.backtick %><%= ctx.corsProxy %><%= ctx.backtick %>
|
||||
|
||||
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.`;
|
||||
}
|
||||
|
||||
// Add Edit with Shakespeare section
|
||||
system += `
|
||||
Replace <%= ctx.backtick %>{href}<%= ctx.backtick %>, <%= ctx.backtick %>{hostname}<%= ctx.backtick %>, or other URL components in the template as needed.<% } %>
|
||||
|
||||
## Edit with Shakespeare
|
||||
|
||||
The "Edit with Shakespeare" button is a way that people can start editing any Shakespeare-compatible site with a single click. It can be added anywhere markdown or HTML is supported, including in READMEs, or within an app itself.`;
|
||||
|
||||
if (repositoryUrl) {
|
||||
const badgeUrl = new URL('/badge.svg', location.origin);
|
||||
const editUrl = new URL('/clone', location.origin);
|
||||
editUrl.searchParams.set('url', repositoryUrl);
|
||||
|
||||
system += `
|
||||
The "Edit with Shakespeare" button is a way that people can start editing any Shakespeare-compatible site with a single click. It can be added anywhere markdown or HTML is supported, including in READMEs, or within an app itself.<% if (ctx.repositoryUrl) { %>
|
||||
|
||||
This project has a repository URL configured, so you can create an "Edit with Shakespeare" button using the following code snippets:
|
||||
|
||||
**Markdown:**
|
||||
\`\`\`markdown
|
||||
[](${editUrl})
|
||||
[](<%= ctx.editUrl %>)
|
||||
\`\`\`
|
||||
|
||||
**HTML/JSX/TSX:**
|
||||
\`\`\`jsx
|
||||
<a href="${editUrl}" target="_blank">
|
||||
<img src="${badgeUrl}" alt="Edit with Shakespeare" />
|
||||
<a href="<%= ctx.editUrl %>" target="_blank">
|
||||
<img src="<%= ctx.badgeUrl %>" alt="Edit with Shakespeare" />
|
||||
</a>
|
||||
\`\`\`
|
||||
|
||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.`;
|
||||
} else {
|
||||
system += `
|
||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use <%= ctx.backtick %>height: auto<%= ctx.backtick %> in CSS (or <%= ctx.backtick %>"h-auto"<%= ctx.backtick %> in Tailwind CSS) when applicable.<% } else { %>
|
||||
|
||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.`;
|
||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.<% } %><% if (ctx.readmeText) { %>
|
||||
|
||||
<%= ctx.readmeText %><% } %><% if (ctx.agentText) { %>
|
||||
|
||||
<%= ctx.agentText %><% } %>`;
|
||||
|
||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||
const { tools, mode, fs, cwd, pluginsPath, user, metadata, corsProxy, repositoryUrl, template } = opts;
|
||||
|
||||
// Add current date
|
||||
const currentDate = new Date().toLocaleDateString("en-US", {
|
||||
weekday: "long",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
// Get skills
|
||||
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
|
||||
if (pluginsPath) {
|
||||
try {
|
||||
skills = await getAllSkills(fs, pluginsPath);
|
||||
} catch {
|
||||
// Skills not available, use empty array
|
||||
skills = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Add README.md if it exists
|
||||
// Get README.md if it exists
|
||||
let readmeText: string | undefined;
|
||||
try {
|
||||
const readmePath = join(cwd, "README.md");
|
||||
const readmeText = await fs.readFile(readmePath, "utf8");
|
||||
if (readmeText) {
|
||||
system += "\n\n" + readmeText;
|
||||
}
|
||||
readmeText = await fs.readFile(readmePath, "utf8");
|
||||
} catch {
|
||||
// README.md not found, continue
|
||||
}
|
||||
|
||||
// Add context from AGENTS.md if it exists
|
||||
// Get agent context if it exists
|
||||
let agentText: string | undefined;
|
||||
try {
|
||||
const { text } = await getAgentContext(fs, cwd);
|
||||
system += "\n\n" + text;
|
||||
agentText = text;
|
||||
} catch {
|
||||
// AGENTS.md not found, continue
|
||||
}
|
||||
|
||||
return system;
|
||||
// Build URLs for Edit with Shakespeare
|
||||
let badgeUrl: string | undefined;
|
||||
let editUrl: string | undefined;
|
||||
if (repositoryUrl) {
|
||||
badgeUrl = new URL('/badge.svg', location.origin).toString();
|
||||
const editUrlObj = new URL('/clone', location.origin);
|
||||
editUrlObj.searchParams.set('url', repositoryUrl);
|
||||
editUrl = editUrlObj.toString();
|
||||
}
|
||||
|
||||
// Build context object for template
|
||||
const context = {
|
||||
mode,
|
||||
currentDate,
|
||||
currentPage: location.href,
|
||||
cwd,
|
||||
repositoryUrl,
|
||||
user,
|
||||
npub: user ? nip19.npubEncode(user.pubkey) : undefined,
|
||||
metadata,
|
||||
tools,
|
||||
skills,
|
||||
corsProxy,
|
||||
originUrl: location.origin,
|
||||
badgeUrl,
|
||||
editUrl,
|
||||
readmeText,
|
||||
agentText,
|
||||
// Helper function to sanitize newlines in text
|
||||
sanitizeNewlines: (text: string) => text.replace(/[\r\n]+/g, ' '),
|
||||
// Helper function to output backticks
|
||||
backtick: '`',
|
||||
};
|
||||
|
||||
// Render the template with the context
|
||||
// Use the provided template, or fall back to the default
|
||||
const templateToRender = template || defaultSystemPrompt;
|
||||
|
||||
try {
|
||||
const eta = new Eta({ varName: 'ctx' });
|
||||
return eta.renderString(templateToRender, context);
|
||||
} catch (error) {
|
||||
console.error("Error rendering system prompt template:", error);
|
||||
// Return the template as-is if rendering fails
|
||||
return templateToRender;
|
||||
}
|
||||
}
|
||||
|
||||
async function getAgentContext(
|
||||
|
||||
@@ -59,6 +59,8 @@
|
||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||
"shareErrorReports": "Share error reports",
|
||||
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
|
||||
"systemPrompt": "System Prompt",
|
||||
"systemPromptDescription": "Customize the AI assistant's system prompt using EJS template syntax. This controls the assistant's behavior and knowledge.",
|
||||
"english": "English",
|
||||
"portuguese": "Portuguese",
|
||||
"chinese": "Chinese",
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Hanyar tsarin fayil inda ake adana fayilolin saiti",
|
||||
"temporaryDirectory": "Kundin Wucin Gadi",
|
||||
"temporaryDirectoryDescription": "Hanyar tsarin fayil don fayilolin wucin gadi",
|
||||
"systemPrompt": "Tambarin Tsarin",
|
||||
"systemPromptDescription": "Keɓanta tambarin tsarin mataimaki na AI ta amfani da tsarin samfuri na EJS. Wannan yana sarrafa ɗabi'a da ilimi na mataimaki.",
|
||||
"english": "Turanci",
|
||||
"portuguese": "Fotigis",
|
||||
"chinese": "Sinanci",
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara faịlụ nhazi",
|
||||
"temporaryDirectory": "Ndekọ Nwa Oge",
|
||||
"temporaryDirectoryDescription": "Ụzọ sistemu faịlụ maka faịlụ nwa oge",
|
||||
"systemPrompt": "Ajụjụ Sistemu",
|
||||
"systemPromptDescription": "Hazie ajụjụ sistemu nke enyemaka AI site na iji syntax template EJS. Nke a na-achịkwa omume na ihe ọmụma nke enyemaka ahụ.",
|
||||
"english": "Bekee",
|
||||
"portuguese": "Portuguese",
|
||||
"chinese": "Chinese",
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Caminho do sistema de arquivos onde os arquivos de configuração são armazenados",
|
||||
"temporaryDirectory": "Diretório Temporário",
|
||||
"temporaryDirectoryDescription": "Caminho do sistema de arquivos para arquivos temporários",
|
||||
"systemPrompt": "Prompt do Sistema",
|
||||
"systemPromptDescription": "Personalize o prompt do sistema do assistente de IA usando sintaxe de template EJS. Isso controla o comportamento e conhecimento do assistente.",
|
||||
"english": "Inglês",
|
||||
"portuguese": "Português",
|
||||
"chinese": "Chinês",
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Ọna eto faili nibiti a tọju awọn faili iṣeto",
|
||||
"temporaryDirectory": "Itọsọna Igba diẹ",
|
||||
"temporaryDirectoryDescription": "Ọna eto faili fun awọn faili igba diẹ",
|
||||
"systemPrompt": "Ibeere Eto",
|
||||
"systemPromptDescription": "Ṣe adani ibeere eto oluranlọwọ AI nipa lilo sintasi awoṣe EJS. Eyi n ṣakoso ihuwasi ati imọ oluranlọwọ naa.",
|
||||
"english": "Gẹẹsi",
|
||||
"portuguese": "Potogisi",
|
||||
"chinese": "Kannada",
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "存储配置文件的文件系统路径",
|
||||
"temporaryDirectory": "临时目录",
|
||||
"temporaryDirectoryDescription": "临时文件的文件系统路径",
|
||||
"systemPrompt": "系统提示",
|
||||
"systemPromptDescription": "使用EJS模板语法自定义AI助手的系统提示。这控制助手的行为和知识。",
|
||||
"english": "English",
|
||||
"portuguese": "Português",
|
||||
"chinese": "中文",
|
||||
|
||||
@@ -5,12 +5,14 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { useOffline } from "@/hooks/useOffline";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
import { defaultSystemPrompt } from "@/lib/system";
|
||||
|
||||
export function SystemSettings() {
|
||||
const { t } = useTranslation();
|
||||
@@ -31,6 +33,7 @@ export function SystemSettings() {
|
||||
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
||||
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
|
||||
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
|
||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||
|
||||
// Check which settings differ from defaults
|
||||
const isModified = useMemo(() => ({
|
||||
@@ -46,6 +49,7 @@ export function SystemSettings() {
|
||||
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
||||
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
|
||||
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
|
||||
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
|
||||
}), [config, defaultConfig]);
|
||||
|
||||
// Restore functions
|
||||
@@ -120,6 +124,12 @@ export function SystemSettings() {
|
||||
updateConfig((current) => ({ ...current, sentryDsn: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreSystemPrompt = () => {
|
||||
const defaultValue = defaultSystemPrompt;
|
||||
setSystemPromptInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, systemPrompt: defaultValue }));
|
||||
};
|
||||
|
||||
// Service Worker state
|
||||
const [swState, setSwState] = useState<string>('');
|
||||
const [isUpdatingSW, setIsUpdatingSW] = useState(false);
|
||||
@@ -912,6 +922,53 @@ export function SystemSettings() {
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* System Prompt Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="system-prompt" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
|
||||
{isModified.systemPrompt && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<div className="flex gap-2 flex-col">
|
||||
<Textarea
|
||||
id="system-prompt"
|
||||
placeholder="Enter EJS template..."
|
||||
value={systemPromptInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSystemPromptInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
systemPrompt: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1 font-mono text-xs min-h-[400px]"
|
||||
/>
|
||||
{isModified.systemPrompt && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={restoreSystemPrompt}
|
||||
className="w-full"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4 mr-2" />
|
||||
{t('restoreToDefault')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('systemPromptDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user