@chamvi/chat-discord 0.0.0-stage → 0.7.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 +202 -0
- package/NOTICE +4 -0
- package/README.md +165 -2
- package/dist/index.d.mts +211 -0
- package/dist/index.mjs +904 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +71 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,166 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/chamvi/chamvi/master/.github/assets/logo.svg" alt="@chamvi/chat-discord" width="128" height="128" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">@chamvi/chat-discord</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<b>Discord for chamvi agents.</b><br>
|
|
9
|
+
A Gateway connection and the Chat SDK Discord adapter,<br>
|
|
10
|
+
plugged into an <code>@chamvi/chat</code> channel.
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
<p align="center">
|
|
14
|
+
<a href="https://www.npmjs.com/package/@chamvi/chat-discord"><img src="https://img.shields.io/npm/v/@chamvi/chat-discord" alt="npm version" /></a>
|
|
15
|
+
<a href="https://github.com/chamvi/chamvi/actions/workflows/ci.yml"><img src="https://github.com/chamvi/chamvi/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
|
16
|
+
<a href="https://github.com/chamvi/chamvi/blob/master/packages/chat-discord/LICENSE"><img src="https://img.shields.io/npm/l/@chamvi/chat-discord" alt="License" /></a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
**Table of Contents**
|
|
22
|
+
- [Installation](#installation)
|
|
23
|
+
- [Usage](#usage)
|
|
24
|
+
- [Limits](#limits)
|
|
25
|
+
- [Operations](#operations)
|
|
26
|
+
- [API](#api)
|
|
27
|
+
- [License](#license)
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npm install @chamvi/chat-discord @chamvi/chat @chamvi/core @chamvi/http chat @chat-adapter/discord@4.44.0 discord.js --save
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
ESM only, Node.js `>=26.0.0`. `@chamvi/chat`, `@chamvi/core`, [`chat`](https://www.npmjs.com/package/chat) (the Chat SDK, 4.44 or later in the 4.x line), `@chat-adapter/discord` and `discord.js` (14.25.1 or later in the 14.x line) are peer dependencies; `@chat-adapter/discord` is pinned to the one version chamvi was verified against (`4.44.0`). `smob` is the only runtime dependency. The package uses only `@chamvi/chat`'s public API: its channel is a `chatChannel()` with the Discord hooks passed as `platform` ([`IChatPlatform`](https://www.npmjs.com/package/@chamvi/chat#platform-packages)).
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
`createDiscordChat()` builds a Chat SDK `Chat`, the Discord adapter and its `chatChannel()`. Contribute the channel with `chatModule()`, subscribe an agent with `channel.on()` and reply from a tool with `ctx.channels.findOneOrFail('chat').emit()`:
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import type { LanguageModel } from 'ai';
|
|
43
|
+
import { z } from 'zod';
|
|
44
|
+
import { createApp, defineModelAgent, defineTool } from '@chamvi/app';
|
|
45
|
+
import type { IApp } from '@chamvi/app';
|
|
46
|
+
import { chatModule } from '@chamvi/chat/module';
|
|
47
|
+
import { createDiscordChat } from '@chamvi/chat-discord';
|
|
48
|
+
import type { DiscordChatOptions } from '@chamvi/chat-discord';
|
|
49
|
+
|
|
50
|
+
export function createDiscordApp(
|
|
51
|
+
model: LanguageModel,
|
|
52
|
+
// state: a Chat SDK state adapter
|
|
53
|
+
options: Pick<DiscordChatOptions, 'state' | 'clientFactory' | 'fetch'>,
|
|
54
|
+
): IApp {
|
|
55
|
+
const {
|
|
56
|
+
DISCORD_BOT_TOKEN,
|
|
57
|
+
DISCORD_APPLICATION_ID,
|
|
58
|
+
DISCORD_GUILD_ID,
|
|
59
|
+
DISCORD_USER_IDS,
|
|
60
|
+
APP_URL,
|
|
61
|
+
} = process.env;
|
|
62
|
+
|
|
63
|
+
if (!DISCORD_BOT_TOKEN || !DISCORD_APPLICATION_ID || !DISCORD_GUILD_ID || !DISCORD_USER_IDS || !APP_URL) {
|
|
64
|
+
throw new Error('Set DISCORD_BOT_TOKEN, DISCORD_APPLICATION_ID, DISCORD_GUILD_ID, DISCORD_USER_IDS (comma separated) and APP_URL.');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const discord = createDiscordChat({
|
|
68
|
+
// a non-secret alias of the bot (the conversation account)
|
|
69
|
+
account: 'assistant',
|
|
70
|
+
// read from the environment per login and per send; never stored or logged
|
|
71
|
+
token: async () => process.env.DISCORD_BOT_TOKEN ?? '',
|
|
72
|
+
applicationId: DISCORD_APPLICATION_ID,
|
|
73
|
+
// ids only: these users in this guild, when they mention the bot or reply to it
|
|
74
|
+
policy: { guilds: [DISCORD_GUILD_ID], users: DISCORD_USER_IDS.split(',').map((id) => id.trim()) },
|
|
75
|
+
resolveInvoker: (identity) => ({
|
|
76
|
+
id: identity.author,
|
|
77
|
+
kind: 'discord',
|
|
78
|
+
permissions: [],
|
|
79
|
+
}),
|
|
80
|
+
// a link to the approval in the chamvi UI: ids only, answered there
|
|
81
|
+
approvalUrl: ({ runId, approvalId }) => `${APP_URL}/ui/approvals?run=${encodeURIComponent(runId)}&approval=${encodeURIComponent(approvalId)}`,
|
|
82
|
+
...options,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const reply = defineTool({
|
|
86
|
+
description: 'Reply in the channel or thread the message came from.',
|
|
87
|
+
inputSchema: z.object({ text: z.string() }),
|
|
88
|
+
execute: async ({ text }, { context }) => {
|
|
89
|
+
// the source channel or thread: no address needed, and the reply pings nobody
|
|
90
|
+
await context.channels.findOneOrFail('chat').emit({ body: text });
|
|
91
|
+
|
|
92
|
+
return 'sent';
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const assistant = defineModelAgent({
|
|
97
|
+
name: 'assistant',
|
|
98
|
+
model,
|
|
99
|
+
instructions: 'You are the team\'s assistant on Discord. Answer with the reply tool.',
|
|
100
|
+
// one memory per thread and one per channel's top-level messages
|
|
101
|
+
conversation: true,
|
|
102
|
+
// mentions and replies in an allowed guild
|
|
103
|
+
channels: [discord.channel.on()],
|
|
104
|
+
tools: { reply },
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// chatModule() contributes the channel; the engine starts and stops it
|
|
108
|
+
return createApp({
|
|
109
|
+
agents: [assistant],
|
|
110
|
+
modules: [chatModule({ channel: discord.channel })],
|
|
111
|
+
conversations: { authorize: ({ agent }) => agent === 'assistant' },
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
The app entry's default export is `createDiscordApp(model, { state })`. Nothing connects when the setup is built, and `chamvi start --check` reads no token and makes no client: the channel's `start` (the engine's) initializes the Chat, then logs one discord.js client in to the Gateway (intents `Guilds`, `GuildMessages`, `MessageContent`, `DirectMessages`). `setup.status()` reports `stopped`, `connecting`, `connected`, `disconnected` or `failed`, from the client's events only.
|
|
117
|
+
|
|
118
|
+
`token` is the bot token or an async provider of it, read per login and per send; it never reaches a store, a run, a log, `onError` or an error message. `state` is a Chat SDK `StateAdapter`; chamvi's intake does not depend on its deduplication.
|
|
119
|
+
|
|
120
|
+
Who may start runs is `policy`, by Discord ids (snowflakes) only, never by names:
|
|
121
|
+
|
|
122
|
+
| Policy | Allows |
|
|
123
|
+
|---|---|
|
|
124
|
+
| `guilds: [...]` | Required. Guild messages only from these guilds (empty: no guild intake) |
|
|
125
|
+
| `channels: [...]` | Narrows the guilds to these channels; a thread matches by its parent channel (a parent discord.js does not know is looked up once) |
|
|
126
|
+
| `users: [...]`, `roles: [...]` | Authors by user id, or by one of their member role ids; with neither, no guild author passes |
|
|
127
|
+
| `dms: { users: [...] }` | Direct messages of these users (default `false`: no DMs); group DMs are refused |
|
|
128
|
+
| `requireMention` | Default `true`: a guild message must mention the bot user directly or reply to a bot message (`@everyone`, `@here` and role mentions do not count) |
|
|
129
|
+
|
|
130
|
+
A message starts runs only when the policy allows it and `resolveInvoker` names an invoker. The bot's own messages, other bots, webhooks and everything the policy refuses are dropped silently, before any other work: no run, no reply, no thread, no Discord call.
|
|
131
|
+
|
|
132
|
+
Subscriptions, replies, approvals, memory and trust follow [`@chamvi/chat`](https://www.npmjs.com/package/@chamvi/chat): the conversation of a message is `{ account, thread id, audience }` with the audience `direct:<user>` for a DM, `channel:<parent channel>` for a guild channel and its public threads, `thread:<thread>` for a private thread or one whose type is unknown. A thread is one memory, a channel's top-level messages another (no threads are created).
|
|
133
|
+
|
|
134
|
+
## Limits
|
|
135
|
+
|
|
136
|
+
- Text only: messages with attachments or no text are refused (reported, no run); replies are text up to 2000 characters (`DISCORD_TEXT_MAX_CHARS`), never split. No buttons, embeds, reactions, edits or slash commands; approvals are a link into the UI.
|
|
137
|
+
- Replies never ping: every send carries `allowed_mentions: { parse: [] }`.
|
|
138
|
+
- Delivery is at least once: each send carries a nonce derived from the channel name, the target channel or thread and the message key with `enforce_nonce`, so a retry within Discord's nonce window returns the first message instead of posting a copy; beyond it a retry may post again. A rate-limited (429) or failed send is `chat_request`, without the token; chamvi has no retry loop of its own.
|
|
139
|
+
- No lossless or offline ingestion. A message that arrives while the connector is down is not fetched later.
|
|
140
|
+
|
|
141
|
+
## Operations
|
|
142
|
+
|
|
143
|
+
Read the [Discord guide](https://chamvi.dev/deployment/discord) before going live. In short:
|
|
144
|
+
|
|
145
|
+
- **Developer Portal.** Enable the **Message Content** privileged intent; without it the login fails with `discord_connection`. Invite the bot with View Channel, Send Messages, Send Messages in Threads and Read Message History. Leave the **Interactions Endpoint URL** empty: setting it diverts interactions away from the Gateway, and chamvi serves no endpoint.
|
|
146
|
+
- **One connector per bot token.** Run one deployment, `Recreate`/stop-then-start, never two replicas.
|
|
147
|
+
- **Login**: an invalid or empty token (or a failing provider) is `discord_auth`, disallowed intents and an invalidated session `discord_connection`; neither retries. Other login failures retry with backoff (`DISCORD_RECONNECT`: 2 s growing to 30 s, 12 attempts); discord.js resumes and reconnects an established session by itself.
|
|
148
|
+
- **Stop** destroys the client within `DISCORD_SHUTDOWN_TIMEOUT_MS` (30 s) and never reconnects after.
|
|
149
|
+
- **Sends** go through Discord REST, independent of the Gateway status.
|
|
150
|
+
|
|
151
|
+
## API
|
|
152
|
+
|
|
153
|
+
| Export | Holds |
|
|
154
|
+
|---|---|
|
|
155
|
+
| `createDiscordChat(options)` | `{ chat, ingress, channel, status() }` |
|
|
156
|
+
| Types `DiscordChatOptions`, `DiscordChatSetup`, `DiscordPolicy`, `DiscordIdentity`, `DiscordConnectionStatus`, `DiscordClient`, `DiscordClientFactory`, `DiscordInboundMessage`, `DiscordInboundAttachment` | |
|
|
157
|
+
| `DISCORD_ADAPTER_NAME` `'discord'`, `DISCORD_API_URL`, `DISCORD_TEXT_MAX_CHARS` 2000, `DISCORD_RECONNECT`, `DISCORD_SHUTDOWN_TIMEOUT_MS` 30 000 | |
|
|
158
|
+
| Error codes `discord_auth`, `discord_connection` (`DISCORD_*_ERROR_CODE`) | |
|
|
159
|
+
|
|
160
|
+
The full option reference is the [Discord guide](https://chamvi.dev/deployment/discord).
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
Made with 💚
|
|
165
|
+
|
|
166
|
+
Published under [Apache License 2.0](./LICENSE).
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import "@chat-adapter/discord";
|
|
2
|
+
import { ClientOptions } from "discord.js";
|
|
3
|
+
import { Chat, Logger, StateAdapter } from "chat";
|
|
4
|
+
import { IClock, Invoker } from "@chamvi/core";
|
|
5
|
+
import { ChatApprovalRef, ChatChannel, ChatIngress } from "@chamvi/chat";
|
|
6
|
+
/** The adapter's name: thread ids are `discord:<guild | @me>:<channel>[:<thread>]`. */
|
|
7
|
+
export declare const DISCORD_ADAPTER_NAME = "discord";
|
|
8
|
+
/** The Discord REST base every send goes to unless `apiUrl` overrides it. */
|
|
9
|
+
export declare const DISCORD_API_URL = "https://discord.com/api/v10";
|
|
10
|
+
/** Discord's bound on a message's content, in characters. */
|
|
11
|
+
export declare const DISCORD_TEXT_MAX_CHARS = 2000;
|
|
12
|
+
/**
|
|
13
|
+
* Re-create the client after a transient login failure: attempt n (0-based)
|
|
14
|
+
* waits `min(maxMs, initialMs * factor^n)`, scaled by a random factor in
|
|
15
|
+
* `1 ± jitter` and capped at `maxMs`; after `maxAttempts` failed attempts in a
|
|
16
|
+
* row (a ready resets the count) the connection stays failed.
|
|
17
|
+
*/
|
|
18
|
+
export declare const DISCORD_RECONNECT: Readonly<{
|
|
19
|
+
initialMs: 2000;
|
|
20
|
+
factor: 1.8;
|
|
21
|
+
maxMs: 30000;
|
|
22
|
+
jitter: 0.25;
|
|
23
|
+
maxAttempts: 12;
|
|
24
|
+
}>;
|
|
25
|
+
/** The bound on destroying the client when the channel stops. */
|
|
26
|
+
export declare const DISCORD_SHUTDOWN_TIMEOUT_MS = 30000;
|
|
27
|
+
/** The bot token was refused, empty, or its provider failed: nothing reconnects. */
|
|
28
|
+
export declare const DISCORD_AUTH_ERROR_CODE = "discord_auth";
|
|
29
|
+
/** The connection gave up: disallowed intents, an invalidated session, or reconnects exhausted. */
|
|
30
|
+
export declare const DISCORD_CONNECTION_ERROR_CODE = "discord_connection";
|
|
31
|
+
/** Who may start runs: Discord ids (snowflakes) only, never names. */
|
|
32
|
+
type DiscordPolicy = {
|
|
33
|
+
/** Guilds whose messages may start runs; empty: no guild intake. */
|
|
34
|
+
guilds: readonly string[];
|
|
35
|
+
/** Narrows guild intake to these channels; a thread matches by its parent channel id. */
|
|
36
|
+
channels?: readonly string[];
|
|
37
|
+
/** Author ids allowed in the guilds. */
|
|
38
|
+
users?: readonly string[];
|
|
39
|
+
/** Author role ids (from the Gateway member payload) allowed in the guilds. */
|
|
40
|
+
roles?: readonly string[];
|
|
41
|
+
/** Direct messages from these user ids; default false (no DMs). */
|
|
42
|
+
dms?: {
|
|
43
|
+
users: readonly string[];
|
|
44
|
+
} | false;
|
|
45
|
+
/** A guild message must mention the bot or reply to it; default true. */
|
|
46
|
+
requireMention?: boolean;
|
|
47
|
+
};
|
|
48
|
+
/** The identity of one incoming message, as the policy and resolveInvoker see it: ids only. */
|
|
49
|
+
type DiscordIdentity = {
|
|
50
|
+
/** The operator's account alias. */
|
|
51
|
+
account: string;
|
|
52
|
+
/** The adapter thread id: `discord:<guild | @me>:<channel>[:<thread>]`. */
|
|
53
|
+
chat: string;
|
|
54
|
+
/** undefined for a DM */
|
|
55
|
+
guild?: string;
|
|
56
|
+
/** The parent channel of a thread (the thread's own id when its parent is unknown), else the message's channel. */
|
|
57
|
+
channel: string;
|
|
58
|
+
/** The thread a message was written in. */
|
|
59
|
+
thread?: string;
|
|
60
|
+
/** For a thread: true private, false public or announcement, undefined when unknown. */
|
|
61
|
+
privateThread?: boolean;
|
|
62
|
+
/** The author's user id. */
|
|
63
|
+
author: string;
|
|
64
|
+
/** The author's member role ids (empty in a DM). */
|
|
65
|
+
roles: readonly string[];
|
|
66
|
+
dm: boolean;
|
|
67
|
+
/** The bot user is mentioned directly, or the message replies to the bot. */
|
|
68
|
+
mentioned: boolean;
|
|
69
|
+
};
|
|
70
|
+
/** An attachment as chamvi reads it (a discord.js Attachment is one). */
|
|
71
|
+
type DiscordInboundAttachment = {
|
|
72
|
+
id: string;
|
|
73
|
+
name: string;
|
|
74
|
+
contentType: string | null;
|
|
75
|
+
size: number;
|
|
76
|
+
url: string;
|
|
77
|
+
proxyURL: string;
|
|
78
|
+
width: number | null;
|
|
79
|
+
height: number | null;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* The members of a discord.js `Message` chamvi reads, structurally, so a fake
|
|
83
|
+
* needs no discord.js runtime (a discord.js Message is one).
|
|
84
|
+
*/
|
|
85
|
+
type DiscordInboundMessage = {
|
|
86
|
+
id: string;
|
|
87
|
+
type: number;
|
|
88
|
+
content: string;
|
|
89
|
+
createdAt: Date;
|
|
90
|
+
editedAt: Date | null;
|
|
91
|
+
webhookId: string | null;
|
|
92
|
+
guildId: string | null;
|
|
93
|
+
channelId: string;
|
|
94
|
+
author: {
|
|
95
|
+
id: string;
|
|
96
|
+
bot: boolean;
|
|
97
|
+
username: string;
|
|
98
|
+
globalName: string | null;
|
|
99
|
+
};
|
|
100
|
+
member?: {
|
|
101
|
+
roles: {
|
|
102
|
+
cache: {
|
|
103
|
+
keys(): Iterable<string>;
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
} | null;
|
|
107
|
+
mentions: {
|
|
108
|
+
users: {
|
|
109
|
+
has(id: string): boolean;
|
|
110
|
+
};
|
|
111
|
+
repliedUser?: {
|
|
112
|
+
id: string;
|
|
113
|
+
} | null;
|
|
114
|
+
};
|
|
115
|
+
attachments: {
|
|
116
|
+
values(): Iterable<DiscordInboundAttachment>;
|
|
117
|
+
};
|
|
118
|
+
channel: DiscordInboundChannel;
|
|
119
|
+
};
|
|
120
|
+
/** The channel of an incoming message; `fetch()` loads a partial one (a thread whose parent is unknown). */
|
|
121
|
+
type DiscordInboundChannel = {
|
|
122
|
+
type: number;
|
|
123
|
+
isThread(): boolean;
|
|
124
|
+
parentId?: string | null;
|
|
125
|
+
fetch?(): Promise<DiscordInboundChannel>;
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* The Gateway connection's state: `failed` is terminal (an invalid token,
|
|
129
|
+
* disallowed intents, an invalidated session, reconnects exhausted) until the
|
|
130
|
+
* channel starts again.
|
|
131
|
+
*/
|
|
132
|
+
type DiscordConnectionStatus = 'stopped' | 'connecting' | 'connected' | 'disconnected' | 'failed';
|
|
133
|
+
/** The members of a discord.js `Client` chamvi uses (a Client is one). */
|
|
134
|
+
type DiscordClient = {
|
|
135
|
+
on(event: string, listener: (...args: any[]) => void): unknown;
|
|
136
|
+
off(event: string, listener: (...args: any[]) => void): unknown;
|
|
137
|
+
login(token: string): Promise<string>;
|
|
138
|
+
destroy(): Promise<void> | void;
|
|
139
|
+
readonly user: {
|
|
140
|
+
id: string;
|
|
141
|
+
} | null;
|
|
142
|
+
};
|
|
143
|
+
/** Makes a client; default `new Client(options)` of discord.js (tests pass a fake). */
|
|
144
|
+
type DiscordClientFactory = (options: ClientOptions) => DiscordClient;
|
|
145
|
+
type DiscordChatOptions = {
|
|
146
|
+
/** The operator's non-secret alias of the bot (the conversation account). */
|
|
147
|
+
account: string;
|
|
148
|
+
/** The bot token, or a provider read per login and per send (never in a store, run, log or error). */
|
|
149
|
+
token: string | (() => Promise<string>);
|
|
150
|
+
/** The bot's application id (a snowflake). */
|
|
151
|
+
applicationId: string;
|
|
152
|
+
/** Who may start runs: ids only; unknown guilds, channels and users are denied. */
|
|
153
|
+
policy: DiscordPolicy;
|
|
154
|
+
/** The invoker of an allowed message's runs; undefined denies the message. */
|
|
155
|
+
resolveInvoker: (identity: DiscordIdentity) => Invoker | undefined | Promise<Invoker | undefined>;
|
|
156
|
+
/** The Chat SDK state adapter of the Chat. */
|
|
157
|
+
state: StateAdapter;
|
|
158
|
+
/** The approval link (ids only); approvals are answered in the UI. */
|
|
159
|
+
approvalUrl: (ref: ChatApprovalRef) => string;
|
|
160
|
+
/** Default `chat`. */
|
|
161
|
+
name?: string;
|
|
162
|
+
/** Default true (runs are tainted). */
|
|
163
|
+
untrusted?: boolean;
|
|
164
|
+
/** Bound of one send; default `CHAT_TIMEOUT_MS`. */
|
|
165
|
+
timeoutMs?: number;
|
|
166
|
+
/** The connector's clock (login retry backoff, shutdown bound); default the engine's. */
|
|
167
|
+
clock?: IClock;
|
|
168
|
+
/** Failures nobody awaits; default console.error. Never gets the token. */
|
|
169
|
+
onError?: (error: unknown) => void;
|
|
170
|
+
/** The logger of the Chat and the adapter; default a console logger at level `warn`. */
|
|
171
|
+
logger?: Logger;
|
|
172
|
+
/** The Chat's bot user name; default `chamvi`. */
|
|
173
|
+
userName?: string;
|
|
174
|
+
/** The Discord REST base; default DISCORD_API_URL. */
|
|
175
|
+
apiUrl?: string;
|
|
176
|
+
/** Makes the discord.js client; default `new Client(options)` (tests pass a fake). */
|
|
177
|
+
clientFactory?: DiscordClientFactory;
|
|
178
|
+
/** The fetch of the REST send; default the global fetch. */
|
|
179
|
+
fetch?: typeof fetch;
|
|
180
|
+
};
|
|
181
|
+
type DiscordChatSetup = {
|
|
182
|
+
chat: Chat;
|
|
183
|
+
ingress: ChatIngress;
|
|
184
|
+
channel: ChatChannel;
|
|
185
|
+
status(): DiscordConnectionStatus;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Discord as a chat channel: a Chat SDK Chat with `@chat-adapter/discord`
|
|
189
|
+
* (initialize, parsing, thread ids only) wrapped by createChatIngressAdapter(),
|
|
190
|
+
* and its chatChannel() bounded at DISCORD_TEXT_MAX_CHARS (2000). Nothing is
|
|
191
|
+
* read or connected here (a factory or `start --check` reads no token and
|
|
192
|
+
* makes no client): the channel's start initializes the Chat, then the
|
|
193
|
+
* connection logs one discord.js client in to the Gateway; its stop destroys
|
|
194
|
+
* the client. `status()` follows the client's events.
|
|
195
|
+
*
|
|
196
|
+
* Inbound, per Gateway message: the bot's own, bot and webhook messages are
|
|
197
|
+
* dropped, then the policy decides on ids alone (DiscordPolicy) before any
|
|
198
|
+
* other work, so a refused message leaves no trace on Discord; an allowed one
|
|
199
|
+
* is parsed by the adapter's public parseMessage(), rebuilt with its thread id
|
|
200
|
+
* and mention verdict, and handed to the facade's processMessage, one after
|
|
201
|
+
* another per channel or thread. `resolveInvoker` names the invoker
|
|
202
|
+
* (undefined denies). An agent with `conversation` gets
|
|
203
|
+
* `{ account, thread id, direct:<user> | channel:<parent> | thread:<thread> }`.
|
|
204
|
+
*
|
|
205
|
+
* Outbound is chamvi's own REST send (createDiscordSender): no pings, a nonce
|
|
206
|
+
* per message key with `enforce_nonce`, abortable at the send deadline,
|
|
207
|
+
* independent of the Gateway status. Delivery is at least once.
|
|
208
|
+
*/
|
|
209
|
+
export declare function createDiscordChat(options: DiscordChatOptions): DiscordChatSetup;
|
|
210
|
+
export type { DiscordChatOptions, DiscordChatSetup, DiscordClient, DiscordClientFactory, DiscordConnectionStatus, DiscordIdentity, DiscordInboundAttachment, DiscordInboundMessage, DiscordPolicy };
|
|
211
|
+
//# sourceMappingURL=index.d.mts.map
|