omp-superagent 0.0.0-stage → 0.1.2
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/DESIGN.md +1502 -0
- package/LICENSE +21 -0
- package/README.ko.md +198 -0
- package/README.md +224 -2
- package/THIRD_PARTY_NOTICES.md +388 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1178 -0
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +65 -4
- package/scripts/ci.ts +33 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +58 -0
- package/scripts/setup.sh +25 -0
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +100 -0
- package/skills/head/references/model-selection.md +83 -0
- package/skills/head/references/routing.md +181 -0
- package/skills/head/references/supervision.md +122 -0
- package/skills/lane/SKILL.md +66 -0
- package/skills/lane/references/workflow.md +95 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +253 -0
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +266 -0
- package/src/contracts.ts +381 -0
- package/src/credentials.ts +172 -0
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +17 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +1012 -0
- package/src/extension.ts +446 -0
- package/src/gateway-client.ts +229 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +440 -0
- package/src/gateway-store.ts +251 -0
- package/src/gateway.ts +654 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +561 -0
- package/src/host-owner.ts +366 -0
- package/src/host-protocol.ts +144 -0
- package/src/host-services.ts +54 -0
- package/src/host.ts +415 -0
- package/src/installed-omp.ts +71 -0
- package/src/lane-extension.ts +184 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/lane-rows.ts +12 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +143 -0
- package/src/native-presets.ts +370 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +131 -0
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +4229 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +779 -0
- package/src/store.ts +862 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +677 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import type { VoiceConnectionState, VoiceWebSocket } from "@discordjs/voice";
|
|
2
|
+
import { Events, type VoiceChannel, type VoiceState } from "discord.js";
|
|
3
|
+
import type OpusScript from "opusscript";
|
|
4
|
+
|
|
5
|
+
const PCM_RATE = 24_000;
|
|
6
|
+
const FRAME_MS = 20;
|
|
7
|
+
const FRAME_SAMPLES = PCM_RATE * FRAME_MS / 1_000;
|
|
8
|
+
const FRAME_BYTES = FRAME_SAMPLES * 2;
|
|
9
|
+
const MAX_PLAYBACK_BYTES = PCM_RATE * 2 * 20;
|
|
10
|
+
const TAIL_WAIT_MS = 2 * FRAME_MS;
|
|
11
|
+
const SILENCE = Buffer.from([0xf8, 0xff, 0xfe]);
|
|
12
|
+
const OPUS_RESET_STATE = 4028;
|
|
13
|
+
|
|
14
|
+
class VoiceLinkError extends Error {
|
|
15
|
+
override readonly name = "VoiceLinkError";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type VoiceHandlers = {
|
|
19
|
+
readonly audio: (pcm: Buffer) => void;
|
|
20
|
+
readonly ended: () => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export async function openVoiceLink(
|
|
24
|
+
channel: VoiceChannel, ownerId: string, handlers: VoiceHandlers, signal: AbortSignal,
|
|
25
|
+
): Promise<{ play(pcm: Buffer): void; clear(): void; close(): void }> {
|
|
26
|
+
signal.throwIfAborted();
|
|
27
|
+
const { client, guild } = channel;
|
|
28
|
+
const bot = client.user;
|
|
29
|
+
if (!bot || bot.id === ownerId) throw new VoiceLinkError("Discord voice requires the authenticated bot and a separate owner");
|
|
30
|
+
const botId = bot.id;
|
|
31
|
+
const guildLoss = [Events.GuildUnavailable, Events.GuildDelete] as const;
|
|
32
|
+
|
|
33
|
+
// Voice states include occupants whose GuildMember isn't cached. channel.members omits those.
|
|
34
|
+
function privateRoom(botRequired: boolean): boolean {
|
|
35
|
+
if (!client.isReady() || !guild.available || guild.voiceStates.cache.get(ownerId)?.channelId !== channel.id) return false;
|
|
36
|
+
const botChannel = guild.voiceStates.cache.get(botId)?.channelId;
|
|
37
|
+
return (botRequired ? botChannel === channel.id : !botChannel || botChannel === channel.id) &&
|
|
38
|
+
!guild.voiceStates.cache.some(state => state.channelId === channel.id && state.id !== ownerId && state.id !== botId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!privateRoom(false)) throw new VoiceLinkError("Discord voice requires the owner alone in the target channel");
|
|
42
|
+
const [sdk, { default: Opus }] = await Promise.all([
|
|
43
|
+
import("@discordjs/voice"), import("opusscript"),
|
|
44
|
+
]).catch((cause: unknown) => { throw new VoiceLinkError("Discord voice needs the optional Voice SDK, DAVE binding, and Opus codec", { cause }); });
|
|
45
|
+
signal.throwIfAborted();
|
|
46
|
+
if (!privateRoom(false)) throw new VoiceLinkError("Discord voice membership changed before joining");
|
|
47
|
+
if (guild.voiceStates.cache.get(botId)?.channelId || sdk.getVoiceConnection(guild.id) || client.voice.adapters.has(guild.id)) {
|
|
48
|
+
throw new VoiceLinkError("The Discord bot is already connected to voice in this server");
|
|
49
|
+
}
|
|
50
|
+
if (!channel.joinable || !channel.speakable) throw new VoiceLinkError("The Discord bot needs permission to join and speak");
|
|
51
|
+
|
|
52
|
+
const connection = sdk.joinVoiceChannel({
|
|
53
|
+
channelId: channel.id, guildId: guild.id, adapterCreator: guild.voiceAdapterCreator,
|
|
54
|
+
selfDeaf: false, selfMute: false, daveEncryption: true,
|
|
55
|
+
});
|
|
56
|
+
const setup = AbortSignal.any([signal, AbortSignal.timeout(15_000)]);
|
|
57
|
+
const ready = Promise.withResolvers<void>();
|
|
58
|
+
let phase: "joining" | "open" | "closed" = "joining";
|
|
59
|
+
let closeReason: unknown;
|
|
60
|
+
let ws: VoiceWebSocket | undefined;
|
|
61
|
+
let receiver: ReturnType<typeof connection.receiver.subscribe> | undefined;
|
|
62
|
+
let decoder: OpusScript | undefined;
|
|
63
|
+
let encoder: OpusScript | undefined;
|
|
64
|
+
let speaking = false;
|
|
65
|
+
let heardOwnerOnVoiceGateway = false;
|
|
66
|
+
const queued = Buffer.allocUnsafe(MAX_PLAYBACK_BYTES);
|
|
67
|
+
const stereo = Buffer.allocUnsafe(FRAME_BYTES * 4);
|
|
68
|
+
let readAt = 0;
|
|
69
|
+
let bytes = 0;
|
|
70
|
+
let lastAudioAt = 0;
|
|
71
|
+
let previous: number | undefined;
|
|
72
|
+
let silenceFrames = 0;
|
|
73
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
74
|
+
|
|
75
|
+
function terminate(reason: unknown, notify = true): void {
|
|
76
|
+
if (phase === "closed") return;
|
|
77
|
+
const wasOpen = phase === "open";
|
|
78
|
+
phase = "closed";
|
|
79
|
+
closeReason = reason;
|
|
80
|
+
clearTimeout(timer);
|
|
81
|
+
signal.removeEventListener("abort", onAbort);
|
|
82
|
+
setup.removeEventListener("abort", onAbort);
|
|
83
|
+
client.off(Events.VoiceStateUpdate, onVoiceState);
|
|
84
|
+
for (const event of guildLoss) client.off(event, onGuildLost);
|
|
85
|
+
client.off(Events.ChannelDelete, onChannelLost);
|
|
86
|
+
client.off(Events.ShardReconnecting, onShardLost);
|
|
87
|
+
connection.off("stateChange", onConnectionState);
|
|
88
|
+
connection.off("transitioned", refresh);
|
|
89
|
+
ws?.off("packet", refresh).off("binary", refresh);
|
|
90
|
+
connection.receiver.speaking.off("end", onSpeechEnd);
|
|
91
|
+
receiver?.destroy();
|
|
92
|
+
decoder?.delete();
|
|
93
|
+
encoder?.delete();
|
|
94
|
+
// The SDK may still be inside its state setter (which can send a rejoin after
|
|
95
|
+
// emitting stateChange). Stop media here, then destroy after its stack unwinds.
|
|
96
|
+
queueMicrotask(() => {
|
|
97
|
+
try {
|
|
98
|
+
if (connection.state.status !== sdk.VoiceConnectionStatus.Destroyed) connection.destroy();
|
|
99
|
+
} finally {
|
|
100
|
+
connection.off("error", terminate);
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
if (!wasOpen) ready.reject(reason);
|
|
104
|
+
else if (notify) handlers.ended();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function refresh(): boolean {
|
|
108
|
+
if (phase === "closed") return false;
|
|
109
|
+
const state = connection.state;
|
|
110
|
+
const network = state.status === sdk.VoiceConnectionStatus.Ready ? state.networking.state : undefined;
|
|
111
|
+
const voice = network?.code === sdk.NetworkingStatusCode.Ready ? network : undefined;
|
|
112
|
+
const peers = voice?.connectionData.connectedClients;
|
|
113
|
+
const unexpectedPeer = peers && (
|
|
114
|
+
(heardOwnerOnVoiceGateway && !peers.has(ownerId)) || [...peers].some(id => id !== ownerId && id !== botId)
|
|
115
|
+
);
|
|
116
|
+
if (!privateRoom(phase === "open") || unexpectedPeer) return rejectMedia("Discord voice membership changed");
|
|
117
|
+
heardOwnerOnVoiceGateway ||= peers?.has(ownerId) ?? false;
|
|
118
|
+
if (voice?.ws !== ws) {
|
|
119
|
+
ws?.off("packet", refresh).off("binary", refresh);
|
|
120
|
+
ws = voice?.ws;
|
|
121
|
+
ws?.on("packet", refresh).on("binary", refresh);
|
|
122
|
+
}
|
|
123
|
+
const dave = voice?.dave;
|
|
124
|
+
const session = dave?.session;
|
|
125
|
+
// The SDK's SessionMethods omits the native binding's group membership API.
|
|
126
|
+
const members: unknown = session?.ready && "getUserIds" in session &&
|
|
127
|
+
typeof session.getUserIds === "function" && session.getUserIds();
|
|
128
|
+
if (Array.isArray(members) && members.some(id => id !== botId && id !== ownerId)) {
|
|
129
|
+
return rejectMedia("Discord voice encryption group membership changed");
|
|
130
|
+
}
|
|
131
|
+
const encryptedPair = voice?.connectionOptions.channelId === channel.id &&
|
|
132
|
+
dave && dave.protocolVersion > 0 && dave.lastTransitionId !== undefined && !dave.reinitializing &&
|
|
133
|
+
Array.isArray(members) && members.length === 2 && members.includes(ownerId) && members.includes(botId);
|
|
134
|
+
if (!encryptedPair || !privateRoom(true)) {
|
|
135
|
+
return phase === "open" ? rejectMedia("Discord voice lost the verified owner-only encrypted connection") : false;
|
|
136
|
+
}
|
|
137
|
+
ready.resolve();
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function rejectMedia(message: string): false {
|
|
142
|
+
terminate(new VoiceLinkError(message));
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function onVoiceState(oldState: VoiceState, newState: VoiceState): void {
|
|
147
|
+
if (newState.guild.id !== guild.id) return;
|
|
148
|
+
if (oldState.channelId !== newState.channelId &&
|
|
149
|
+
(newState.id === ownerId || (newState.id === botId && newState.channelId !== channel.id) ||
|
|
150
|
+
(newState.id !== botId && newState.channelId === channel.id))) {
|
|
151
|
+
terminate(new VoiceLinkError("Discord voice membership changed"));
|
|
152
|
+
} else refresh();
|
|
153
|
+
}
|
|
154
|
+
function onConnectionState(oldState: VoiceConnectionState, state: VoiceConnectionState): void {
|
|
155
|
+
if (state.status === sdk.VoiceConnectionStatus.Destroyed || state.status === sdk.VoiceConnectionStatus.Disconnected ||
|
|
156
|
+
(oldState.status === sdk.VoiceConnectionStatus.Ready && state.status !== sdk.VoiceConnectionStatus.Ready)) {
|
|
157
|
+
terminate(new VoiceLinkError("Discord voice disconnected"));
|
|
158
|
+
} else refresh();
|
|
159
|
+
}
|
|
160
|
+
function onGuildLost(lost: { readonly id: string }): void { if (lost.id === guild.id) terminate(new VoiceLinkError("Discord voice server became unavailable")); }
|
|
161
|
+
function onChannelLost(lost: { readonly id: string }): void { if (lost.id === channel.id) terminate(new VoiceLinkError("Discord voice channel was deleted")); }
|
|
162
|
+
function onShardLost(id: number): void { if (id === guild.shardId) terminate(new VoiceLinkError("Discord voice gateway disconnected")); }
|
|
163
|
+
function onAbort(): void { terminate(signal.aborted ? signal.reason : new VoiceLinkError("Timed out waiting for owner-only encrypted Discord voice")); }
|
|
164
|
+
function onSpeechEnd(id: string): void { if (id === ownerId) speaking = false; }
|
|
165
|
+
|
|
166
|
+
function schedule(now = performance.now()): void {
|
|
167
|
+
if (phase === "open" && timer === undefined && (bytes >= 2 || silenceFrames > 0)) {
|
|
168
|
+
timer = setTimeout(send, Math.max(0, FRAME_MS - (performance.now() - now)));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function send(): void {
|
|
173
|
+
const now = performance.now();
|
|
174
|
+
timer = undefined;
|
|
175
|
+
if (!encoder || !refresh()) return;
|
|
176
|
+
try {
|
|
177
|
+
const sampleBytes = Math.min(FRAME_BYTES, bytes - (bytes % 2));
|
|
178
|
+
if (sampleBytes === FRAME_BYTES || (sampleBytes > 0 && now - lastAudioAt >= TAIL_WAIT_MS)) {
|
|
179
|
+
for (let offset = 0; offset < FRAME_BYTES; offset += 2) {
|
|
180
|
+
const index = (readAt + offset) % queued.length;
|
|
181
|
+
const sample = offset < sampleBytes ? queued.readInt16LE(index) : 0;
|
|
182
|
+
const interpolated = Math.round(((previous ?? sample) + sample) / 2);
|
|
183
|
+
stereo.writeInt16LE(interpolated, offset * 4);
|
|
184
|
+
stereo.writeInt16LE(interpolated, offset * 4 + 2);
|
|
185
|
+
stereo.writeInt16LE(sample, offset * 4 + 4);
|
|
186
|
+
stereo.writeInt16LE(sample, offset * 4 + 6);
|
|
187
|
+
previous = sample;
|
|
188
|
+
}
|
|
189
|
+
readAt = (readAt + sampleBytes) % queued.length;
|
|
190
|
+
bytes -= sampleBytes;
|
|
191
|
+
connection.playOpusPacket(encoder.encode(stereo, FRAME_SAMPLES * 2));
|
|
192
|
+
silenceFrames = 5;
|
|
193
|
+
} else if (silenceFrames > 0) {
|
|
194
|
+
connection.playOpusPacket(SILENCE);
|
|
195
|
+
if (--silenceFrames === 0) connection.setSpeaking(false);
|
|
196
|
+
}
|
|
197
|
+
schedule(now);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
terminate(error);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function clear(): void {
|
|
204
|
+
if (phase !== "open") return;
|
|
205
|
+
readAt = 0;
|
|
206
|
+
bytes = 0;
|
|
207
|
+
previous = undefined;
|
|
208
|
+
try { encoder?.encoderCTL(OPUS_RESET_STATE, 0); }
|
|
209
|
+
catch (error) { terminate(error); }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function play(pcm: Buffer): void {
|
|
213
|
+
if (!pcm.length || phase !== "open" || !refresh()) return;
|
|
214
|
+
if (pcm.length > queued.length - bytes) {
|
|
215
|
+
terminate(new VoiceLinkError("Discord voice playback exceeded its 20-second buffer"));
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const at = (readAt + bytes) % queued.length;
|
|
219
|
+
const first = Math.min(queued.length - at, pcm.length);
|
|
220
|
+
pcm.copy(queued, at, 0, first);
|
|
221
|
+
if (first < pcm.length) pcm.copy(queued, 0, first);
|
|
222
|
+
bytes += pcm.length;
|
|
223
|
+
lastAudioAt = performance.now();
|
|
224
|
+
schedule(lastAudioAt);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
228
|
+
setup.addEventListener("abort", onAbort, { once: true });
|
|
229
|
+
client.on(Events.VoiceStateUpdate, onVoiceState);
|
|
230
|
+
for (const event of guildLoss) client.on(event, onGuildLost);
|
|
231
|
+
client.on(Events.ChannelDelete, onChannelLost);
|
|
232
|
+
client.on(Events.ShardReconnecting, onShardLost);
|
|
233
|
+
connection.on("error", terminate);
|
|
234
|
+
connection.on("transitioned", refresh);
|
|
235
|
+
connection.on("stateChange", onConnectionState);
|
|
236
|
+
try {
|
|
237
|
+
if (setup.aborted) onAbort();
|
|
238
|
+
else onConnectionState(connection.state, connection.state);
|
|
239
|
+
await ready.promise;
|
|
240
|
+
signal.throwIfAborted();
|
|
241
|
+
if (!refresh()) throw closeReason ?? new VoiceLinkError("Discord voice stopped before startup completed");
|
|
242
|
+
// Opus itself resamples and downmixes Discord's stereo into 24 kHz mono.
|
|
243
|
+
decoder = new Opus(PCM_RATE, 1, Opus.Application.VOIP);
|
|
244
|
+
encoder = new Opus(48_000, 2, Opus.Application.VOIP);
|
|
245
|
+
receiver = connection.receiver.subscribe(ownerId, { end: { behavior: sdk.EndBehaviorType.Manual } });
|
|
246
|
+
receiver.on("error", terminate);
|
|
247
|
+
receiver.on("close", () => terminate(new VoiceLinkError("Discord voice receive stream closed")));
|
|
248
|
+
connection.receiver.speaking.on("end", onSpeechEnd);
|
|
249
|
+
receiver.on("data", (packet: Buffer) => {
|
|
250
|
+
if (!decoder || !refresh()) return;
|
|
251
|
+
if (packet.equals(SILENCE)) { speaking = false; return; }
|
|
252
|
+
try {
|
|
253
|
+
const pcm = decoder.decode(packet);
|
|
254
|
+
if (!speaking) {
|
|
255
|
+
speaking = true;
|
|
256
|
+
clear();
|
|
257
|
+
}
|
|
258
|
+
if (phase === "open") handlers.audio(pcm);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
terminate(error);
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
phase = "open";
|
|
264
|
+
setup.removeEventListener("abort", onAbort);
|
|
265
|
+
return { play, clear, close: () => terminate(new VoiceLinkError("Discord voice closed"), false) };
|
|
266
|
+
} catch (error) {
|
|
267
|
+
terminate(error, false);
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { ChannelType, MessageType, type Message, type TextChannel } from "discord.js";
|
|
2
|
+
import type { DiscordVoiceConfig } from "./config";
|
|
3
|
+
import { routeKey, type Inbound, type OutputRecord } from "./contracts";
|
|
4
|
+
import { VoiceDrafts } from "./discord-voice-draft";
|
|
5
|
+
import type { openVoiceLink } from "./discord-voice-link";
|
|
6
|
+
import type { openLive } from "./openai-live";
|
|
7
|
+
import type { openCodexLive } from "./codex-live";
|
|
8
|
+
|
|
9
|
+
// Keep codecs and the provider out of setup, login, and ordinary text traffic.
|
|
10
|
+
const connectDiscord: typeof openVoiceLink = async (...args) =>
|
|
11
|
+
(await import("./discord-voice-link")).openVoiceLink(...args);
|
|
12
|
+
const connectProvider: typeof openLive = async (...args) =>
|
|
13
|
+
(await import("./openai-live")).openLive(...args);
|
|
14
|
+
const connectSubscription: typeof openCodexLive = async (...args) =>
|
|
15
|
+
(await import("./codex-live")).openCodexLive(...args);
|
|
16
|
+
|
|
17
|
+
/** One explicitly started session on the existing Gateway client. No background rejoin or paid retries. */
|
|
18
|
+
export class DiscordVoice {
|
|
19
|
+
private session?: AbortController;
|
|
20
|
+
private drafts = new VoiceDrafts();
|
|
21
|
+
private readonly awaitingText = new Map<string, string>();
|
|
22
|
+
private notifyReply?: () => void;
|
|
23
|
+
private shareUntil = 0;
|
|
24
|
+
private lastCommand = 0n;
|
|
25
|
+
private readonly startedAt = Date.now();
|
|
26
|
+
|
|
27
|
+
constructor(private readonly config: DiscordVoiceConfig, private readonly owner: string,
|
|
28
|
+
private readonly apiKey: string | undefined, private readonly report: (error: unknown) => void, private readonly link = connectDiscord,
|
|
29
|
+
private readonly live = connectProvider, private readonly subscription = connectSubscription) {}
|
|
30
|
+
|
|
31
|
+
static isControl(text: string): boolean { return /^\/voice(?:\s|$)/i.test(text.trim()); }
|
|
32
|
+
|
|
33
|
+
/** Only called for authorized, original MessageCreate events, never catchup or edits. */
|
|
34
|
+
command(message: Message, input: Inbound): string | null {
|
|
35
|
+
if (message.author.bot || message.author.id !== this.owner || message.webhookId || message.editedTimestamp !== null ||
|
|
36
|
+
(message.type !== MessageType.Default && message.type !== MessageType.Reply) || message.channel.type !== ChannelType.GuildText ||
|
|
37
|
+
message.channelId !== this.config.textChannelId || message.createdTimestamp < this.startedAt ||
|
|
38
|
+
!/^\d{1,20}$/.test(message.id)) return null;
|
|
39
|
+
const sequence = BigInt(message.id);
|
|
40
|
+
if (sequence <= this.lastCommand) return null;
|
|
41
|
+
this.lastCommand = sequence;
|
|
42
|
+
const channel = message.channel;
|
|
43
|
+
const control = message.content.trim();
|
|
44
|
+
if (control === "/voice confirm") {
|
|
45
|
+
const work = this.drafts.consume(message);
|
|
46
|
+
if (work) this.awaitingText.set(input.id, routeKey(input.route));
|
|
47
|
+
if (!work) this.notice(channel, "No matching active voice draft. Reply to the current draft, or write the request directly.");
|
|
48
|
+
return work;
|
|
49
|
+
}
|
|
50
|
+
if (message.type !== MessageType.Default || message.reference || message.attachments.size) return null;
|
|
51
|
+
if (control === "/voice stop") {
|
|
52
|
+
this.close();
|
|
53
|
+
this.notice(channel, "Voice is off.");
|
|
54
|
+
} else if (control === "/voice share" && this.config.auth === "subscription") {
|
|
55
|
+
if (!this.session || !this.notifyReply) this.notice(channel, "Start subscription voice before sharing a work draft.");
|
|
56
|
+
else {
|
|
57
|
+
this.shareUntil = performance.now() + 60_000;
|
|
58
|
+
this.notice(channel, "For one minute, the next voice work draft may be posted here. Speak the task now. Posting is not approval.");
|
|
59
|
+
}
|
|
60
|
+
} else if (control === "/voice start") {
|
|
61
|
+
if (this.session) this.notice(channel, "A voice session is already starting or active.");
|
|
62
|
+
else void this.start(channel).catch(() => this.report(new Error("Discord voice startup failed")));
|
|
63
|
+
} else this.notice(channel, this.config.auth === "subscription"
|
|
64
|
+
? "Use /voice start or /voice stop. Use /voice share before dictating one work draft for this channel."
|
|
65
|
+
: "Use /voice start or /voice stop. Voice uses paid OpenAI Live audio.");
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private async start(text: TextChannel): Promise<void> {
|
|
70
|
+
const session = new AbortController();
|
|
71
|
+
this.session = session;
|
|
72
|
+
const { signal } = session;
|
|
73
|
+
const finish = (reason: string) => {
|
|
74
|
+
if (this.session !== session) return;
|
|
75
|
+
this.close();
|
|
76
|
+
this.notice(text, reason);
|
|
77
|
+
};
|
|
78
|
+
const timer = setTimeout(() => finish("Voice stopped at the configured session time limit."),
|
|
79
|
+
this.config.maxSessionSeconds * 1000);
|
|
80
|
+
signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
|
|
81
|
+
try {
|
|
82
|
+
const config = this.config;
|
|
83
|
+
let connect: (handlers: Parameters<typeof openLive>[1]) => ReturnType<typeof openLive>;
|
|
84
|
+
if (config.auth === "subscription") {
|
|
85
|
+
connect = handlers => this.subscription({ voice: config.voice }, handlers, signal);
|
|
86
|
+
} else {
|
|
87
|
+
const apiKey = this.apiKey;
|
|
88
|
+
if (!apiKey) { finish("A separate voice provider key is required. No Live session was opened."); return; }
|
|
89
|
+
connect = handlers => this.live({ model: config.model, backendModel: config.backendModel, voice: config.voice, apiKey }, handlers, signal);
|
|
90
|
+
}
|
|
91
|
+
const channel = await text.guild.channels.fetch(this.config.channelId);
|
|
92
|
+
if (signal.aborted) return;
|
|
93
|
+
if (channel?.type !== ChannelType.GuildVoice || channel.guildId !== text.guildId ||
|
|
94
|
+
text.guild.voiceStates.cache.get(this.owner)?.channelId !== channel.id) {
|
|
95
|
+
finish("Join the configured voice channel in this server before starting voice."); return;
|
|
96
|
+
}
|
|
97
|
+
let provider: Awaited<ReturnType<typeof openLive>> | undefined;
|
|
98
|
+
const ended = () => finish("Voice session ended. Use /voice start to open a new session.");
|
|
99
|
+
const activeLink = await this.link(channel, this.owner, {
|
|
100
|
+
audio: pcm => { if (!signal.aborted) provider?.input(pcm); },
|
|
101
|
+
ended,
|
|
102
|
+
}, signal);
|
|
103
|
+
if (signal.aborted) { activeLink.close(); return; }
|
|
104
|
+
provider = await connect({
|
|
105
|
+
audio: pcm => { if (!signal.aborted) activeLink.play(pcm); },
|
|
106
|
+
interrupt: () => activeLink.clear(), ended,
|
|
107
|
+
forward: async request => {
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
if (config.auth === "subscription") {
|
|
110
|
+
if (!this.shareUntil || performance.now() >= this.shareUntil) throw new Error("No written permission to share a voice draft");
|
|
111
|
+
this.shareUntil = 0;
|
|
112
|
+
}
|
|
113
|
+
await this.drafts.propose(text, this.owner, request, signal);
|
|
114
|
+
return "Draft posted for written confirmation. Not yet submitted to HEAD or executed.";
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
if (signal.aborted) { provider.close(); return; }
|
|
118
|
+
this.notifyReply = () => provider?.notifyHeadReply();
|
|
119
|
+
this.notice(text, config.auth === "subscription"
|
|
120
|
+
? "Voice ready. Audio goes to OpenAI using your Codex subscription. To post one work draft here, type /voice share before dictating it. Use /voice stop to disconnect."
|
|
121
|
+
: "Voice ready. Your audio goes to OpenAI Live. Use /voice stop to disconnect.");
|
|
122
|
+
} catch {
|
|
123
|
+
// Never send SDK errors, bearer headers, owner audio, or transcripts to Discord/logs.
|
|
124
|
+
finish(this.config.auth === "subscription"
|
|
125
|
+
? "Could not open Codex subscription voice. Check the voice bridge, subscription login, voice access and Discord channel. No API fallback."
|
|
126
|
+
: "Could not open voice. Check channel membership, permissions, voice dependencies and provider settings. No automatic retry.");
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private notice(channel: TextChannel, content: string): void {
|
|
131
|
+
void channel.send({ content, allowedMentions: { parse: [] } }).catch(() => this.report(new Error("Discord voice notice delivery failed")));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
textDelivered(output: OutputRecord): void {
|
|
135
|
+
if (this.awaitingText.get(output.sourceId) !== routeKey(output.route)) return;
|
|
136
|
+
this.awaitingText.delete(output.sourceId);
|
|
137
|
+
// Discord delivery succeeded; a best-effort spoken notice cannot change that outcome.
|
|
138
|
+
try { this.notifyReply?.(); } catch { this.report(new Error("Voice reply notification failed")); }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
close(): void {
|
|
142
|
+
const session = this.session;
|
|
143
|
+
this.session = undefined;
|
|
144
|
+
this.notifyReply = undefined;
|
|
145
|
+
this.shareUntil = 0;
|
|
146
|
+
this.awaitingText.clear();
|
|
147
|
+
session?.abort();
|
|
148
|
+
this.drafts.clear();
|
|
149
|
+
}
|
|
150
|
+
}
|