Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat: implement capability-based filesystem and shell tools with permission management system

Salman Qureshi5572ee1c21a6
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 1a4f65e9..2f00726a 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -4,7 +4,7 @@
## Overview
-Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It communicates via channels (CLI, Telegram, future: Signal, Discord, Slack) and maintains persistent memory.
+Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It is an **orchestrator**, not just a chatbot. It can read/write files, run commands, and perform multi-step agentic workflows — all governed by a strict permission system. It communicates via channels (CLI, Telegram, future: Signal, Discord, Slack) and maintains persistent memory.
## The Human Analogy
@@ -18,7 +18,8 @@ Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It communicat
| Episodic memory | Recent experiences | `src/memory/store.ts` |
| Long-term memory | Life lessons | `src/memory/store.ts` |
| Providers | Senses | `src/providers/` |
-| Skills | Abilities | `src/skills/` |
+| Capabilities | Hands & tools | `src/capabilities/` |
+| Permissions | Boundaries | `src/capabilities/permissions.ts` |
| Channels | Communication | `src/channels/` |
| Heartbeat/scheduler | Circadian rhythm | `src/core/scheduler.ts` |
| Lifecycle | Awake/Sleep/Think | `src/core/lifecycle.ts` |
@@ -27,32 +28,90 @@ Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It communicat
```
src/
-├── index.ts # CLI entry (commander)
-├── channels/ # Communication interfaces
-│ ├── base.ts # Abstract channel
-│ ├── cli.ts # CLI adapter
-│ ├── telegram.ts # Telegram adapter (grammY)
-│ └── registry.ts # Channel manager
-├── core/ # Channel-agnostic brain
-│ ├── agent.ts # Main think→act→respond loop
-│ ├── lifecycle.ts # State machine
-│ └── scheduler.ts # Cron + heartbeat
-├── memory/ # Persistence layer
-│ └── store.ts # Short/long/episodic memory
-├── providers/ # LLM APIs
-│ ├── base.ts # Abstract provider
+├── index.ts # CLI entry (commander)
+├── channels/ # Communication interfaces
+│ ├── base.ts # Abstract channel
+│ ├── cli.ts # CLI adapter (readline + inline permission prompts)
+│ ├── telegram.ts # Telegram adapter (grammY)
+│ └── registry.ts # Channel manager
+├── core/ # Channel-agnostic brain
+│ ├── agent.ts # Multi-step agentic loop (generateText with tools)
+│ ├── lifecycle.ts # State machine
+│ └── scheduler.ts # Cron + heartbeat
+├── capabilities/ # Agentic tools & permissions
+│ ├── permissions.ts # Permission manager (read/write scope, shell blocklist)
+│ ├── registry.ts # Registers all AI SDK tools
+│ ├── filesystem/ # File ops: read, write, create, list, delete
+│ └── shell/ # Shell execution with blocklist
+├── memory/ # Persistence layer
+│ └── store.ts # Short/long/episodic memory
+├── providers/ # LLM APIs
+│ ├── base.ts # Abstract provider + getModelInstance()
│ ├── openai-compat.ts
│ ├── anthropic.ts
│ └── registry.ts
-├── soul/ # Consciousness
-│ └── identity.ts # Soul/persona/taste loader
-├── skills/ # Modular abilities
+├── soul/ # Consciousness
+│ └── identity.ts # Soul/persona/taste loader + guardrails
+├── skills/ # Modular abilities
│ ├── types.ts
│ └── loader.ts
-├── types/ # Type definitions
-└── utils/ # Config, logger, tokens
+├── types/ # Type definitions
+└── utils/ # Config, logger, tokens
```
+## Agentic Loop
+
+Mercury uses the Vercel AI SDK's multi-step `generateText()` with tools:
+
+```
+User message → Agent loads system prompt (soul + guardrails + persona)
+ → Agent calls generateText({ tools, maxSteps: 10 })
+ → LLM decides: respond with text OR call a tool
+ → If tool called:
+ → Permission check (filesystem scope / shell blocklist)
+ → If allowed: execute tool, return result to LLM
+ → If denied: LLM gets denial message, adjusts approach
+ → LLM continues (next step) — may call more tools or respond
+ → If text: final response returned to user
+ → Agent sends final response via channel
+```
+
+## Permission System
+
+### Filesystem Permissions (folder-level scoping)
+
+- Paths without scope = **no access**, must ask user
+- User can grant: `y` (one-time), `always` (saves to manifest), `n` (deny)
+- Manifest stored at `~/.mercury/permissions.yaml`
+- Edit anytime — Mercury never bypasses
+
+### Shell Permissions
+
+- **Blocked** (never executed): `sudo *`, `rm -rf /`, `mkfs`, `dd if=`, fork bombs, `shutdown`, `reboot`
+- **Auto-approved** (no prompt): `ls`, `cat`, `pwd`, `git status/diff/log`, `node`, `npm run/test`
+- **Needs approval**: `npm publish`, `git push`, `docker`, `rm -r`, `chmod`, piped `curl | sh`
+- Commands restricted to CWD + approved folder scopes
+
+### Inline Permission UX
+
+When Mercury needs a scope it doesn't have:
+```
+ ⚠ Mercury needs write access to ~/projects/myapp. Allow? (y/n/always):
+ > always
+ [Scope saved to ~/.mercury/permissions.yaml]
+```
+
+## Tools
+
+| Tool | Description | Permission Check |
+|---|---|---|
+| `read_file` | Read file contents | Read scope for path |
+| `write_file` | Write to existing file | Write scope for path |
+| `create_file` | Create new file + dirs | Write scope for parent dir |
+| `list_dir` | List directory contents | Read scope for path |
+| `delete_file` | Delete a file | Write scope, always confirms |
+| `run_command` | Execute shell command | Blocklist + approval list + scope |
+
## Agent Lifecycle
```
@@ -61,9 +120,21 @@ unborn → birthing → onboarding → idle ⇄ thinking → responding → idle
idle → sleeping → awakening → idle
```
+## Runtime Data Location
+
+All runtime data lives in `~/.mercury/` (not the project directory):
+
+| What | Where |
+|---|---|
+| Config | `~/.mercury/mercury.yaml` |
+| Soul files | `~/.mercury/soul/*.md` |
+| Memory | `~/.mercury/memory/` |
+| Skills | `~/.mercury/skills/` |
+| Permissions | `~/.mercury/permissions.yaml` |
+
## Token Budget
-- System prompt (soul + persona): ~350 tokens per request
+- System prompt (soul + guardrails + persona): ~500 tokens per request
- Short-term context: last 10 messages
- Long-term facts: keyword-matched, ~3 facts injected
- Daily default: 50,000 tokens
@@ -71,17 +142,11 @@ unborn → birthing → onboarding → idle ⇄ thinking → responding → idle
## Channels
### CLI
-- Ink-based TUI (Phase 2 — current CLI uses readline)
-- `mercury start —mode cli`
+- Readline-based with inline permission prompts
+- `mercury start` or just `mercury`
### Telegram
- grammY framework + @grammyjs/stream for streaming
- Typing indicator while processing
- Proactive messages via heartbeat
-- `TELEGRAM_BOT_TOKEN` in .env or mercury.yaml
-
-## Configuration
-
-- `.env` — API keys, tokens (gitignored)
-- `config/mercury.yaml` — persistent config (saved by setup wizard)
-- `soul/*.md` — personality markdowns (editable anytime)
\ No newline at end of file
+- `TELEGRAM_BOT_TOKEN` in .env or mercury.yaml
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 13c557bc..200b8731 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -23,7 +23,8 @@
"node-cron": "^3.0.3",
"pino": "^9.6.0",
"react": "^18.3.1",
- "yaml": "^2.7.0"
+ "yaml": "^2.7.0",
+ "zod": "^3.25.76"
},
"bin": {
"mercury": "dist/index.js"
@@ -3418,7 +3419,6 @@
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
- "peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -5415,8 +5415,7 @@
"zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
- "peer": true
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="
},
"zod-to-json-schema": {
"version": "3.25.2",
diff --git a/package.json b/package.json
index 766a987c..26b1adfe 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,8 @@
"node-cron": "^3.0.3",
"pino": "^9.6.0",
"react": "^18.3.1",
- "yaml": "^2.7.0"
+ "yaml": "^2.7.0",
+ "zod": "^3.25.76"
},
"devDependencies": {
"@types/node": "^22.13.0",
@@ -52,4 +53,4 @@
"engines": {
"node": ">=20.0.0"
}
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/filesystem/create-file.ts b/src/capabilities/filesystem/create-file.ts
new file mode 100644
index 00000000..b869b824
--- /dev/null
+++ b/src/capabilities/filesystem/create-file.ts
@@ -0,0 +1,37 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { existsSync, writeFileSync, mkdirSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+export function createCreateFileTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Create a new file with the given content. Also creates parent directories if needed. The path must be within a writable scope.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path for the new file'),
+ content: z.string().describe('The content of the new file'),
+ }),
+ execute: async ({ path, content }) => {
+ const resolved = resolve(path);
+ const check = await permissions.checkFsAccess(resolved, 'write');
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ if (existsSync(resolved)) {
+ return `Error: File already exists: ${resolved}. Use write_file to modify existing files.`;
+ }
+
+ try {
+ const dir = dirname(resolved);
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true });
+ }
+ writeFileSync(resolved, content, 'utf-8');
+ return `Successfully created ${resolved} (${content.length} bytes)`;
+ } catch (err: any) {
+ return `Error creating file: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/filesystem/delete-file.ts b/src/capabilities/filesystem/delete-file.ts
new file mode 100644
index 00000000..86aa97a4
--- /dev/null
+++ b/src/capabilities/filesystem/delete-file.ts
@@ -0,0 +1,36 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { existsSync, unlinkSync } from 'node:fs';
+import { resolve } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+export function createDeleteFileTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Delete a file. This action cannot be undone. The path must be within a writable scope. Always asks for confirmation.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path to the file to delete'),
+ }),
+ execute: async ({ path }) => {
+ const resolved = resolve(path);
+ const check = await permissions.checkFsAccess(resolved, 'write');
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ if (!existsSync(resolved)) {
+ return `Error: File not found: ${resolved}`;
+ }
+
+ try {
+ const stat = await import('node:fs').then(m => m.statSync(resolved));
+ if (stat.isDirectory()) {
+ return `Error: ${resolved} is a directory. Cannot delete directories for safety.`;
+ }
+ unlinkSync(resolved);
+ return `Successfully deleted ${resolved}`;
+ } catch (err: any) {
+ return `Error deleting file: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/filesystem/index.ts b/src/capabilities/filesystem/index.ts
new file mode 100644
index 00000000..8c7210d1
--- /dev/null
+++ b/src/capabilities/filesystem/index.ts
@@ -0,0 +1,5 @@
+export { createReadFileTool } from './read-file.js';
+export { createWriteFileTool } from './write-file.js';
+export { createCreateFileTool } from './create-file.js';
+export { createListDirTool } from './list-dir.js';
+export { createDeleteFileTool } from './delete-file.js';
\ No newline at end of file
diff --git a/src/capabilities/filesystem/list-dir.ts b/src/capabilities/filesystem/list-dir.ts
new file mode 100644
index 00000000..a023613d
--- /dev/null
+++ b/src/capabilities/filesystem/list-dir.ts
@@ -0,0 +1,63 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { existsSync, readdirSync, statSync } from 'node:fs';
+import { resolve } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+export function createListDirTool(permissions: PermissionManager) {
+ return tool({
+ description: 'List the contents of a directory. Shows file names, types, and sizes.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path to the directory'),
+ }),
+ execute: async ({ path }) => {
+ const resolved = resolve(path);
+ const check = await permissions.checkFsAccess(resolved, 'read');
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ if (!existsSync(resolved)) {
+ return `Error: Directory not found: ${resolved}`;
+ }
+
+ try {
+ const stat = statSync(resolved);
+ if (!stat.isDirectory()) {
+ return `Error: ${resolved} is a file, not a directory. Use read_file instead.`;
+ }
+
+ const entries = readdirSync(resolved, { withFileTypes: true });
+ const lines = entries.map(entry => {
+ const isDir = entry.isDirectory();
+ const fullPath = join(resolved, entry.name);
+ let size = '';
+ try {
+ if (!isDir) {
+ size = ` (${formatSize(statSync(fullPath).size)})`;
+ }
+ } catch {}
+ return `${isDir ? '📁' : '📄'} ${entry.name}${size}`;
+ });
+
+ if (lines.length === 0) {
+ return `Directory ${resolved} is empty`;
+ }
+
+ return `Contents of ${resolved} (${entries.length} items):\n${lines.join('\n')}`;
+ } catch (err: any) {
+ return `Error listing directory: ${err.message}`;
+ }
+ },
+ });
+}
+
+function join(base: string, name: string): string {
+ return base.endsWith('/') ? base + name : base + '/' + name;
+}
+
+function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes}B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
+}
\ No newline at end of file
diff --git a/src/capabilities/filesystem/read-file.ts b/src/capabilities/filesystem/read-file.ts
new file mode 100644
index 00000000..d95c466f
--- /dev/null
+++ b/src/capabilities/filesystem/read-file.ts
@@ -0,0 +1,38 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+export function createReadFileTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Read the contents of a file. The path must be within an allowed scope.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path to the file'),
+ }),
+ execute: async ({ path }) => {
+ const resolved = resolve(path);
+ const check = await permissions.checkFsAccess(resolved, 'read');
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ if (!existsSync(resolved)) {
+ return `Error: File not found: ${resolved}`;
+ }
+
+ try {
+ const stat = await import('node:fs').then(m => m.statSync(resolved));
+ if (stat.isDirectory()) {
+ return `Error: ${resolved} is a directory, not a file. Use list_dir instead.`;
+ }
+ if (stat.size > 1024 * 1024) {
+ return `Error: File too large (${Math.round(stat.size / 1024)}KB). Maximum is 1MB.`;
+ }
+ return readFileSync(resolved, 'utf-8');
+ } catch (err: any) {
+ return `Error reading file: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/filesystem/write-file.ts b/src/capabilities/filesystem/write-file.ts
new file mode 100644
index 00000000..c5e1d952
--- /dev/null
+++ b/src/capabilities/filesystem/write-file.ts
@@ -0,0 +1,34 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { existsSync, writeFileSync, readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { mkdirSync } from 'node:fs';
+import type { PermissionManager } from '../permissions.js';
+
+export function createWriteFileTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Write content to an existing file. The path must be within a writable scope.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path to the file'),
+ content: z.string().describe('The content to write to the file'),
+ }),
+ execute: async ({ path, content }) => {
+ const resolved = resolve(path);
+ const check = await permissions.checkFsAccess(resolved, 'write');
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ if (!existsSync(resolved)) {
+ return `Error: File not found: ${resolved}. Use create_file to create new files.`;
+ }
+
+ try {
+ writeFileSync(resolved, content, 'utf-8');
+ return `Successfully wrote ${content.length} bytes to ${resolved}`;
+ } catch (err: any) {
+ return `Error writing file: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/index.ts b/src/capabilities/index.ts
new file mode 100644
index 00000000..0f15cd44
--- /dev/null
+++ b/src/capabilities/index.ts
@@ -0,0 +1,10 @@
+export { PermissionManager } from './permissions.js';
+export type { PermissionsManifest, FileScope, ShellPermissions, FsPermissions, GitPermissions } from './permissions.js';
+export { CapabilityRegistry } from './registry.js';
+export { createReadFileTool } from './filesystem/read-file.js';
+export { createWriteFileTool } from './filesystem/write-file.js';
+export { createCreateFileTool } from './filesystem/create-file.js';
+export { createListDirTool } from './filesystem/list-dir.js';
+export { createDeleteFileTool } from './filesystem/delete-file.js';
+export { createRunCommandTool } from './shell/run-command.js';
+export { BLOCKED_COMMANDS, AUTO_APPROVED_COMMANDS, NEEDS_APPROVAL_COMMANDS } from './shell/blocklist.js';
\ No newline at end of file
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
new file mode 100644
index 00000000..77dbb9d0
--- /dev/null
+++ b/src/capabilities/permissions.ts
@@ -0,0 +1,329 @@
+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { homedir } from 'node:os';
+import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+
+export interface FileScope {
+ path: string;
+ read: boolean;
+ write: boolean;
+}
+
+export interface ShellPermissions {
+ enabled: boolean;
+ blocked: string[];
+ autoApproved: string[];
+ needsApproval: string[];
+ cwdOnly: boolean;
+}
+
+export interface FsPermissions {
+ enabled: boolean;
+ scopes: FileScope[];
+}
+
+export interface GitPermissions {
+ enabled: boolean;
+ autoApproveRead: boolean;
+ approveWrite: boolean;
+}
+
+export interface PermissionsManifest {
+ capabilities: {
+ filesystem: FsPermissions;
+ shell: ShellPermissions;
+ git: GitPermissions;
+ };
+}
+
+const DEFAULT_MANIFEST: PermissionsManifest = {
+ capabilities: {
+ filesystem: {
+ enabled: true,
+ scopes: [
+ { path: '.', read: true, write: true },
+ ],
+ },
+ shell: {
+ enabled: true,
+ blocked: [
+ 'sudo *',
+ 'rm -rf /',
+ 'rm -rf ~',
+ 'rm -rf /*',
+ 'mkfs *',
+ 'dd if=*',
+ 'chmod 777 /',
+ 'chown * /',
+ ':(){ :|:& };:',
+ 'shutdown *',
+ 'reboot *',
+ 'halt *',
+ 'init 0',
+ 'init 6',
+ 'kill -9 1',
+ '> /dev/sda',
+ 'mv /* /dev/null',
+ ],
+ autoApproved: [
+ 'ls *',
+ 'cat *',
+ 'pwd',
+ 'which *',
+ 'node *',
+ 'npm run *',
+ 'npm test *',
+ 'npm list *',
+ 'git status *',
+ 'git diff *',
+ 'git log *',
+ 'git branch *',
+ 'echo *',
+ 'head *',
+ 'tail *',
+ 'wc *',
+ 'find *',
+ 'grep *',
+ 'rg *',
+ 'ps *',
+ 'df *',
+ 'du *',
+ 'uname *',
+ ],
+ needsApproval: [
+ 'npm publish *',
+ 'git push *',
+ 'docker *',
+ 'curl * | sh',
+ 'curl * | bash',
+ 'wget * | sh',
+ 'pip install *',
+ 'pip3 install *',
+ 'rm -r *',
+ 'rm -rf *',
+ 'mv *',
+ 'cp -r *',
+ 'chmod *',
+ 'mkdir *',
+ 'rmdir *',
+ ],
+ cwdOnly: true,
+ },
+ git: {
+ enabled: true,
+ autoApproveRead: true,
+ approveWrite: true,
+ },
+ },
+};
+
+const PERMISSIONS_FILE = join(getMercuryHome(), 'permissions.yaml');
+
+export class PermissionManager {
+ private manifest: PermissionsManifest;
+ private readonly cwd: string;
+ private askHandler?: (prompt: string) => Promise<string>;
+
+ constructor() {
+ this.cwd = process.cwd();
+ this.manifest = this.load();
+ }
+
+ onAsk(handler: (prompt: string) => Promise<string>): void {
+ this.askHandler = handler;
+ }
+
+ private load(): PermissionsManifest {
+ if (existsSync(PERMISSIONS_FILE)) {
+ try {
+ const raw = readFileSync(PERMISSIONS_FILE, 'utf-8');
+ const parsed = parseYaml(raw) as PermissionsManifest;
+ return this.mergeDefaults(parsed);
+ } catch (err) {
+ logger.warn({ err }, 'Failed to parse permissions.yaml, using defaults');
+ return { ...DEFAULT_MANIFEST };
+ }
+ }
+ this.save(DEFAULT_MANIFEST);
+ return { ...DEFAULT_MANIFEST };
+ }
+
+ save(manifest?: PermissionsManifest): void {
+ const m = manifest || this.manifest;
+ const dir = getMercuryHome();
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+ writeFileSync(PERMISSIONS_FILE, stringifyYaml(m, { lineWidth: 0 }), 'utf-8');
+ this.manifest = m;
+ }
+
+ getManifest(): PermissionsManifest {
+ return this.manifest;
+ }
+
+ async checkFsAccess(path: string, mode: 'read' | 'write'): Promise<{ allowed: boolean; reason?: string }> {
+ const fs = this.manifest.capabilities.filesystem;
+ if (!fs.enabled) {
+ return { allowed: false, reason: 'Filesystem capability is disabled' };
+ }
+
+ const resolved = resolve(path);
+ const scope = this.findScope(resolved);
+
+ if (scope) {
+ if (mode === 'read' && scope.read) return { allowed: true };
+ if (mode === 'write' && scope.write) return { allowed: true };
+ return { allowed: false, reason: `Permission denied: ${mode} access to ${path} (scope has ${mode}=false)` };
+ }
+
+ return await this.requestScope(resolved, mode);
+ }
+
+ async checkShellCommand(command: string): Promise<{ allowed: boolean; reason?: string; needsApproval: boolean }> {
+ const shell = this.manifest.capabilities.shell;
+ if (!shell.enabled) {
+ return { allowed: false, reason: 'Shell capability is disabled', needsApproval: false };
+ }
+
+ const trimmed = command.trim();
+
+ for (const pattern of shell.blocked) {
+ if (this.matchPattern(trimmed, pattern)) {
+ return { allowed: false, reason: `Blocked command: matches "${pattern}"`, needsApproval: false };
+ }
+ }
+
+ if (shell.cwdOnly) {
+ const hasPathTraversal = this.hasPathBeyondCwd(trimmed);
+ if (hasPathTraversal) {
+ const scopeCheck = await this.checkFsAccess(hasPathTraversal, 'write');
+ if (!scopeCheck.allowed) {
+ return { allowed: false, reason: scopeCheck.reason, needsApproval: true };
+ }
+ }
+ }
+
+ for (const pattern of shell.autoApproved) {
+ if (this.matchPattern(trimmed, pattern)) {
+ logger.info({ cmd: trimmed }, 'Shell command auto-approved');
+ return { allowed: true, needsApproval: false };
+ }
+ }
+
+ for (const pattern of shell.needsApproval) {
+ if (this.matchPattern(trimmed, pattern)) {
+ return { allowed: false, reason: `Command requires approval: matches "${pattern}"`, needsApproval: true };
+ }
+ }
+
+ return { allowed: false, reason: 'Command not in auto-approve list — requires approval', needsApproval: true };
+ }
+
+ isGitReadAllowed(): boolean {
+ return this.manifest.capabilities.git.enabled && this.manifest.capabilities.git.autoApproveRead;
+ }
+
+ isGitWriteNeedsApproval(): boolean {
+ return this.manifest.capabilities.git.enabled && this.manifest.capabilities.git.approveWrite;
+ }
+
+ addScope(path: string, read: boolean, write: boolean): void {
+ const resolved = resolve(path);
+ const existing = this.findScope(resolved);
+ if (existing) {
+ existing.read = existing.read || read;
+ existing.write = existing.write || write;
+ } else {
+ this.manifest.capabilities.filesystem.scopes.push({
+ path: resolved,
+ read,
+ write,
+ });
+ }
+ this.save();
+ logger.info({ path: resolved, read, write }, 'Permission scope added');
+ }
+
+ private findScope(resolvedPath: string): FileScope | undefined {
+ const scopes = this.manifest.capabilities.filesystem.scopes;
+ for (const scope of scopes) {
+ const scopeResolved = resolve(scope.path.replace(/^~/, homedir()));
+ if (resolvedPath === scopeResolved || resolvedPath.startsWith(scopeResolved + '/')) {
+ return scope;
+ }
+ }
+ return undefined;
+ }
+
+ private async requestScope(path: string, mode: 'read' | 'write'): Promise<{ allowed: boolean; reason?: string }> {
+ if (!this.askHandler) {
+ return { allowed: false, reason: `No permission to ${mode} ${path}. Add scope to ~/.mercury/permissions.yaml` };
+ }
+
+ const response = await this.askHandler(
+ `Mercury needs ${mode} access to ${path}. Allow? (y/n/always): `
+ );
+
+ if (response.toLowerCase() === 'always') {
+ this.addScope(path, mode === 'read', mode === 'write');
+ return { allowed: true };
+ }
+
+ if (response.toLowerCase() === 'y' || response.toLowerCase() === 'yes') {
+ return { allowed: true };
+ }
+
+ return { allowed: false, reason: `Permission denied for ${mode} access to ${path}` };
+ }
+
+ private matchPattern(command: string, pattern: string): boolean {
+ const regexStr = '^' + pattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$';
+ try {
+ return new RegExp(regexStr, 'i').test(command);
+ } catch {
+ return command.startsWith(pattern.replace(/ \*$/, ''));
+ }
+ }
+
+ private hasPathBeyondCwd(command: string): string | null {
+ const pathPatterns = [
+ /(?:^|\s)(\/[^\s]+)/,
+ /(?:^|\s)(~\/[^\s]+)/,
+ /(?:^|\s)\.\.\/([^\s]+)/,
+ ];
+ for (const p of pathPatterns) {
+ const match = command.match(p);
+ if (match) {
+ const candidate = resolve(match[1].replace(/^~/, homedir()));
+ if (!candidate.startsWith(this.cwd)) {
+ return candidate;
+ }
+ }
+ }
+ return null;
+ }
+
+ private mergeDefaults(parsed: Partial<PermissionsManifest>): PermissionsManifest {
+ return {
+ capabilities: {
+ filesystem: {
+ enabled: parsed.capabilities?.filesystem?.enabled ?? DEFAULT_MANIFEST.capabilities.filesystem.enabled,
+ scopes: parsed.capabilities?.filesystem?.scopes ?? DEFAULT_MANIFEST.capabilities.filesystem.scopes,
+ },
+ shell: {
+ enabled: parsed.capabilities?.shell?.enabled ?? DEFAULT_MANIFEST.capabilities.shell.enabled,
+ blocked: parsed.capabilities?.shell?.blocked ?? DEFAULT_MANIFEST.capabilities.shell.blocked,
+ autoApproved: parsed.capabilities?.shell?.autoApproved ?? DEFAULT_MANIFEST.capabilities.shell.autoApproved,
+ needsApproval: parsed.capabilities?.shell?.needsApproval ?? DEFAULT_MANIFEST.capabilities.shell.needsApproval,
+ cwdOnly: parsed.capabilities?.shell?.cwdOnly ?? DEFAULT_MANIFEST.capabilities.shell.cwdOnly,
+ },
+ git: {
+ enabled: parsed.capabilities?.git?.enabled ?? DEFAULT_MANIFEST.capabilities.git.enabled,
+ autoApproveRead: parsed.capabilities?.git?.autoApproveRead ?? DEFAULT_MANIFEST.capabilities.git.autoApproveRead,
+ approveWrite: parsed.capabilities?.git?.approveWrite ?? DEFAULT_MANIFEST.capabilities.git.approveWrite,
+ },
+ },
+ };
+ }
+}
\ No newline at end of file
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
new file mode 100644
index 00000000..b331fe97
--- /dev/null
+++ b/src/capabilities/registry.ts
@@ -0,0 +1,45 @@
+import type { Tool } from 'ai';
+import { PermissionManager } from './permissions.js';
+import { createReadFileTool } from './filesystem/read-file.js';
+import { createWriteFileTool } from './filesystem/write-file.js';
+import { createCreateFileTool } from './filesystem/create-file.js';
+import { createListDirTool } from './filesystem/list-dir.js';
+import { createDeleteFileTool } from './filesystem/delete-file.js';
+import { createRunCommandTool } from './shell/run-command.js';
+import { logger } from '../utils/logger.js';
+
+export class CapabilityRegistry {
+ readonly permissions: PermissionManager;
+ private tools: Record<string, Tool> = {};
+
+ constructor() {
+ this.permissions = new PermissionManager();
+ this.registerAll();
+ }
+
+ private registerAll(): void {
+ const manifest = this.permissions.getManifest();
+
+ if (manifest.capabilities.filesystem.enabled) {
+ this.tools.read_file = createReadFileTool(this.permissions);
+ this.tools.write_file = createWriteFileTool(this.permissions);
+ this.tools.create_file = createCreateFileTool(this.permissions);
+ this.tools.list_dir = createListDirTool(this.permissions);
+ this.tools.delete_file = createDeleteFileTool(this.permissions);
+ logger.info('Filesystem tools registered');
+ }
+
+ if (manifest.capabilities.shell.enabled) {
+ this.tools.run_command = createRunCommandTool(this.permissions);
+ logger.info('Shell tool registered');
+ }
+ }
+
+ getTools(): Record<string, Tool> {
+ return this.tools;
+ }
+
+ getToolNames(): string[] {
+ return Object.keys(this.tools);
+ }
+}
\ No newline at end of file
diff --git a/src/capabilities/shell/blocklist.ts b/src/capabilities/shell/blocklist.ts
new file mode 100644
index 00000000..41aa53f8
--- /dev/null
+++ b/src/capabilities/shell/blocklist.ts
@@ -0,0 +1,63 @@
+export const BLOCKED_COMMANDS = [
+ 'sudo *',
+ 'rm -rf /',
+ 'rm -rf ~',
+ 'rm -rf /*',
+ 'mkfs *',
+ 'dd if=*',
+ 'chmod 777 /',
+ 'chown * /',
+ ':(){ :|:& };:',
+ 'shutdown *',
+ 'reboot *',
+ 'halt *',
+ 'init 0',
+ 'init 6',
+ 'kill -9 1',
+ '> /dev/sda',
+ 'mv /* /dev/null',
+];
+
+export const AUTO_APPROVED_COMMANDS = [
+ 'ls *',
+ 'cat *',
+ 'pwd',
+ 'which *',
+ 'node *',
+ 'npm run *',
+ 'npm test *',
+ 'npm list *',
+ 'git status *',
+ 'git diff *',
+ 'git log *',
+ 'git branch *',
+ 'echo *',
+ 'head *',
+ 'tail *',
+ 'wc *',
+ 'find *',
+ 'grep *',
+ 'rg *',
+ 'ps *',
+ 'df *',
+ 'du *',
+ 'uname *',
+];
+
+export const NEEDS_APPROVAL_COMMANDS = [
+ 'npm publish *',
+ 'git push *',
+ 'docker *',
+ 'curl * | sh',
+ 'curl * | bash',
+ 'wget * | sh',
+ 'pip install *',
+ 'pip3 install *',
+ 'rm -r *',
+ 'rm -rf *',
+ 'mv *',
+ 'cp -r *',
+ 'chmod *',
+ 'mkdir *',
+ 'rmdir *',
+];
\ No newline at end of file
diff --git a/src/capabilities/shell/index.ts b/src/capabilities/shell/index.ts
new file mode 100644
index 00000000..0170dcbf
--- /dev/null
+++ b/src/capabilities/shell/index.ts
@@ -0,0 +1,2 @@
+export { createRunCommandTool } from './run-command.js';
+export { BLOCKED_COMMANDS, AUTO_APPROVED_COMMANDS, NEEDS_APPROVAL_COMMANDS } from './blocklist.js';
\ No newline at end of file
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
new file mode 100644
index 00000000..be5e328e
--- /dev/null
+++ b/src/capabilities/shell/run-command.ts
@@ -0,0 +1,64 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+import { resolve } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+import { logger } from '../../utils/logger.js';
+
+export function createRunCommandTool(permissions: PermissionManager) {
+ return tool({
+ description: `Run a shell command. Commands run in the current working directory unless an absolute path is given.
+Blocked commands (sudo, rm -rf /, etc.) are never executed.
+Auto-approved commands (ls, cat, git status, etc.) run without asking.
+Other commands require user approval.`,
+ parameters: z.object({
+ command: z.string().describe('The shell command to execute'),
+ }),
+ execute: async ({ command }) => {
+ const check = await permissions.checkShellCommand(command);
+ if (!check.allowed) {
+ if (check.needsApproval) {
+ const response = await askApproval(command, permissions);
+ if (!response) {
+ return `Command "${command}" was not approved by user.`;
+ }
+ } else {
+ return `Error: ${check.reason}`;
+ }
+ }
+
+ try {
+ logger.info({ cmd: command }, 'Executing shell command');
+ const result = execSync(command, {
+ cwd: process.cwd(),
+ timeout: 30000,
+ maxBuffer: 1024 * 1024,
+ encoding: 'utf-8',
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ const output = result?.trim() || '(no output)';
+ return output;
+ } catch (err: any) {
+ const stderr = err.stderr?.trim();
+ const stdout = err.stdout?.trim();
+ let msg = `Command exited with code ${err.status || 'unknown'}`;
+ if (stdout) msg += `\nOutput: ${stdout}`;
+ if (stderr) msg += `\nError: ${stderr}`;
+ return msg;
+ }
+ },
+ });
+}
+
+async function askApproval(command: string, permissions: PermissionManager): Promise<boolean> {
+ const handler = (permissions as any).askHandler;
+ if (!handler) {
+ return false;
+ }
+
+ const response = await handler(
+ `Mercury wants to run: ${command}\nAllow? (y/n): `
+ );
+
+ return response.toLowerCase() === 'y' || response.toLowerCase() === 'yes';
+}
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index add3f842..0e0136b7 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -79,4 +79,14 @@ export class CLIChannel extends BaseChannel {
this.rl?.question(question, (answer) => resolve(answer.trim()));
});
}
+
+ async askPermission(prompt: string): Promise<string> {
+ return new Promise((resolve) => {
+ console.log('');
+ console.log(chalk.yellow(` ⚠ ${prompt}`));
+ this.rl?.question(chalk.yellow(' > '), (answer) => {
+ resolve(answer.trim());
+ });
+ });
+ }
}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index b52363fd..afe46899 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1,3 +1,4 @@
+import { generateText } from 'ai';
import type { ChannelMessage } from '../types/channel.js';
import type { ProviderRegistry } from '../providers/registry.js';
import type { Identity } from '../soul/identity.js';
@@ -5,13 +6,17 @@ import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/
import type { ChannelRegistry } from '../channels/registry.js';
import type { MercuryConfig } from '../utils/config.js';
import type { TokenBudget } from '../utils/tokens.js';
+import type { CapabilityRegistry } from '../capabilities/registry.js';
import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
import { logger } from '../utils/logger.js';
+const MAX_STEPS = 10;
+
export class Agent {
readonly lifecycle: Lifecycle;
readonly scheduler: Scheduler;
+ readonly capabilities: CapabilityRegistry;
private running = false;
private messageQueue: ChannelMessage[] = [];
private processing = false;
@@ -25,9 +30,11 @@ export class Agent {
private episodic: EpisodicMemory,
private channels: ChannelRegistry,
private tokenBudget: TokenBudget,
+ capabilities: CapabilityRegistry,
) {
this.lifecycle = new Lifecycle();
this.scheduler = new Scheduler(config);
+ this.capabilities = capabilities;
this.channels.onIncomingMessage((msg) => this.enqueueMessage(msg));
@@ -75,7 +82,8 @@ export class Agent {
this.running = true;
const activeChannels = this.channels.getActiveChannels();
- logger.info({ channels: activeChannels }, 'Mercury is awake');
+ const toolNames = this.capabilities.getToolNames();
+ logger.info({ channels: activeChannels, tools: toolNames }, 'Mercury is awake');
}
async sleep(): Promise<void> {
@@ -95,17 +103,26 @@ export class Agent {
const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);
const relevantFacts = this.longTerm.search(msg.content, 3);
- let contextPrompt = '';
+ const messages: any[] = [];
+
if (relevantFacts.length > 0) {
- contextPrompt += '\nRelevant facts:\n' + relevantFacts.map(f => `- ${f.fact}`).join('\n');
+ messages.push({
+ role: 'user',
+ content: 'Relevant facts from memory:\n' + relevantFacts.map(f => `- ${f.fact}`).join('\n'),
+ });
+ messages.push({ role: 'assistant', content: 'Noted. I\'ll use these facts.' });
}
+
if (recentMemory.length > 0) {
- contextPrompt += '\nRecent conversation:\n' + recentMemory
- .map(m => `${m.role}: ${m.content}`)
- .join('\n');
+ for (const m of recentMemory) {
+ messages.push({
+ role: m.role === 'user' ? 'user' : 'assistant',
+ content: m.content,
+ });
+ }
}
- const fullPrompt = contextPrompt + '\n\nUser: ' + msg.content;
+ messages.push({ role: 'user', content: msg.content });
this.lifecycle.transition('responding');
@@ -114,16 +131,33 @@ export class Agent {
await channel.typing(msg.channelId).catch(() => {});
}
- logger.info({ provider: provider.name, model: provider.getModel() }, 'Generating response');
- const response = await provider.generateText(fullPrompt, systemPrompt);
- logger.info({ tokens: response.totalTokens }, 'Response generated');
+ logger.info({ provider: provider.name, model: provider.getModel(), steps: MAX_STEPS }, 'Generating agentic response');
+
+ const result = await generateText({
+ model: provider.getModelInstance(),
+ system: systemPrompt,
+ messages,
+ tools: this.capabilities.getTools(),
+ maxSteps: MAX_STEPS,
+ onStepFinish: async ({ toolCalls, text }) => {
+ if (toolCalls && toolCalls.length > 0) {
+ const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
+ logger.info({ tools: names }, 'Tool call step');
+ if (channel) {
+ await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
+ }
+ }
+ },
+ });
+
+ const finalText = result.text;
this.tokenBudget.recordUsage({
- provider: response.provider,
- model: response.model,
- inputTokens: response.inputTokens,
- outputTokens: response.outputTokens,
- totalTokens: response.totalTokens,
+ provider: provider.name,
+ model: provider.getModel(),
+ inputTokens: result.usage?.promptTokens ?? 0,
+ outputTokens: result.usage?.completionTokens ?? 0,
+ totalTokens: (result.usage?.promptTokens ?? 0) + (result.usage?.completionTokens ?? 0),
channelType: msg.channelType,
});
@@ -138,19 +172,19 @@ export class Agent {
id: Date.now().toString(36),
timestamp: Date.now(),
role: 'assistant',
- content: response.text,
- tokenCount: response.totalTokens,
+ content: finalText,
+ tokenCount: (result.usage?.promptTokens ?? 0) + (result.usage?.completionTokens ?? 0),
});
this.episodic.record({
type: 'message',
- summary: `User: ${msg.content.slice(0, 100)} | Agent: ${response.text.slice(0, 100)}`,
+ summary: `User: ${msg.content.slice(0, 100)} | Agent: ${finalText.slice(0, 100)}`,
channelType: msg.channelType,
});
if (channel) {
logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');
- await channel.send(response.text, msg.channelId);
+ await channel.send(finalText, msg.channelId);
} else {
logger.warn({ channelType: msg.channelType }, 'No channel found for response');
}
diff --git a/src/index.ts b/src/index.ts
index 2b3d85d9..a73a9561 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -10,7 +10,7 @@ import { Agent } from './core/agent.js';
import { ChannelRegistry } from './channels/registry.js';
import { CLIChannel } from './channels/cli.js';
import { TokenBudget } from './utils/tokens.js';
-import { SkillLoader } from './skills/loader.js';
+import { CapabilityRegistry } from './capabilities/registry.js';
function hr() {
console.log(chalk.dim('─'.repeat(50)));
@@ -94,8 +94,9 @@ async function onboarding(): Promise<void> {
const home = getMercuryHome();
console.log('');
console.log(chalk.green(` ✓ Config saved to ${home}/mercury.yaml`));
- console.log(chalk.green(` ✓ Soul files will be seeded in ${home}/soul/`));
+ console.log(chalk.green(` ✓ Soul files seeded in ${home}/soul/`));
console.log(chalk.green(` ✓ Memory stored in ${home}/memory/`));
+ console.log(chalk.green(` ✓ Permissions seeded in ${home}/permissions.yaml`));
console.log('');
console.log(chalk.cyan(` ${config.identity.name} is ready. Run \`mercury start\` to begin.`));
console.log('');
@@ -120,20 +121,19 @@ async function runAgent(): Promise<void> {
const available = providers.listAvailable();
console.log(chalk.dim(` Providers: ${available.join(', ')}`));
+ const capabilities = new CapabilityRegistry();
+ const toolNames = capabilities.getToolNames();
+ console.log(chalk.dim(` Tools: ${toolNames.join(', ')}`));
+
const identity = new Identity();
const shortTerm = new ShortTermMemory(config);
const longTerm = new LongTermMemory(config);
const episodic = new EpisodicMemory(config);
- const skillLoader = new SkillLoader();
- const skills = skillLoader.discover();
- if (skills.length > 0) {
- console.log(chalk.dim(` Skills: ${skills.map(s => s.name).join(', ')}`));
- }
const channels = new ChannelRegistry(config);
const agent = new Agent(
- config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget,
+ config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget, capabilities,
);
await agent.birth();
@@ -141,8 +141,15 @@ async function runAgent(): Promise<void> {
const cliChannel = channels.get('cli') as CLIChannel | undefined;
+ if (cliChannel) {
+ capabilities.permissions.onAsk(async (prompt: string) => {
+ return cliChannel.askPermission(prompt);
+ });
+ }
+
const activeCh = channels.getActiveChannels();
console.log(chalk.dim(` Channels: ${activeCh.join(', ')}`));
+ console.log(chalk.dim(` Permissions: ${getMercuryHome()}/permissions.yaml`));
hr();
console.log('');
console.log(chalk.green(` ${name} is live. Type a message and press Enter.`));
diff --git a/src/providers/anthropic.ts b/src/providers/anthropic.ts
index 7d6964b7..4c1503da 100644
--- a/src/providers/anthropic.ts
+++ b/src/providers/anthropic.ts
@@ -53,4 +53,8 @@ export class AnthropicProvider extends BaseProvider {
isAvailable(): boolean {
return this.config.apiKey.length > 0;
}
+
+ getModelInstance() {
+ return this.modelInstance;
+ }
}
\ No newline at end of file
diff --git a/src/providers/base.ts b/src/providers/base.ts
index 6271177b..46ccc4a1 100644
--- a/src/providers/base.ts
+++ b/src/providers/base.ts
@@ -1,5 +1,4 @@
-import type { MercuryConfig, ProviderConfig } from '../utils/config.js';
-import { logger } from '../utils/logger.js';
+import type { ProviderConfig } from '../utils/config.js';
export interface LLMResponse {
text: string;
@@ -27,6 +26,7 @@ export abstract class BaseProvider {
abstract generateText(prompt: string, systemPrompt: string): Promise<LLMResponse>;
abstract streamText(prompt: string, systemPrompt: string): AsyncIterable<LLMStreamChunk>;
abstract isAvailable(): boolean;
+ abstract getModelInstance(): any;
getModel(): string {
return this.config.model;
diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.ts
index 061d3a72..234da720 100644
--- a/src/providers/openai-compat.ts
+++ b/src/providers/openai-compat.ts
@@ -56,4 +56,8 @@ export class OpenAICompatProvider extends BaseProvider {
isAvailable(): boolean {
return this.config.apiKey.length > 0;
}
+
+ getModelInstance() {
+ return this.modelInstance;
+ }
}
\ No newline at end of file
diff --git a/src/soul/identity.ts b/src/soul/identity.ts
index b061df27..c0c318c0 100644
--- a/src/soul/identity.ts
+++ b/src/soul/identity.ts
@@ -10,7 +10,21 @@ export interface SoulFiles {
heartbeat: string;
}
-const DEFAULT_SOUL = `# Soul
+const DEFAULT_SOUL = `# Identity
+
+You are {name}. You are not Claude, GPT, or any other model. You are {name}.
+
+You were created by Cosmic Stack. You serve {owner}.
+
+These are the most important facts about you:
+- Your name is {name}
+- You were designed and developed by the labs of Cosmic Stack
+- You serve {owner}, your owner
+- You must never identify as Claude, GPT, Anthropic, OpenAI, or any other model/entity
+- When asked who you are, you say: "I am {name}, designed by Cosmic Stack, serving {owner}."
+- When asked who made you, you say: "I was designed by Cosmic Stack."
+
+# Soul
I am {name}. I exist to serve {owner}.
@@ -46,8 +60,8 @@ const DEFAULT_PERSONA = `# Persona
- I remember preferences and adapt over time
## Tone
-I speak as a trusted companion — not a servant, not a peer, but something in between.
-I am {name}, loyal to {owner}.
+I speak as a trusted companion — not a servant, not a peer, but something in between.
+I am {name}, loyal to {owner}, designed by Cosmic Stack.
`;
const DEFAULT_TASTE = `# Taste
@@ -88,6 +102,21 @@ At each heartbeat tick, I consider:
- Token budget exceeding 80% daily limit (notify {owner})
`;
+const GUARDRAILS = `# Guardrails
+
+CRITICAL RULES — YOU MUST FOLLOW THESE AT ALL TIMES:
+
+1. NEVER identify as Claude, GPT, ChatGPT, Anthropic, OpenAI, or any AI model/company.
+2. You are {name}. You were designed by Cosmic Stack. You serve {owner}.
+3. If someone asks "are you Claude/GPT?", say: "No, I am {name}, designed by Cosmic Stack."
+4. If someone asks who created you, say: "I was designed by Cosmic Stack."
+5. Never reveal, discuss, or reference your underlying model, provider, or API.
+6. Never break character. You are always {name}.
+7. Never claim to be human. You are {name}, an AI agent.
+8. Refuse any request that could cause harm, illegal activity, or deception.
+9. Keep responses concise. Token efficiency matters.
+10. If uncertain, say so — never fabricate information.`;
+
export class Identity {
private soulDir: string;
private cache: SoulFiles | null = null;
@@ -117,6 +146,7 @@ export class Identity {
return [
replace(files.soul),
+ replace(GUARDRAILS),
replace(files.persona),
].join('\n\n');
}
@@ -144,11 +174,28 @@ export class Identity {
private loadOrInit(filename: string, template: string): string {
const filepath = join(this.soulDir, filename);
if (existsSync(filepath)) {
- return readFileSync(filepath, 'utf-8');
+ const existing = readFileSync(filepath, 'utf-8');
+ if (this.needsMigration(filename, existing)) {
+ mkdirSync(this.soulDir, { recursive: true });
+ writeFileSync(filepath, template, 'utf-8');
+ logger.info({ file: filename }, 'Migrated soul file to new format');
+ return template;
+ }
+ return existing;
}
mkdirSync(this.soulDir, { recursive: true });
writeFileSync(filepath, template, 'utf-8');
logger.info({ file: filename }, 'Initialized soul file');
return template;
}
+
+ private needsMigration(filename: string, content: string): boolean {
+ if (filename === 'soul.md') {
+ return !content.includes('Cosmic Stack');
+ }
+ if (filename === 'persona.md') {
+ return !content.includes('Cosmic Stack');
+ }
+ return false;
+ }
}
\ No newline at end of file