@abdarrahmanabdelnasir/relay-node 0.1.6
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 +22 -0
- package/README.md +80 -0
- package/dist/adapters/discord.d.ts +21 -0
- package/dist/adapters/discord.js +289 -0
- package/dist/http.d.ts +6 -0
- package/dist/http.js +41 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/relayClient.d.ts +22 -0
- package/dist/relayClient.js +90 -0
- package/dist/signing.d.ts +2 -0
- package/dist/signing.js +7 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.js +1 -0
- package/dist-cjs/adapters/discord.d.ts +21 -0
- package/dist-cjs/adapters/discord.js +292 -0
- package/dist-cjs/http.d.ts +6 -0
- package/dist-cjs/http.js +44 -0
- package/dist-cjs/index.cjs +21 -0
- package/dist-cjs/index.d.ts +5 -0
- package/dist-cjs/package.cjs +0 -0
- package/dist-cjs/relayClient.d.ts +22 -0
- package/dist-cjs/relayClient.js +94 -0
- package/dist-cjs/signing.d.ts +2 -0
- package/dist-cjs/signing.js +14 -0
- package/dist-cjs/types.d.ts +60 -0
- package/dist-cjs/types.js +2 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Commandless
|
|
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.
|
|
22
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# @commandless/relay-node
|
|
2
|
+
|
|
3
|
+
Lightweight Node SDK to integrate your Discord bot with the Commandless backend. It forwards events (messages/interactions) and executes returned actions (AI replies or commands). Your bot token never leaves your app.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i discord.js @commandless/relay-node
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quickstart (Discord.js v14)
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Client, GatewayIntentBits } from 'discord.js';
|
|
15
|
+
import { RelayClient, useDiscordAdapter } from '@commandless/relay-node';
|
|
16
|
+
|
|
17
|
+
const discord = new Client({
|
|
18
|
+
intents: [
|
|
19
|
+
GatewayIntentBits.Guilds,
|
|
20
|
+
GatewayIntentBits.GuildMessages,
|
|
21
|
+
GatewayIntentBits.MessageContent,
|
|
22
|
+
],
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const relay = new RelayClient({
|
|
26
|
+
apiKey: process.env.COMMANDLESS_API_KEY!,
|
|
27
|
+
baseUrl: process.env.COMMANDLESS_SERVICE_URL,
|
|
28
|
+
hmacSecret: process.env.COMMANDLESS_HMAC_SECRET, // optional but recommended
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
useDiscordAdapter({ client: discord, relay });
|
|
32
|
+
|
|
33
|
+
discord.login(process.env.BOT_TOKEN);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Templates
|
|
37
|
+
|
|
38
|
+
- AI-only (conversational replies, no local commands): see `examples/index.ai-only.js` in the main repo.
|
|
39
|
+
- With registry (route command actions to your handlers): see `examples/index.with-registry.js`.
|
|
40
|
+
|
|
41
|
+
### Environment variables
|
|
42
|
+
|
|
43
|
+
- `BOT_TOKEN` — Discord bot token
|
|
44
|
+
- `COMMANDLESS_API_KEY` — API key created in the dashboard
|
|
45
|
+
- `COMMANDLESS_SERVICE_URL` — your Commandless service base URL
|
|
46
|
+
- `COMMANDLESS_HMAC_SECRET` — optional HMAC signing secret
|
|
47
|
+
- `BOT_ID` — optional fixed bot id to lock persona to a specific bot row
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
- `RelayClient(opts)`
|
|
52
|
+
- `sendEvent(event)` → `Decision | null` (retries + idempotency)
|
|
53
|
+
- `enqueue(event)` → fire-and-forget queue
|
|
54
|
+
- `useDiscordAdapter({ client, relay, execute? })`
|
|
55
|
+
- Wires `messageCreate` and `interactionCreate`
|
|
56
|
+
- Optional `execute(decision, ctx)` to override default reply behavior
|
|
57
|
+
- `mentionRequired` (default true) to only process when mentioned or replying to the bot
|
|
58
|
+
|
|
59
|
+
## Security
|
|
60
|
+
|
|
61
|
+
- Every request includes `x-commandless-key`.
|
|
62
|
+
- Optional `x-signature` HMAC (SHA-256 of raw body) if you set `hmacSecret`.
|
|
63
|
+
- Idempotency with `x-idempotency-key` to dedupe retries.
|
|
64
|
+
|
|
65
|
+
## Troubleshooting
|
|
66
|
+
|
|
67
|
+
- No persona loaded: ensure events carry `botId` (set `BOT_ID` or let `registerBot` link) and the bot row has a saved personality; ensure your API key maps to the same `user_id`.
|
|
68
|
+
- 401/405 errors from dashboard: set `COMMANDLESS_SERVICE_URL` correctly; SDK calls should go to the service (Railway), not the dashboard host.
|
|
69
|
+
- Empty AI responses: verify OpenRouter/OpenAI envs on the backend and timeouts; the SDK will log decisions and retries.
|
|
70
|
+
|
|
71
|
+
## Requirements
|
|
72
|
+
|
|
73
|
+
- Node 18+
|
|
74
|
+
- Discord.js 14+
|
|
75
|
+
|
|
76
|
+
## Notes
|
|
77
|
+
|
|
78
|
+
MVP; surface may evolve pre‑1.0. Please file issues and suggestions.
|
|
79
|
+
|
|
80
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Client, Message, Interaction } from "discord.js";
|
|
2
|
+
import { RelayClient } from "../relayClient.js";
|
|
3
|
+
import type { Decision } from "../types.js";
|
|
4
|
+
export interface DiscordAdapterOptions {
|
|
5
|
+
client: Client;
|
|
6
|
+
relay: RelayClient;
|
|
7
|
+
execute?: (dec: Decision, ctx: {
|
|
8
|
+
message?: Message;
|
|
9
|
+
interaction?: Interaction;
|
|
10
|
+
}) => Promise<void>;
|
|
11
|
+
onCommand?: (spec: {
|
|
12
|
+
slash?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
args?: Record<string, unknown>;
|
|
15
|
+
}, ctx: {
|
|
16
|
+
message?: Message;
|
|
17
|
+
interaction?: Interaction;
|
|
18
|
+
}) => Promise<void>;
|
|
19
|
+
mentionRequired?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function useDiscordAdapter(opts: DiscordAdapterOptions): void;
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
export function useDiscordAdapter(opts) {
|
|
2
|
+
const { client, relay } = opts;
|
|
3
|
+
client.on("messageCreate", async (message) => {
|
|
4
|
+
if (message.author.bot)
|
|
5
|
+
return;
|
|
6
|
+
const mentionRequired = opts.mentionRequired !== false;
|
|
7
|
+
const mentioned = !!client.user?.id && (message.mentions?.users?.has?.(client.user.id) ?? false);
|
|
8
|
+
// Typing indicator will be driven by a short loop only when addressed
|
|
9
|
+
// Detect reply-to-bot accurately
|
|
10
|
+
let isReplyToBot = false;
|
|
11
|
+
try {
|
|
12
|
+
if (message.reference?.messageId && client.user?.id) {
|
|
13
|
+
const ref = await message.channel.messages.fetch(message.reference.messageId).catch(() => null);
|
|
14
|
+
if (ref && ref.author && ref.author.id === client.user.id)
|
|
15
|
+
isReplyToBot = true;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
catch { }
|
|
19
|
+
if (mentionRequired && !mentioned && !isReplyToBot)
|
|
20
|
+
return;
|
|
21
|
+
const evt = {
|
|
22
|
+
type: "messageCreate",
|
|
23
|
+
id: message.id,
|
|
24
|
+
guildId: message.guildId ?? undefined,
|
|
25
|
+
channelId: message.channelId,
|
|
26
|
+
authorId: message.author.id,
|
|
27
|
+
content: message.content,
|
|
28
|
+
timestamp: message.createdTimestamp,
|
|
29
|
+
botClientId: client.user?.id,
|
|
30
|
+
isReplyToBot,
|
|
31
|
+
referencedMessageId: message.reference?.messageId,
|
|
32
|
+
referencedMessageAuthorId: message.reference ? client.user?.id : undefined,
|
|
33
|
+
};
|
|
34
|
+
try {
|
|
35
|
+
let typingTimer = null;
|
|
36
|
+
try {
|
|
37
|
+
await message.channel?.sendTyping?.();
|
|
38
|
+
}
|
|
39
|
+
catch { }
|
|
40
|
+
typingTimer = setInterval(() => {
|
|
41
|
+
try {
|
|
42
|
+
message.channel?.sendTyping?.();
|
|
43
|
+
}
|
|
44
|
+
catch { }
|
|
45
|
+
}, 8000);
|
|
46
|
+
const dec = await relay.sendEvent(evt);
|
|
47
|
+
if (dec)
|
|
48
|
+
await (opts.execute ? opts.execute(dec, { message }) : defaultExecute(dec, { message }, opts));
|
|
49
|
+
if (typingTimer)
|
|
50
|
+
clearInterval(typingTimer);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
// swallow; user code can add logging
|
|
54
|
+
// ensure typing cleared
|
|
55
|
+
// no-op: interval cleared by GC if not set
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
client.on("interactionCreate", async (interaction) => {
|
|
59
|
+
if (!interaction.isCommand())
|
|
60
|
+
return;
|
|
61
|
+
const cmd = interaction;
|
|
62
|
+
const evt = {
|
|
63
|
+
type: "interactionCreate",
|
|
64
|
+
id: interaction.id,
|
|
65
|
+
guildId: interaction.guildId ?? undefined,
|
|
66
|
+
channelId: interaction.channelId ?? undefined,
|
|
67
|
+
userId: interaction.user.id,
|
|
68
|
+
name: cmd.commandName,
|
|
69
|
+
options: (() => {
|
|
70
|
+
const out = {};
|
|
71
|
+
try {
|
|
72
|
+
// Guard for discord.js v14 CommandInteractionOptionResolver
|
|
73
|
+
const data = cmd.options?.data || [];
|
|
74
|
+
for (const d of data)
|
|
75
|
+
out[d.name] = d.value;
|
|
76
|
+
}
|
|
77
|
+
catch { }
|
|
78
|
+
return out;
|
|
79
|
+
})(),
|
|
80
|
+
timestamp: Date.now(),
|
|
81
|
+
};
|
|
82
|
+
try {
|
|
83
|
+
const dec = await relay.sendEvent(evt);
|
|
84
|
+
if (dec)
|
|
85
|
+
await (opts.execute ? opts.execute(dec, { interaction }) : defaultExecute(dec, { interaction }, opts));
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
// swallow
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function getByPath(root, path) {
|
|
93
|
+
if (!root || !path)
|
|
94
|
+
return undefined;
|
|
95
|
+
try {
|
|
96
|
+
return path.split('.').reduce((o, k) => (o ? o[k] : undefined), root);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function pickHandler(registry, action) {
|
|
103
|
+
if (!registry || !action)
|
|
104
|
+
return null;
|
|
105
|
+
try {
|
|
106
|
+
if (typeof registry.get === 'function') {
|
|
107
|
+
return registry.get(action) || registry.get(action.toLowerCase());
|
|
108
|
+
}
|
|
109
|
+
return registry[action] || registry[action.toLowerCase?.()];
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function runHandler(handler, message, args, rest) {
|
|
116
|
+
if (!handler)
|
|
117
|
+
return false;
|
|
118
|
+
try {
|
|
119
|
+
if (typeof handler.execute === 'function') {
|
|
120
|
+
await handler.execute(message, args, rest);
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
if (typeof handler.run === 'function') {
|
|
124
|
+
await handler.run(message, args, rest);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
if (typeof handler.messageRun === 'function') {
|
|
128
|
+
await handler.messageRun(message, { args, rest });
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
if (typeof handler.exec === 'function') {
|
|
132
|
+
await handler.exec(message, rest.join(' '));
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
if (typeof handler === 'function') {
|
|
136
|
+
await handler({ message, args, rest });
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// swallow; user code can add logging
|
|
142
|
+
return true; // handler existed and threw; consider handled to avoid double-processing
|
|
143
|
+
}
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
async function defaultExecute(decision, ctx, opts) {
|
|
147
|
+
const reply = decision.actions?.find(a => a.kind === "reply");
|
|
148
|
+
const command = decision.actions?.find(a => a.kind === "command");
|
|
149
|
+
if (reply) {
|
|
150
|
+
if (ctx.message) {
|
|
151
|
+
await ctx.message.reply({ content: reply.content });
|
|
152
|
+
}
|
|
153
|
+
else if (ctx.interaction && ctx.interaction.isRepliable())
|
|
154
|
+
await ctx.interaction.reply({ content: reply.content, ephemeral: reply.ephemeral ?? false });
|
|
155
|
+
}
|
|
156
|
+
if (command && ctx.message) {
|
|
157
|
+
const slash = String(command.slash || '').trim();
|
|
158
|
+
const disableBuiltins = String(process.env.COMMANDLESS_DISABLE_BUILTINS || '').toLowerCase() === 'true';
|
|
159
|
+
const registryPath = process.env.COMMAND_REGISTRY_PATH || '';
|
|
160
|
+
// If user provided explicit handler via onCommand, prefer it
|
|
161
|
+
if (opts?.onCommand) {
|
|
162
|
+
await opts.onCommand({ slash, name: command.name, args: command.args || {} }, ctx).catch(() => { });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
// Env-based auto-routing to existing registry
|
|
166
|
+
if (registryPath) {
|
|
167
|
+
const aliasesRaw = process.env.COMMAND_REGISTRY_ALIAS_JSON || '';
|
|
168
|
+
let alias = {};
|
|
169
|
+
try {
|
|
170
|
+
if (aliasesRaw)
|
|
171
|
+
alias = JSON.parse(aliasesRaw);
|
|
172
|
+
}
|
|
173
|
+
catch { }
|
|
174
|
+
const fromSlash = slash ? parseSlash(slash).action : null;
|
|
175
|
+
const base = String(command.name || fromSlash || '').toLowerCase();
|
|
176
|
+
const action = (alias[base] || base);
|
|
177
|
+
const registry = getByPath(opts?.client, registryPath);
|
|
178
|
+
const handler = pickHandler(registry, action);
|
|
179
|
+
const ok = await runHandler(handler, ctx.message, (command.args || {}), []);
|
|
180
|
+
if (ok || disableBuiltins)
|
|
181
|
+
return; // handled or built-ins disabled
|
|
182
|
+
// fallthrough to built-ins only if not disabled
|
|
183
|
+
}
|
|
184
|
+
// Default built-ins (only if not disabled)
|
|
185
|
+
if (!disableBuiltins) {
|
|
186
|
+
if (slash)
|
|
187
|
+
await executeLocalDiscordCommand(slash, ctx.message).catch(() => { });
|
|
188
|
+
else
|
|
189
|
+
await executeLocalAction(String(command.name || ''), command.args || {}, ctx.message).catch(() => { });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function executeLocalDiscordCommand(slashText, message) {
|
|
194
|
+
const { action, params } = parseSlash(slashText);
|
|
195
|
+
if (!action)
|
|
196
|
+
return;
|
|
197
|
+
try {
|
|
198
|
+
switch (action) {
|
|
199
|
+
case 'say': {
|
|
200
|
+
const content = String(params.message || params.text || params.content || '').trim();
|
|
201
|
+
const ch = message.channel;
|
|
202
|
+
if (content && ch && typeof ch.send === 'function')
|
|
203
|
+
await ch.send({ content });
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
case 'pin': {
|
|
207
|
+
let target = null;
|
|
208
|
+
if (message.reference?.messageId) {
|
|
209
|
+
try {
|
|
210
|
+
target = await message.channel.messages.fetch(message.reference.messageId);
|
|
211
|
+
}
|
|
212
|
+
catch { }
|
|
213
|
+
}
|
|
214
|
+
if (!target) {
|
|
215
|
+
const fetched = await message.channel.messages.fetch({ limit: 2 });
|
|
216
|
+
target = fetched.filter(m => m.id !== message.id).first() || fetched.first();
|
|
217
|
+
}
|
|
218
|
+
if (target && typeof target.pin === 'function')
|
|
219
|
+
await target.pin();
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
case 'purge': {
|
|
223
|
+
const amt = Number(params.amount || params.n || params.count || '0');
|
|
224
|
+
if (amt > 0 && 'bulkDelete' in message.channel) {
|
|
225
|
+
await message.channel.bulkDelete(Math.min(amt, 100), true);
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
// No amount -> delete referenced/last message
|
|
229
|
+
let target = null;
|
|
230
|
+
if (message.reference?.messageId) {
|
|
231
|
+
try {
|
|
232
|
+
target = await message.channel.messages.fetch(message.reference.messageId);
|
|
233
|
+
}
|
|
234
|
+
catch { }
|
|
235
|
+
}
|
|
236
|
+
if (!target) {
|
|
237
|
+
const fetched = await message.channel.messages.fetch({ limit: 2 });
|
|
238
|
+
target = fetched.filter((m) => m.id !== message.id).first() || fetched.first();
|
|
239
|
+
}
|
|
240
|
+
if (target && typeof target.delete === 'function')
|
|
241
|
+
await target.delete().catch(() => { });
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
default:
|
|
245
|
+
// Let bots handle domain-specific actions via custom routing
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch { }
|
|
250
|
+
}
|
|
251
|
+
async function executeLocalAction(action, params, message) {
|
|
252
|
+
try {
|
|
253
|
+
switch (action) {
|
|
254
|
+
case 'say': {
|
|
255
|
+
const t = String(params.message || '').trim();
|
|
256
|
+
const ch = message.channel;
|
|
257
|
+
if (t && ch?.send)
|
|
258
|
+
await ch.send({ content: t });
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
// Add common cross-bot actions here if desired
|
|
262
|
+
default:
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch { }
|
|
267
|
+
}
|
|
268
|
+
function parseSlash(text) {
|
|
269
|
+
const out = {};
|
|
270
|
+
const t = String(text || '').trim().replace(/^\//, '');
|
|
271
|
+
if (!t)
|
|
272
|
+
return { action: null, params: out };
|
|
273
|
+
const [head, ...rest] = t.split(/\s+/);
|
|
274
|
+
let action = head.toLowerCase();
|
|
275
|
+
// parse k=v pairs
|
|
276
|
+
for (const part of rest) {
|
|
277
|
+
const m = part.match(/^([^=]+)=(.*)$/);
|
|
278
|
+
if (m)
|
|
279
|
+
out[m[1]] = m[2];
|
|
280
|
+
}
|
|
281
|
+
// also support freeform for simple commands e.g., "purge 5" or "say hello" (map to message)
|
|
282
|
+
if (!Object.keys(out).length && rest.length) {
|
|
283
|
+
if (action === 'purge' && /^\d+$/.test(rest[0]))
|
|
284
|
+
out.amount = rest[0];
|
|
285
|
+
else
|
|
286
|
+
out.message = rest.join(' ');
|
|
287
|
+
}
|
|
288
|
+
return { action, params: out };
|
|
289
|
+
}
|
package/dist/http.d.ts
ADDED
package/dist/http.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { hmacSign, nowUnixMs } from "./signing.js";
|
|
2
|
+
export async function postJson(url, apiKey, body, opts) {
|
|
3
|
+
const controller = new AbortController();
|
|
4
|
+
const timeout = setTimeout(() => controller.abort(), opts?.timeoutMs ?? 15000);
|
|
5
|
+
const json = JSON.stringify(body);
|
|
6
|
+
const headers = {
|
|
7
|
+
"content-type": "application/json",
|
|
8
|
+
// Use canonical header expected by the server; keep legacy for compatibility
|
|
9
|
+
"x-api-key": apiKey,
|
|
10
|
+
"x-commandless-key": apiKey,
|
|
11
|
+
"x-timestamp": String(nowUnixMs())
|
|
12
|
+
};
|
|
13
|
+
if (opts?.hmacSecret)
|
|
14
|
+
headers["x-signature"] = hmacSign(json, opts.hmacSecret);
|
|
15
|
+
if (opts?.idempotencyKey)
|
|
16
|
+
headers["x-idempotency-key"] = opts.idempotencyKey;
|
|
17
|
+
try {
|
|
18
|
+
const res = await fetch(url, { method: "POST", body: json, headers, signal: controller.signal });
|
|
19
|
+
const requestId = res.headers.get("x-request-id") ?? undefined;
|
|
20
|
+
if (!res.ok) {
|
|
21
|
+
const text = await safeText(res);
|
|
22
|
+
return { ok: false, status: res.status, error: text, requestId };
|
|
23
|
+
}
|
|
24
|
+
const data = (await res.json());
|
|
25
|
+
return { ok: true, status: res.status, data, requestId };
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return { ok: false, status: 0, error: err?.message ?? String(err) };
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
clearTimeout(timeout);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function safeText(res) {
|
|
35
|
+
try {
|
|
36
|
+
return await res.text();
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Decision, RelayClientOptions, RelayEvent } from "./types.js";
|
|
2
|
+
export declare class RelayClient {
|
|
3
|
+
private readonly apiKey;
|
|
4
|
+
private readonly baseUrl;
|
|
5
|
+
private readonly hmacSecret?;
|
|
6
|
+
private readonly timeoutMs;
|
|
7
|
+
private readonly maxRetries;
|
|
8
|
+
private readonly queue;
|
|
9
|
+
private sending;
|
|
10
|
+
private botId?;
|
|
11
|
+
constructor(opts: RelayClientOptions);
|
|
12
|
+
registerBot(info: {
|
|
13
|
+
platform: 'discord';
|
|
14
|
+
name?: string;
|
|
15
|
+
clientId?: string;
|
|
16
|
+
}): Promise<string | null>;
|
|
17
|
+
heartbeat(): Promise<void>;
|
|
18
|
+
sendEvent(event: RelayEvent): Promise<Decision | null>;
|
|
19
|
+
enqueue(event: RelayEvent): void;
|
|
20
|
+
private drain;
|
|
21
|
+
private sendWithRetry;
|
|
22
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { postJson } from "./http.js";
|
|
2
|
+
const DEFAULT_BASE = "https://api.commandless.app";
|
|
3
|
+
export class RelayClient {
|
|
4
|
+
constructor(opts) {
|
|
5
|
+
this.maxRetries = 3;
|
|
6
|
+
this.queue = [];
|
|
7
|
+
this.sending = false;
|
|
8
|
+
this.apiKey = opts.apiKey;
|
|
9
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE).replace(/\/$/, "");
|
|
10
|
+
this.hmacSecret = opts.hmacSecret;
|
|
11
|
+
this.timeoutMs = opts.timeoutMs ?? 15000;
|
|
12
|
+
}
|
|
13
|
+
// Optional: register this SDK bot and obtain/confirm botId
|
|
14
|
+
async registerBot(info) {
|
|
15
|
+
try {
|
|
16
|
+
const url = `${this.baseUrl}/v1/relay/register`;
|
|
17
|
+
const res = await postJson(url, this.apiKey, info, {
|
|
18
|
+
hmacSecret: this.hmacSecret,
|
|
19
|
+
timeoutMs: this.timeoutMs,
|
|
20
|
+
});
|
|
21
|
+
if (res.ok && res.data?.botId) {
|
|
22
|
+
this.botId = res.data.botId;
|
|
23
|
+
return this.botId;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// Optional heartbeat to show online status
|
|
32
|
+
async heartbeat() {
|
|
33
|
+
try {
|
|
34
|
+
const url = `${this.baseUrl}/v1/relay/heartbeat`;
|
|
35
|
+
const res = await postJson(url, this.apiKey, { botId: this.botId }, {
|
|
36
|
+
hmacSecret: this.hmacSecret,
|
|
37
|
+
timeoutMs: this.timeoutMs,
|
|
38
|
+
});
|
|
39
|
+
// Return server response to caller (index.js checks syncRequested)
|
|
40
|
+
return res.data;
|
|
41
|
+
}
|
|
42
|
+
catch { }
|
|
43
|
+
}
|
|
44
|
+
async sendEvent(event) {
|
|
45
|
+
// Immediate send with retries and idempotency
|
|
46
|
+
if (this.botId)
|
|
47
|
+
event.botId = this.botId;
|
|
48
|
+
return await this.sendWithRetry(event);
|
|
49
|
+
}
|
|
50
|
+
enqueue(event) {
|
|
51
|
+
this.queue.push(event);
|
|
52
|
+
if (!this.sending)
|
|
53
|
+
void this.drain();
|
|
54
|
+
}
|
|
55
|
+
async drain() {
|
|
56
|
+
this.sending = true;
|
|
57
|
+
while (this.queue.length) {
|
|
58
|
+
const evt = this.queue.shift();
|
|
59
|
+
try {
|
|
60
|
+
await this.sendWithRetry(evt);
|
|
61
|
+
}
|
|
62
|
+
catch { /* swallow to keep draining */ }
|
|
63
|
+
}
|
|
64
|
+
this.sending = false;
|
|
65
|
+
}
|
|
66
|
+
async sendWithRetry(event) {
|
|
67
|
+
const url = `${this.baseUrl}/v1/relay/events`;
|
|
68
|
+
const idem = makeIdempotencyKey(event);
|
|
69
|
+
let lastErr;
|
|
70
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
71
|
+
const res = await postJson(url, this.apiKey, event, {
|
|
72
|
+
hmacSecret: this.hmacSecret,
|
|
73
|
+
timeoutMs: this.timeoutMs,
|
|
74
|
+
idempotencyKey: idem,
|
|
75
|
+
});
|
|
76
|
+
if (res.ok)
|
|
77
|
+
return res.data?.decision ?? null;
|
|
78
|
+
lastErr = new Error(`Commandless error (${res.status}): ${res.error ?? "unknown"}`);
|
|
79
|
+
// basic backoff
|
|
80
|
+
await sleep(200 * (attempt + 1));
|
|
81
|
+
}
|
|
82
|
+
throw lastErr;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function makeIdempotencyKey(event) {
|
|
86
|
+
// Simple stable key: type-id-timestamp buckets (can be improved)
|
|
87
|
+
const base = `${event.type}:${event.id}:${Math.floor(event.timestamp / 1000)}`;
|
|
88
|
+
return Buffer.from(base).toString("base64url");
|
|
89
|
+
}
|
|
90
|
+
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
package/dist/signing.js
ADDED
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type Snowflake = string;
|
|
2
|
+
export type RelayEvent = {
|
|
3
|
+
type: "messageCreate";
|
|
4
|
+
id: string;
|
|
5
|
+
guildId?: Snowflake;
|
|
6
|
+
channelId: Snowflake;
|
|
7
|
+
authorId: Snowflake;
|
|
8
|
+
content: string;
|
|
9
|
+
timestamp: number;
|
|
10
|
+
botClientId?: Snowflake;
|
|
11
|
+
isReplyToBot?: boolean;
|
|
12
|
+
referencedMessageId?: string;
|
|
13
|
+
referencedMessageAuthorId?: Snowflake;
|
|
14
|
+
referencedMessageContent?: string;
|
|
15
|
+
} | {
|
|
16
|
+
type: "interactionCreate";
|
|
17
|
+
id: string;
|
|
18
|
+
guildId?: Snowflake;
|
|
19
|
+
channelId?: Snowflake;
|
|
20
|
+
userId: Snowflake;
|
|
21
|
+
name: string;
|
|
22
|
+
options?: Record<string, unknown>;
|
|
23
|
+
timestamp: number;
|
|
24
|
+
botClientId?: Snowflake;
|
|
25
|
+
};
|
|
26
|
+
export interface Decision {
|
|
27
|
+
id: string;
|
|
28
|
+
intent: string;
|
|
29
|
+
confidence: number;
|
|
30
|
+
params: Record<string, unknown>;
|
|
31
|
+
safety?: {
|
|
32
|
+
blocked?: boolean;
|
|
33
|
+
reasons?: string[];
|
|
34
|
+
};
|
|
35
|
+
next_step?: string;
|
|
36
|
+
actions?: Array<{
|
|
37
|
+
kind: "reply";
|
|
38
|
+
content: string;
|
|
39
|
+
ephemeral?: boolean;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "command";
|
|
42
|
+
name?: string;
|
|
43
|
+
args?: Record<string, unknown>;
|
|
44
|
+
slash?: string;
|
|
45
|
+
simulate?: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
export interface RelayClientOptions {
|
|
49
|
+
apiKey: string;
|
|
50
|
+
baseUrl?: string;
|
|
51
|
+
hmacSecret?: string;
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
}
|
|
54
|
+
export interface HttpResponse<T> {
|
|
55
|
+
ok: boolean;
|
|
56
|
+
status: number;
|
|
57
|
+
data?: T;
|
|
58
|
+
error?: string;
|
|
59
|
+
requestId?: string;
|
|
60
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Client, Message, Interaction } from "discord.js";
|
|
2
|
+
import { RelayClient } from "../relayClient.js";
|
|
3
|
+
import type { Decision } from "../types.js";
|
|
4
|
+
export interface DiscordAdapterOptions {
|
|
5
|
+
client: Client;
|
|
6
|
+
relay: RelayClient;
|
|
7
|
+
execute?: (dec: Decision, ctx: {
|
|
8
|
+
message?: Message;
|
|
9
|
+
interaction?: Interaction;
|
|
10
|
+
}) => Promise<void>;
|
|
11
|
+
onCommand?: (spec: {
|
|
12
|
+
slash?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
args?: Record<string, unknown>;
|
|
15
|
+
}, ctx: {
|
|
16
|
+
message?: Message;
|
|
17
|
+
interaction?: Interaction;
|
|
18
|
+
}) => Promise<void>;
|
|
19
|
+
mentionRequired?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function useDiscordAdapter(opts: DiscordAdapterOptions): void;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useDiscordAdapter = useDiscordAdapter;
|
|
4
|
+
function useDiscordAdapter(opts) {
|
|
5
|
+
const { client, relay } = opts;
|
|
6
|
+
client.on("messageCreate", async (message) => {
|
|
7
|
+
if (message.author.bot)
|
|
8
|
+
return;
|
|
9
|
+
const mentionRequired = opts.mentionRequired !== false;
|
|
10
|
+
const mentioned = !!client.user?.id && (message.mentions?.users?.has?.(client.user.id) ?? false);
|
|
11
|
+
// Typing indicator will be driven by a short loop only when addressed
|
|
12
|
+
// Detect reply-to-bot accurately
|
|
13
|
+
let isReplyToBot = false;
|
|
14
|
+
try {
|
|
15
|
+
if (message.reference?.messageId && client.user?.id) {
|
|
16
|
+
const ref = await message.channel.messages.fetch(message.reference.messageId).catch(() => null);
|
|
17
|
+
if (ref && ref.author && ref.author.id === client.user.id)
|
|
18
|
+
isReplyToBot = true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
catch { }
|
|
22
|
+
if (mentionRequired && !mentioned && !isReplyToBot)
|
|
23
|
+
return;
|
|
24
|
+
const evt = {
|
|
25
|
+
type: "messageCreate",
|
|
26
|
+
id: message.id,
|
|
27
|
+
guildId: message.guildId ?? undefined,
|
|
28
|
+
channelId: message.channelId,
|
|
29
|
+
authorId: message.author.id,
|
|
30
|
+
content: message.content,
|
|
31
|
+
timestamp: message.createdTimestamp,
|
|
32
|
+
botClientId: client.user?.id,
|
|
33
|
+
isReplyToBot,
|
|
34
|
+
referencedMessageId: message.reference?.messageId,
|
|
35
|
+
referencedMessageAuthorId: message.reference ? client.user?.id : undefined,
|
|
36
|
+
};
|
|
37
|
+
try {
|
|
38
|
+
let typingTimer = null;
|
|
39
|
+
try {
|
|
40
|
+
await message.channel?.sendTyping?.();
|
|
41
|
+
}
|
|
42
|
+
catch { }
|
|
43
|
+
typingTimer = setInterval(() => {
|
|
44
|
+
try {
|
|
45
|
+
message.channel?.sendTyping?.();
|
|
46
|
+
}
|
|
47
|
+
catch { }
|
|
48
|
+
}, 8000);
|
|
49
|
+
const dec = await relay.sendEvent(evt);
|
|
50
|
+
if (dec)
|
|
51
|
+
await (opts.execute ? opts.execute(dec, { message }) : defaultExecute(dec, { message }, opts));
|
|
52
|
+
if (typingTimer)
|
|
53
|
+
clearInterval(typingTimer);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
// swallow; user code can add logging
|
|
57
|
+
// ensure typing cleared
|
|
58
|
+
// no-op: interval cleared by GC if not set
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
client.on("interactionCreate", async (interaction) => {
|
|
62
|
+
if (!interaction.isCommand())
|
|
63
|
+
return;
|
|
64
|
+
const cmd = interaction;
|
|
65
|
+
const evt = {
|
|
66
|
+
type: "interactionCreate",
|
|
67
|
+
id: interaction.id,
|
|
68
|
+
guildId: interaction.guildId ?? undefined,
|
|
69
|
+
channelId: interaction.channelId ?? undefined,
|
|
70
|
+
userId: interaction.user.id,
|
|
71
|
+
name: cmd.commandName,
|
|
72
|
+
options: (() => {
|
|
73
|
+
const out = {};
|
|
74
|
+
try {
|
|
75
|
+
// Guard for discord.js v14 CommandInteractionOptionResolver
|
|
76
|
+
const data = cmd.options?.data || [];
|
|
77
|
+
for (const d of data)
|
|
78
|
+
out[d.name] = d.value;
|
|
79
|
+
}
|
|
80
|
+
catch { }
|
|
81
|
+
return out;
|
|
82
|
+
})(),
|
|
83
|
+
timestamp: Date.now(),
|
|
84
|
+
};
|
|
85
|
+
try {
|
|
86
|
+
const dec = await relay.sendEvent(evt);
|
|
87
|
+
if (dec)
|
|
88
|
+
await (opts.execute ? opts.execute(dec, { interaction }) : defaultExecute(dec, { interaction }, opts));
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
// swallow
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
function getByPath(root, path) {
|
|
96
|
+
if (!root || !path)
|
|
97
|
+
return undefined;
|
|
98
|
+
try {
|
|
99
|
+
return path.split('.').reduce((o, k) => (o ? o[k] : undefined), root);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function pickHandler(registry, action) {
|
|
106
|
+
if (!registry || !action)
|
|
107
|
+
return null;
|
|
108
|
+
try {
|
|
109
|
+
if (typeof registry.get === 'function') {
|
|
110
|
+
return registry.get(action) || registry.get(action.toLowerCase());
|
|
111
|
+
}
|
|
112
|
+
return registry[action] || registry[action.toLowerCase?.()];
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function runHandler(handler, message, args, rest) {
|
|
119
|
+
if (!handler)
|
|
120
|
+
return false;
|
|
121
|
+
try {
|
|
122
|
+
if (typeof handler.execute === 'function') {
|
|
123
|
+
await handler.execute(message, args, rest);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
if (typeof handler.run === 'function') {
|
|
127
|
+
await handler.run(message, args, rest);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
if (typeof handler.messageRun === 'function') {
|
|
131
|
+
await handler.messageRun(message, { args, rest });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
if (typeof handler.exec === 'function') {
|
|
135
|
+
await handler.exec(message, rest.join(' '));
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
if (typeof handler === 'function') {
|
|
139
|
+
await handler({ message, args, rest });
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// swallow; user code can add logging
|
|
145
|
+
return true; // handler existed and threw; consider handled to avoid double-processing
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
async function defaultExecute(decision, ctx, opts) {
|
|
150
|
+
const reply = decision.actions?.find(a => a.kind === "reply");
|
|
151
|
+
const command = decision.actions?.find(a => a.kind === "command");
|
|
152
|
+
if (reply) {
|
|
153
|
+
if (ctx.message) {
|
|
154
|
+
await ctx.message.reply({ content: reply.content });
|
|
155
|
+
}
|
|
156
|
+
else if (ctx.interaction && ctx.interaction.isRepliable())
|
|
157
|
+
await ctx.interaction.reply({ content: reply.content, ephemeral: reply.ephemeral ?? false });
|
|
158
|
+
}
|
|
159
|
+
if (command && ctx.message) {
|
|
160
|
+
const slash = String(command.slash || '').trim();
|
|
161
|
+
const disableBuiltins = String(process.env.COMMANDLESS_DISABLE_BUILTINS || '').toLowerCase() === 'true';
|
|
162
|
+
const registryPath = process.env.COMMAND_REGISTRY_PATH || '';
|
|
163
|
+
// If user provided explicit handler via onCommand, prefer it
|
|
164
|
+
if (opts?.onCommand) {
|
|
165
|
+
await opts.onCommand({ slash, name: command.name, args: command.args || {} }, ctx).catch(() => { });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
// Env-based auto-routing to existing registry
|
|
169
|
+
if (registryPath) {
|
|
170
|
+
const aliasesRaw = process.env.COMMAND_REGISTRY_ALIAS_JSON || '';
|
|
171
|
+
let alias = {};
|
|
172
|
+
try {
|
|
173
|
+
if (aliasesRaw)
|
|
174
|
+
alias = JSON.parse(aliasesRaw);
|
|
175
|
+
}
|
|
176
|
+
catch { }
|
|
177
|
+
const fromSlash = slash ? parseSlash(slash).action : null;
|
|
178
|
+
const base = String(command.name || fromSlash || '').toLowerCase();
|
|
179
|
+
const action = (alias[base] || base);
|
|
180
|
+
const registry = getByPath(opts?.client, registryPath);
|
|
181
|
+
const handler = pickHandler(registry, action);
|
|
182
|
+
const ok = await runHandler(handler, ctx.message, (command.args || {}), []);
|
|
183
|
+
if (ok || disableBuiltins)
|
|
184
|
+
return; // handled or built-ins disabled
|
|
185
|
+
// fallthrough to built-ins only if not disabled
|
|
186
|
+
}
|
|
187
|
+
// Default built-ins (only if not disabled)
|
|
188
|
+
if (!disableBuiltins) {
|
|
189
|
+
if (slash)
|
|
190
|
+
await executeLocalDiscordCommand(slash, ctx.message).catch(() => { });
|
|
191
|
+
else
|
|
192
|
+
await executeLocalAction(String(command.name || ''), command.args || {}, ctx.message).catch(() => { });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function executeLocalDiscordCommand(slashText, message) {
|
|
197
|
+
const { action, params } = parseSlash(slashText);
|
|
198
|
+
if (!action)
|
|
199
|
+
return;
|
|
200
|
+
try {
|
|
201
|
+
switch (action) {
|
|
202
|
+
case 'say': {
|
|
203
|
+
const content = String(params.message || params.text || params.content || '').trim();
|
|
204
|
+
const ch = message.channel;
|
|
205
|
+
if (content && ch && typeof ch.send === 'function')
|
|
206
|
+
await ch.send({ content });
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
case 'pin': {
|
|
210
|
+
let target = null;
|
|
211
|
+
if (message.reference?.messageId) {
|
|
212
|
+
try {
|
|
213
|
+
target = await message.channel.messages.fetch(message.reference.messageId);
|
|
214
|
+
}
|
|
215
|
+
catch { }
|
|
216
|
+
}
|
|
217
|
+
if (!target) {
|
|
218
|
+
const fetched = await message.channel.messages.fetch({ limit: 2 });
|
|
219
|
+
target = fetched.filter(m => m.id !== message.id).first() || fetched.first();
|
|
220
|
+
}
|
|
221
|
+
if (target && typeof target.pin === 'function')
|
|
222
|
+
await target.pin();
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case 'purge': {
|
|
226
|
+
const amt = Number(params.amount || params.n || params.count || '0');
|
|
227
|
+
if (amt > 0 && 'bulkDelete' in message.channel) {
|
|
228
|
+
await message.channel.bulkDelete(Math.min(amt, 100), true);
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
// No amount -> delete referenced/last message
|
|
232
|
+
let target = null;
|
|
233
|
+
if (message.reference?.messageId) {
|
|
234
|
+
try {
|
|
235
|
+
target = await message.channel.messages.fetch(message.reference.messageId);
|
|
236
|
+
}
|
|
237
|
+
catch { }
|
|
238
|
+
}
|
|
239
|
+
if (!target) {
|
|
240
|
+
const fetched = await message.channel.messages.fetch({ limit: 2 });
|
|
241
|
+
target = fetched.filter((m) => m.id !== message.id).first() || fetched.first();
|
|
242
|
+
}
|
|
243
|
+
if (target && typeof target.delete === 'function')
|
|
244
|
+
await target.delete().catch(() => { });
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
default:
|
|
248
|
+
// Let bots handle domain-specific actions via custom routing
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch { }
|
|
253
|
+
}
|
|
254
|
+
async function executeLocalAction(action, params, message) {
|
|
255
|
+
try {
|
|
256
|
+
switch (action) {
|
|
257
|
+
case 'say': {
|
|
258
|
+
const t = String(params.message || '').trim();
|
|
259
|
+
const ch = message.channel;
|
|
260
|
+
if (t && ch?.send)
|
|
261
|
+
await ch.send({ content: t });
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
// Add common cross-bot actions here if desired
|
|
265
|
+
default:
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch { }
|
|
270
|
+
}
|
|
271
|
+
function parseSlash(text) {
|
|
272
|
+
const out = {};
|
|
273
|
+
const t = String(text || '').trim().replace(/^\//, '');
|
|
274
|
+
if (!t)
|
|
275
|
+
return { action: null, params: out };
|
|
276
|
+
const [head, ...rest] = t.split(/\s+/);
|
|
277
|
+
let action = head.toLowerCase();
|
|
278
|
+
// parse k=v pairs
|
|
279
|
+
for (const part of rest) {
|
|
280
|
+
const m = part.match(/^([^=]+)=(.*)$/);
|
|
281
|
+
if (m)
|
|
282
|
+
out[m[1]] = m[2];
|
|
283
|
+
}
|
|
284
|
+
// also support freeform for simple commands e.g., "purge 5" or "say hello" (map to message)
|
|
285
|
+
if (!Object.keys(out).length && rest.length) {
|
|
286
|
+
if (action === 'purge' && /^\d+$/.test(rest[0]))
|
|
287
|
+
out.amount = rest[0];
|
|
288
|
+
else
|
|
289
|
+
out.message = rest.join(' ');
|
|
290
|
+
}
|
|
291
|
+
return { action, params: out };
|
|
292
|
+
}
|
package/dist-cjs/http.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.postJson = postJson;
|
|
4
|
+
const signing_js_1 = require("./signing.js");
|
|
5
|
+
async function postJson(url, apiKey, body, opts) {
|
|
6
|
+
const controller = new AbortController();
|
|
7
|
+
const timeout = setTimeout(() => controller.abort(), opts?.timeoutMs ?? 15000);
|
|
8
|
+
const json = JSON.stringify(body);
|
|
9
|
+
const headers = {
|
|
10
|
+
"content-type": "application/json",
|
|
11
|
+
// Use canonical header expected by the server; keep legacy for compatibility
|
|
12
|
+
"x-api-key": apiKey,
|
|
13
|
+
"x-commandless-key": apiKey,
|
|
14
|
+
"x-timestamp": String((0, signing_js_1.nowUnixMs)())
|
|
15
|
+
};
|
|
16
|
+
if (opts?.hmacSecret)
|
|
17
|
+
headers["x-signature"] = (0, signing_js_1.hmacSign)(json, opts.hmacSecret);
|
|
18
|
+
if (opts?.idempotencyKey)
|
|
19
|
+
headers["x-idempotency-key"] = opts.idempotencyKey;
|
|
20
|
+
try {
|
|
21
|
+
const res = await fetch(url, { method: "POST", body: json, headers, signal: controller.signal });
|
|
22
|
+
const requestId = res.headers.get("x-request-id") ?? undefined;
|
|
23
|
+
if (!res.ok) {
|
|
24
|
+
const text = await safeText(res);
|
|
25
|
+
return { ok: false, status: res.status, error: text, requestId };
|
|
26
|
+
}
|
|
27
|
+
const data = (await res.json());
|
|
28
|
+
return { ok: true, status: res.status, data, requestId };
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
return { ok: false, status: 0, error: err?.message ?? String(err) };
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
clearTimeout(timeout);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function safeText(res) {
|
|
38
|
+
try {
|
|
39
|
+
return await res.text();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return "";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./types.js"), exports);
|
|
18
|
+
__exportStar(require("./signing.js"), exports);
|
|
19
|
+
__exportStar(require("./http.js"), exports);
|
|
20
|
+
__exportStar(require("./relayClient.js"), exports);
|
|
21
|
+
__exportStar(require("./adapters/discord.js"), exports);
|
|
File without changes
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Decision, RelayClientOptions, RelayEvent } from "./types.js";
|
|
2
|
+
export declare class RelayClient {
|
|
3
|
+
private readonly apiKey;
|
|
4
|
+
private readonly baseUrl;
|
|
5
|
+
private readonly hmacSecret?;
|
|
6
|
+
private readonly timeoutMs;
|
|
7
|
+
private readonly maxRetries;
|
|
8
|
+
private readonly queue;
|
|
9
|
+
private sending;
|
|
10
|
+
private botId?;
|
|
11
|
+
constructor(opts: RelayClientOptions);
|
|
12
|
+
registerBot(info: {
|
|
13
|
+
platform: 'discord';
|
|
14
|
+
name?: string;
|
|
15
|
+
clientId?: string;
|
|
16
|
+
}): Promise<string | null>;
|
|
17
|
+
heartbeat(): Promise<void>;
|
|
18
|
+
sendEvent(event: RelayEvent): Promise<Decision | null>;
|
|
19
|
+
enqueue(event: RelayEvent): void;
|
|
20
|
+
private drain;
|
|
21
|
+
private sendWithRetry;
|
|
22
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RelayClient = void 0;
|
|
4
|
+
const http_js_1 = require("./http.js");
|
|
5
|
+
const DEFAULT_BASE = "https://api.commandless.app";
|
|
6
|
+
class RelayClient {
|
|
7
|
+
constructor(opts) {
|
|
8
|
+
this.maxRetries = 3;
|
|
9
|
+
this.queue = [];
|
|
10
|
+
this.sending = false;
|
|
11
|
+
this.apiKey = opts.apiKey;
|
|
12
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE).replace(/\/$/, "");
|
|
13
|
+
this.hmacSecret = opts.hmacSecret;
|
|
14
|
+
this.timeoutMs = opts.timeoutMs ?? 15000;
|
|
15
|
+
}
|
|
16
|
+
// Optional: register this SDK bot and obtain/confirm botId
|
|
17
|
+
async registerBot(info) {
|
|
18
|
+
try {
|
|
19
|
+
const url = `${this.baseUrl}/v1/relay/register`;
|
|
20
|
+
const res = await (0, http_js_1.postJson)(url, this.apiKey, info, {
|
|
21
|
+
hmacSecret: this.hmacSecret,
|
|
22
|
+
timeoutMs: this.timeoutMs,
|
|
23
|
+
});
|
|
24
|
+
if (res.ok && res.data?.botId) {
|
|
25
|
+
this.botId = res.data.botId;
|
|
26
|
+
return this.botId;
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Optional heartbeat to show online status
|
|
35
|
+
async heartbeat() {
|
|
36
|
+
try {
|
|
37
|
+
const url = `${this.baseUrl}/v1/relay/heartbeat`;
|
|
38
|
+
const res = await (0, http_js_1.postJson)(url, this.apiKey, { botId: this.botId }, {
|
|
39
|
+
hmacSecret: this.hmacSecret,
|
|
40
|
+
timeoutMs: this.timeoutMs,
|
|
41
|
+
});
|
|
42
|
+
// Return server response to caller (index.js checks syncRequested)
|
|
43
|
+
return res.data;
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
}
|
|
47
|
+
async sendEvent(event) {
|
|
48
|
+
// Immediate send with retries and idempotency
|
|
49
|
+
if (this.botId)
|
|
50
|
+
event.botId = this.botId;
|
|
51
|
+
return await this.sendWithRetry(event);
|
|
52
|
+
}
|
|
53
|
+
enqueue(event) {
|
|
54
|
+
this.queue.push(event);
|
|
55
|
+
if (!this.sending)
|
|
56
|
+
void this.drain();
|
|
57
|
+
}
|
|
58
|
+
async drain() {
|
|
59
|
+
this.sending = true;
|
|
60
|
+
while (this.queue.length) {
|
|
61
|
+
const evt = this.queue.shift();
|
|
62
|
+
try {
|
|
63
|
+
await this.sendWithRetry(evt);
|
|
64
|
+
}
|
|
65
|
+
catch { /* swallow to keep draining */ }
|
|
66
|
+
}
|
|
67
|
+
this.sending = false;
|
|
68
|
+
}
|
|
69
|
+
async sendWithRetry(event) {
|
|
70
|
+
const url = `${this.baseUrl}/v1/relay/events`;
|
|
71
|
+
const idem = makeIdempotencyKey(event);
|
|
72
|
+
let lastErr;
|
|
73
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
74
|
+
const res = await (0, http_js_1.postJson)(url, this.apiKey, event, {
|
|
75
|
+
hmacSecret: this.hmacSecret,
|
|
76
|
+
timeoutMs: this.timeoutMs,
|
|
77
|
+
idempotencyKey: idem,
|
|
78
|
+
});
|
|
79
|
+
if (res.ok)
|
|
80
|
+
return res.data?.decision ?? null;
|
|
81
|
+
lastErr = new Error(`Commandless error (${res.status}): ${res.error ?? "unknown"}`);
|
|
82
|
+
// basic backoff
|
|
83
|
+
await sleep(200 * (attempt + 1));
|
|
84
|
+
}
|
|
85
|
+
throw lastErr;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
exports.RelayClient = RelayClient;
|
|
89
|
+
function makeIdempotencyKey(event) {
|
|
90
|
+
// Simple stable key: type-id-timestamp buckets (can be improved)
|
|
91
|
+
const base = `${event.type}:${event.id}:${Math.floor(event.timestamp / 1000)}`;
|
|
92
|
+
return Buffer.from(base).toString("base64url");
|
|
93
|
+
}
|
|
94
|
+
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.hmacSign = hmacSign;
|
|
7
|
+
exports.nowUnixMs = nowUnixMs;
|
|
8
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
9
|
+
function hmacSign(body, secret) {
|
|
10
|
+
return crypto_1.default.createHmac("sha256", secret).update(body).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
function nowUnixMs() {
|
|
13
|
+
return Date.now();
|
|
14
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type Snowflake = string;
|
|
2
|
+
export type RelayEvent = {
|
|
3
|
+
type: "messageCreate";
|
|
4
|
+
id: string;
|
|
5
|
+
guildId?: Snowflake;
|
|
6
|
+
channelId: Snowflake;
|
|
7
|
+
authorId: Snowflake;
|
|
8
|
+
content: string;
|
|
9
|
+
timestamp: number;
|
|
10
|
+
botClientId?: Snowflake;
|
|
11
|
+
isReplyToBot?: boolean;
|
|
12
|
+
referencedMessageId?: string;
|
|
13
|
+
referencedMessageAuthorId?: Snowflake;
|
|
14
|
+
referencedMessageContent?: string;
|
|
15
|
+
} | {
|
|
16
|
+
type: "interactionCreate";
|
|
17
|
+
id: string;
|
|
18
|
+
guildId?: Snowflake;
|
|
19
|
+
channelId?: Snowflake;
|
|
20
|
+
userId: Snowflake;
|
|
21
|
+
name: string;
|
|
22
|
+
options?: Record<string, unknown>;
|
|
23
|
+
timestamp: number;
|
|
24
|
+
botClientId?: Snowflake;
|
|
25
|
+
};
|
|
26
|
+
export interface Decision {
|
|
27
|
+
id: string;
|
|
28
|
+
intent: string;
|
|
29
|
+
confidence: number;
|
|
30
|
+
params: Record<string, unknown>;
|
|
31
|
+
safety?: {
|
|
32
|
+
blocked?: boolean;
|
|
33
|
+
reasons?: string[];
|
|
34
|
+
};
|
|
35
|
+
next_step?: string;
|
|
36
|
+
actions?: Array<{
|
|
37
|
+
kind: "reply";
|
|
38
|
+
content: string;
|
|
39
|
+
ephemeral?: boolean;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "command";
|
|
42
|
+
name?: string;
|
|
43
|
+
args?: Record<string, unknown>;
|
|
44
|
+
slash?: string;
|
|
45
|
+
simulate?: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
export interface RelayClientOptions {
|
|
49
|
+
apiKey: string;
|
|
50
|
+
baseUrl?: string;
|
|
51
|
+
hmacSecret?: string;
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
}
|
|
54
|
+
export interface HttpResponse<T> {
|
|
55
|
+
ok: boolean;
|
|
56
|
+
status: number;
|
|
57
|
+
data?: T;
|
|
58
|
+
error?: string;
|
|
59
|
+
requestId?: string;
|
|
60
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@abdarrahmanabdelnasir/relay-node",
|
|
3
|
+
"version": "0.1.6",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"module": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"require": "./dist-cjs/index.cjs",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"dist-cjs",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist-cjs/package.cjs','')\" && node -e \"const fs=require('fs');fs.renameSync('dist-cjs/index.js','dist-cjs/index.cjs')\"",
|
|
24
|
+
"clean": "rimraf dist || rm -rf dist",
|
|
25
|
+
"prepublishOnly": "npm run clean && npm run build"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/GMOnyx/Commandlessapp"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/GMOnyx/Commandlessapp#readme",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/GMOnyx/Commandlessapp/issues"
|
|
39
|
+
},
|
|
40
|
+
"author": "Commandless",
|
|
41
|
+
"keywords": [
|
|
42
|
+
"commandless",
|
|
43
|
+
"discord",
|
|
44
|
+
"relay",
|
|
45
|
+
"sdk",
|
|
46
|
+
"nlp",
|
|
47
|
+
"intent"
|
|
48
|
+
],
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"discord.js": ">=14.0.0"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"rimraf": "^5.0.5",
|
|
57
|
+
"typescript": "^5.4.0"
|
|
58
|
+
}
|
|
59
|
+
}
|