@cordbot/agent 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +112 -0
- package/bin/cordbot.js +10 -0
- package/dist/agent/manager.js +256 -0
- package/dist/agent/stream.js +359 -0
- package/dist/auth.js +161 -0
- package/dist/cli.js +128 -0
- package/dist/discord/client.js +24 -0
- package/dist/discord/events.js +283 -0
- package/dist/discord/sync.js +148 -0
- package/dist/index.js +72 -0
- package/dist/init.js +82 -0
- package/dist/permissions/discord.js +66 -0
- package/dist/scheduler/parser.js +62 -0
- package/dist/scheduler/runner.js +201 -0
- package/dist/service/config.js +2 -0
- package/dist/service/manifest.js +27 -0
- package/dist/service/token-manager.js +143 -0
- package/dist/service/types.js +1 -0
- package/dist/storage/database.js +122 -0
- package/dist/tools/builtin-loader.js +21 -0
- package/dist/tools/cron/add_job.js +96 -0
- package/dist/tools/cron/list_jobs.js +55 -0
- package/dist/tools/cron/remove_job.js +64 -0
- package/dist/tools/cron/update_job.js +97 -0
- package/dist/tools/gmail/list_messages.js +87 -0
- package/dist/tools/gmail/send_email.js +118 -0
- package/dist/tools/loader.js +84 -0
- package/dist/tools/share_file.js +61 -0
- package/package.json +65 -0
- package/templates/.claude-cron.template +3 -0
- package/templates/channel-CLAUDE.md.template +26 -0
- package/templates/cron-skill.md +63 -0
- package/templates/root-CLAUDE.md.template +78 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Christian Alfoni
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Cordbot
|
|
2
|
+
|
|
3
|
+
A Discord bot powered by the Claude Agent SDK that enables autonomous AI assistance directly in your Discord server.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
Cordbot is a directory-based Discord bot that syncs Discord channels to local folders, maintains persistent conversation sessions in threads, and supports scheduled autonomous tasks. It uses the Claude Agent SDK with full system access (dangerous mode) to read files, run commands, and make code changes.
|
|
8
|
+
|
|
9
|
+
## Key Features
|
|
10
|
+
|
|
11
|
+
- **🤖 Autonomous AI Agent**: Full Claude Code SDK capabilities with dangerous mode enabled
|
|
12
|
+
- **💬 Thread-Based Sessions**: Each Discord thread maintains persistent conversation history
|
|
13
|
+
- **📁 Directory-Based**: Each workspace directory has its own configuration and synced channels
|
|
14
|
+
- **📎 File Attachments**: Upload files to Claude or receive generated files back through Discord
|
|
15
|
+
- **⏰ Scheduled Tasks**: Configure autonomous tasks with `.claude-cron` files
|
|
16
|
+
- **🔌 Service Integrations**: Connect Gmail, Google Calendar, and other services via OAuth
|
|
17
|
+
- **🔄 Hot Reload**: Watches for configuration changes and reloads automatically
|
|
18
|
+
|
|
19
|
+
## Getting Started
|
|
20
|
+
|
|
21
|
+
Visit **[cordbot.io](https://cordbot.io)** to:
|
|
22
|
+
|
|
23
|
+
1. Sign in with your Discord account
|
|
24
|
+
2. Configure your bot token and server
|
|
25
|
+
3. Connect service integrations (Gmail, etc.)
|
|
26
|
+
4. Get your agent authentication token
|
|
27
|
+
|
|
28
|
+
Run the agent:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx @cordbot/agent
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The bot will sync Discord channels to folders in your workspace directory, where you can interact with Claude through Discord messages and threads.
|
|
35
|
+
|
|
36
|
+
## How It Works
|
|
37
|
+
|
|
38
|
+
1. **Authentication**: Sign in at cordbot.io to configure your bot and get authenticated
|
|
39
|
+
2. **Channel Sync**: Discord channels are synced to local folders in your workspace directory
|
|
40
|
+
3. **Contextual Instructions**: Each channel folder has a `CLAUDE.md` file providing context to Claude
|
|
41
|
+
4. **Thread Sessions**: Start a conversation in Discord and the bot maintains context throughout the thread
|
|
42
|
+
5. **File Attachments**: Send files to Claude by attaching them to Discord messages, or receive files Claude generates
|
|
43
|
+
6. **Scheduled Jobs**: Configure `.claude-cron` files to run autonomous tasks on a schedule
|
|
44
|
+
7. **Service Tools**: Connected services (Gmail, etc.) become available as tools Claude can use
|
|
45
|
+
|
|
46
|
+
### Working with Files
|
|
47
|
+
|
|
48
|
+
**Sending files to Claude:**
|
|
49
|
+
|
|
50
|
+
- Attach files to any Discord message (images, code, documents, etc.)
|
|
51
|
+
- Files are automatically downloaded to the channel folder
|
|
52
|
+
- Claude can read, edit, and process them using its standard tools
|
|
53
|
+
- Existing files with the same name are overwritten
|
|
54
|
+
|
|
55
|
+
**Receiving files from Claude:**
|
|
56
|
+
|
|
57
|
+
- Claude can use the `shareFile` tool to send files back to you
|
|
58
|
+
- Files are attached to Discord after Claude's response
|
|
59
|
+
- Works with any file type: generated code, diagrams, reports, etc.
|
|
60
|
+
|
|
61
|
+
Example:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
You: [Attach config.json] "Can you update the timeout to 30 seconds?"
|
|
65
|
+
Claude: [Reads config.json, edits it, uses shareFile to send back]
|
|
66
|
+
Discord: 📎 Shared files: config.json
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Project Structure
|
|
70
|
+
|
|
71
|
+
This is a monorepo containing:
|
|
72
|
+
|
|
73
|
+
- **`packages/bot/`** - The agent process and Discord bot
|
|
74
|
+
- **`packages/web-service/`** - Web dashboard for configuration and OAuth flows
|
|
75
|
+
|
|
76
|
+
## Documentation
|
|
77
|
+
|
|
78
|
+
- **Agent Documentation**: See [packages/bot/README.md](packages/bot/README.md) for detailed agent usage
|
|
79
|
+
- **Web Service**: Visit [cordbot.io](https://cordbot.io) for setup and configuration
|
|
80
|
+
- **How It Works**: See the documentation section at [cordbot.io](https://cordbot.io) for details on channels, threads, messages, and cron jobs
|
|
81
|
+
|
|
82
|
+
## Security Warning
|
|
83
|
+
|
|
84
|
+
Cordbot runs in "dangerous mode" with full system access:
|
|
85
|
+
|
|
86
|
+
- Full filesystem read/write
|
|
87
|
+
- Bash command execution
|
|
88
|
+
- Network operations
|
|
89
|
+
- Package management
|
|
90
|
+
|
|
91
|
+
**Only use in trusted environments with controlled Discord access.** Never share your authentication tokens or commit `.env` files to git.
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
# Install dependencies
|
|
97
|
+
npm install
|
|
98
|
+
|
|
99
|
+
# Build packages
|
|
100
|
+
npm run build
|
|
101
|
+
|
|
102
|
+
# Run tests
|
|
103
|
+
npm test
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
|
109
|
+
|
|
110
|
+
## Support
|
|
111
|
+
|
|
112
|
+
For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/yourusername/cordbot).
|
package/bin/cordbot.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// This file is the entry point for the CLI command
|
|
4
|
+
// It simply imports and runs the CLI module
|
|
5
|
+
import('../dist/cli.js').then(module => {
|
|
6
|
+
module.run();
|
|
7
|
+
}).catch(err => {
|
|
8
|
+
console.error('Failed to start cordbot:', err);
|
|
9
|
+
process.exit(1);
|
|
10
|
+
});
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { query, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import { fetchManifest } from "../service/manifest.js";
|
|
4
|
+
import { loadDynamicTools } from "../tools/loader.js";
|
|
5
|
+
import { loadBuiltinTools } from "../tools/builtin-loader.js";
|
|
6
|
+
import { SERVICE_URL } from "../service/config.js";
|
|
7
|
+
import { TokenManager } from "../service/token-manager.js";
|
|
8
|
+
export class SessionManager {
|
|
9
|
+
db;
|
|
10
|
+
sessionsDir;
|
|
11
|
+
pendingCronSessions = new Map();
|
|
12
|
+
dynamicMcpServer = null;
|
|
13
|
+
tokenManager = null;
|
|
14
|
+
currentChannels = new Map();
|
|
15
|
+
currentWorkingDirs = new Map();
|
|
16
|
+
filesToShare = new Map(); // sessionId -> file paths
|
|
17
|
+
constructor(db, sessionsDir) {
|
|
18
|
+
this.db = db;
|
|
19
|
+
this.sessionsDir = sessionsDir;
|
|
20
|
+
}
|
|
21
|
+
async initialize(botToken) {
|
|
22
|
+
// Load built-in tools (always available, no auth needed)
|
|
23
|
+
const builtinTools = loadBuiltinTools(() => {
|
|
24
|
+
// Get the working directory for the currently executing session
|
|
25
|
+
const entries = Array.from(this.currentWorkingDirs.entries());
|
|
26
|
+
return entries.length > 0 ? entries[0][1] : process.cwd();
|
|
27
|
+
}, (filePath) => {
|
|
28
|
+
// Queue file for sharing - get current session
|
|
29
|
+
const entries = Array.from(this.currentWorkingDirs.entries());
|
|
30
|
+
if (entries.length > 0) {
|
|
31
|
+
const sessionId = entries[0][0];
|
|
32
|
+
this.queueFileForSharing(sessionId, filePath);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
// Fetch manifest from service for authenticated tools
|
|
36
|
+
const manifest = await fetchManifest(botToken, SERVICE_URL);
|
|
37
|
+
let dynamicTools = [];
|
|
38
|
+
if (manifest) {
|
|
39
|
+
const toolCount = Object.values(manifest.toolsConfig || {}).reduce((sum, tools) => sum + tools.length, 0);
|
|
40
|
+
console.log(`📦 Manifest loaded: ${toolCount} authenticated tools available`);
|
|
41
|
+
// Create token manager
|
|
42
|
+
this.tokenManager = new TokenManager(botToken, SERVICE_URL, manifest);
|
|
43
|
+
this.tokenManager.startBackgroundRefresh();
|
|
44
|
+
// Load dynamic tools with token manager and channel getter
|
|
45
|
+
dynamicTools = await loadDynamicTools(manifest, this.tokenManager, () => {
|
|
46
|
+
// Get the channel for the currently executing session
|
|
47
|
+
// This will be set before each query execution
|
|
48
|
+
const entries = Array.from(this.currentChannels.entries());
|
|
49
|
+
return entries.length > 0 ? entries[0][1] : null;
|
|
50
|
+
});
|
|
51
|
+
if (dynamicTools.length > 0) {
|
|
52
|
+
console.log(` ✓ Loaded ${dynamicTools.length} authenticated tools`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
console.log('ℹ️ No manifest - authenticated tools disabled');
|
|
57
|
+
}
|
|
58
|
+
// Combine built-in and dynamic tools
|
|
59
|
+
const allTools = [...builtinTools, ...dynamicTools];
|
|
60
|
+
if (allTools.length > 0) {
|
|
61
|
+
// Create SDK MCP server with all tools
|
|
62
|
+
this.dynamicMcpServer = createSdkMcpServer({
|
|
63
|
+
name: 'cordbot-tools',
|
|
64
|
+
version: '1.0.0',
|
|
65
|
+
tools: allTools
|
|
66
|
+
});
|
|
67
|
+
console.log(`✅ Total tools available: ${allTools.length} (${builtinTools.length} built-in + ${dynamicTools.length} authenticated)`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Get or create a session for a Discord thread
|
|
72
|
+
* Returns the session ID to use with query({ resume: sessionId })
|
|
73
|
+
*/
|
|
74
|
+
async getOrCreateSession(threadId, channelId, messageId, workingDir) {
|
|
75
|
+
// Check database for existing session
|
|
76
|
+
const existing = this.db.getMapping(threadId);
|
|
77
|
+
if (existing) {
|
|
78
|
+
// Update last active
|
|
79
|
+
this.db.updateLastActive(threadId);
|
|
80
|
+
return {
|
|
81
|
+
sessionId: existing.session_id,
|
|
82
|
+
isNew: false,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
// Create new session - first query will initialize it
|
|
86
|
+
const sessionId = `sess_${Date.now()}_${randomUUID()}`;
|
|
87
|
+
// Store in database
|
|
88
|
+
this.db.createMapping({
|
|
89
|
+
discord_thread_id: threadId,
|
|
90
|
+
discord_channel_id: channelId,
|
|
91
|
+
discord_message_id: messageId,
|
|
92
|
+
session_id: sessionId,
|
|
93
|
+
working_directory: workingDir,
|
|
94
|
+
status: "active",
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
sessionId,
|
|
98
|
+
isNew: true,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Create a session mapping with a specific session ID (for cron sessions)
|
|
103
|
+
*/
|
|
104
|
+
createMappingWithSessionId(threadId, channelId, messageId, sessionId, workingDir) {
|
|
105
|
+
this.db.createMapping({
|
|
106
|
+
discord_thread_id: threadId,
|
|
107
|
+
discord_channel_id: channelId,
|
|
108
|
+
discord_message_id: messageId,
|
|
109
|
+
session_id: sessionId,
|
|
110
|
+
working_directory: workingDir,
|
|
111
|
+
status: "active",
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Set the Discord channel for the current session
|
|
116
|
+
* Must be called before createQuery to enable permission requests
|
|
117
|
+
*/
|
|
118
|
+
setChannelContext(sessionId, channel) {
|
|
119
|
+
this.currentChannels.set(sessionId, channel);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Clear the channel context after query execution
|
|
123
|
+
*/
|
|
124
|
+
clearChannelContext(sessionId) {
|
|
125
|
+
this.currentChannels.delete(sessionId);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Set the working directory for the current session
|
|
129
|
+
* Must be called before createQuery to enable built-in tools (cron, etc.)
|
|
130
|
+
*/
|
|
131
|
+
setWorkingDirContext(sessionId, workingDir) {
|
|
132
|
+
this.currentWorkingDirs.set(sessionId, workingDir);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Clear the working directory context after query execution
|
|
136
|
+
*/
|
|
137
|
+
clearWorkingDirContext(sessionId) {
|
|
138
|
+
this.currentWorkingDirs.delete(sessionId);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Create a query for a user message
|
|
142
|
+
* Automatically resumes session if sessionId exists
|
|
143
|
+
*/
|
|
144
|
+
createQuery(userMessage, sessionId, workingDir) {
|
|
145
|
+
const options = {
|
|
146
|
+
cwd: workingDir,
|
|
147
|
+
resume: sessionId || undefined, // Resume if existing, else new
|
|
148
|
+
includePartialMessages: true, // Get streaming events
|
|
149
|
+
settingSources: ["project"], // Load root CLAUDE.md + channel CLAUDE.md files + .claude/skills
|
|
150
|
+
allowDangerouslySkipPermissions: true,
|
|
151
|
+
permissionMode: "bypassPermissions",
|
|
152
|
+
tools: { type: "preset", preset: "claude_code" }, // Enable all Claude Code tools
|
|
153
|
+
};
|
|
154
|
+
// Add dynamic MCP server if available
|
|
155
|
+
if (this.dynamicMcpServer) {
|
|
156
|
+
options.mcpServers = {
|
|
157
|
+
'cordbot-dynamic-tools': this.dynamicMcpServer
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
return query({
|
|
161
|
+
prompt: userMessage,
|
|
162
|
+
options,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
async updateSession(sessionId, threadId) {
|
|
166
|
+
this.db.updateLastActive(threadId);
|
|
167
|
+
}
|
|
168
|
+
async updateSessionId(oldSessionId, newSessionId, threadId) {
|
|
169
|
+
// Update the database mapping with the real SDK session ID
|
|
170
|
+
const mapping = this.db.getMapping(threadId);
|
|
171
|
+
if (mapping && mapping.session_id === oldSessionId) {
|
|
172
|
+
this.db.updateSessionId(threadId, newSessionId);
|
|
173
|
+
console.log(`📝 Updated session ID: ${oldSessionId} → ${newSessionId}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async archiveOldSessions(daysInactive) {
|
|
177
|
+
const cutoff = Date.now() - daysInactive * 24 * 60 * 60 * 1000;
|
|
178
|
+
const oldSessions = this.db.getAllActive().filter((s) => {
|
|
179
|
+
return new Date(s.last_active_at).getTime() < cutoff;
|
|
180
|
+
});
|
|
181
|
+
for (const session of oldSessions) {
|
|
182
|
+
this.db.archiveSession(session.discord_thread_id);
|
|
183
|
+
}
|
|
184
|
+
return oldSessions.length;
|
|
185
|
+
}
|
|
186
|
+
getActiveSessionCount() {
|
|
187
|
+
return this.db.getActiveCount();
|
|
188
|
+
}
|
|
189
|
+
getSessionByThreadId(threadId) {
|
|
190
|
+
const mapping = this.db.getMapping(threadId);
|
|
191
|
+
if (!mapping)
|
|
192
|
+
return undefined;
|
|
193
|
+
return {
|
|
194
|
+
sessionId: mapping.session_id,
|
|
195
|
+
threadId: mapping.discord_thread_id,
|
|
196
|
+
channelId: mapping.discord_channel_id,
|
|
197
|
+
workingDirectory: mapping.working_directory,
|
|
198
|
+
created: new Date(mapping.created_at),
|
|
199
|
+
lastActive: new Date(mapping.last_active_at),
|
|
200
|
+
status: mapping.status,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Store a cron session that can be continued with the next message in the channel
|
|
205
|
+
*/
|
|
206
|
+
setPendingCronSession(channelId, sessionId, workingDir) {
|
|
207
|
+
this.pendingCronSessions.set(channelId, {
|
|
208
|
+
sessionId,
|
|
209
|
+
timestamp: Date.now(),
|
|
210
|
+
workingDir,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Get and remove a pending cron session if one exists and is recent (within 1 hour)
|
|
215
|
+
*/
|
|
216
|
+
getPendingCronSession(channelId) {
|
|
217
|
+
const pending = this.pendingCronSessions.get(channelId);
|
|
218
|
+
if (!pending)
|
|
219
|
+
return null;
|
|
220
|
+
// Check if it's still valid (within 1 hour)
|
|
221
|
+
const age = Date.now() - pending.timestamp;
|
|
222
|
+
const oneHour = 60 * 60 * 1000;
|
|
223
|
+
if (age > oneHour) {
|
|
224
|
+
// Expired, remove it
|
|
225
|
+
this.pendingCronSessions.delete(channelId);
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
// Valid, remove it (one-time use)
|
|
229
|
+
this.pendingCronSessions.delete(channelId);
|
|
230
|
+
return pending;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Queue a file to be shared with the user (attached to Discord)
|
|
234
|
+
*/
|
|
235
|
+
queueFileForSharing(sessionId, filePath) {
|
|
236
|
+
const existing = this.filesToShare.get(sessionId) || [];
|
|
237
|
+
existing.push(filePath);
|
|
238
|
+
this.filesToShare.set(sessionId, existing);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Get and clear files queued for sharing
|
|
242
|
+
*/
|
|
243
|
+
getFilesToShare(sessionId) {
|
|
244
|
+
const files = this.filesToShare.get(sessionId) || [];
|
|
245
|
+
this.filesToShare.delete(sessionId);
|
|
246
|
+
return files;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Cleanup token manager on shutdown
|
|
250
|
+
*/
|
|
251
|
+
shutdown() {
|
|
252
|
+
if (this.tokenManager) {
|
|
253
|
+
this.tokenManager.stopBackgroundRefresh();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|