@openclaw/twitch 2026.10.10 → 2026.11.5-beta.1
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/dist/.setup/{monitor-OlDdzwhV.mjs → monitor-DfA87gBg.mjs} +92 -181
- package/dist/.setup/plugin-B2l8TCND.mjs +1023 -0
- package/dist/.setup/setup-plugin-api-EN3PbyIC.mjs +2 -0
- package/dist/.setup/{setup-surface-8f7RsuJw.mjs → setup-surface-mdCyd7g7.mjs} +78 -91
- package/dist/.source-module-urls/e92ae748f4a308f6cf1a5ef62518f7ba0627945de435d928747fa07ea1b4421f.json +1 -1
- package/dist/api.js +1 -3
- package/dist/channel-plugin-api.js +1 -1
- package/dist/setup-entry.js +1 -1
- package/dist/setup-plugin-api.js +1 -1
- package/package.json +5 -5
- package/dist/.setup/plugin-CnPNkPhc.mjs +0 -851
- package/dist/.setup/runtime-DrwVh6hF.mjs +0 -7
- package/dist/.setup/setup-plugin-api-DCp5heMU.mjs +0 -2
|
@@ -0,0 +1,1023 @@
|
|
|
1
|
+
import { a as resolveTwitchAccountContext, c as normalizeToken, i as resolveDefaultTwitchAccountId, l as normalizeTwitchChannel, n as DEFAULT_ACCOUNT_ID$1, o as twitchConfigAdapter, r as getAccountConfig, s as isAccountConfigured, t as twitchSetupPlugin, u as resolveTwitchToken } from "./setup-surface-mdCyd7g7.mjs";
|
|
2
|
+
import { StaticAuthProvider, accessTokenIsExpired, getTokenInfo } from "@twurple/auth";
|
|
3
|
+
import { ChatClient, LogLevel } from "@twurple/chat";
|
|
4
|
+
import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
|
|
5
|
+
import { MarkdownConfigSchema, buildChannelConfigSchema } from "openclaw/plugin-sdk/channel-config-schema";
|
|
6
|
+
import { buildChannelOutboundSessionRoute, createChatChannelPlugin, stripChannelTargetPrefix } from "openclaw/plugin-sdk/channel-core";
|
|
7
|
+
import { createAccountStatusSink, createChannelMessageAdapterFromOutbound, createMessageReceiptFromOutboundResults, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
|
|
8
|
+
import { createLoggedPairingApprovalNotifier, createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
|
|
9
|
+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
10
|
+
import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
|
|
11
|
+
import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
|
|
12
|
+
import { runChannelProbe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
13
|
+
import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
|
|
14
|
+
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/account-resolution";
|
|
15
|
+
import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
|
|
16
|
+
import { captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
|
|
17
|
+
import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
|
|
18
|
+
import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
|
|
19
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
20
|
+
import { isDeepStrictEqual } from "node:util";
|
|
21
|
+
import { readProviderJsonObjectResponse } from "openclaw/plugin-sdk/provider-http";
|
|
22
|
+
import { createOAuthRefreshError, createOAuthRefreshResponseError, isRecoverableOAuthRefreshFailure, readOAuthRefreshErrorReason } from "openclaw/plugin-sdk/provider-oauth-runtime";
|
|
23
|
+
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
24
|
+
import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
25
|
+
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
|
|
28
|
+
// extensions/twitch/src/runtime.ts
|
|
29
|
+
const { setRuntime: setTwitchRuntime, getRuntime: getTwitchRuntime } = createPluginRuntimeStore({
|
|
30
|
+
pluginId: "twitch",
|
|
31
|
+
errorMessage: "Twitch runtime not initialized"
|
|
32
|
+
});
|
|
33
|
+
// extensions/twitch/src/oauth-owner.ts
|
|
34
|
+
const tasks = /* @__PURE__ */ new WeakMap();
|
|
35
|
+
function lineageOf(account, token) {
|
|
36
|
+
return createHash("sha256").update(JSON.stringify([
|
|
37
|
+
account.username.toLowerCase(),
|
|
38
|
+
account.clientId,
|
|
39
|
+
account.clientSecret,
|
|
40
|
+
token,
|
|
41
|
+
account.refreshToken,
|
|
42
|
+
account.expiresIn,
|
|
43
|
+
account.obtainmentTimestamp
|
|
44
|
+
])).digest("hex");
|
|
45
|
+
}
|
|
46
|
+
async function exchange(account, refreshToken, assertCurrent) {
|
|
47
|
+
let dispatched = false;
|
|
48
|
+
const { response, release } = await fetchWithSsrFGuard({
|
|
49
|
+
url: "https://id.twitch.tv/oauth2/token",
|
|
50
|
+
policy: { allowedHostnames: ["id.twitch.tv"] },
|
|
51
|
+
requireHttps: true,
|
|
52
|
+
timeoutMs: 3e4,
|
|
53
|
+
auditContext: "twitch.oauth.refresh",
|
|
54
|
+
beforeRequest: () => {
|
|
55
|
+
assertCurrent();
|
|
56
|
+
dispatched = true;
|
|
57
|
+
},
|
|
58
|
+
init: {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
62
|
+
Accept: "application/json"
|
|
63
|
+
},
|
|
64
|
+
body: new URLSearchParams({
|
|
65
|
+
client_id: account.clientId,
|
|
66
|
+
client_secret: account.clientSecret,
|
|
67
|
+
grant_type: "refresh_token",
|
|
68
|
+
refresh_token: refreshToken
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
}).catch((cause) => {
|
|
72
|
+
throw createOAuthRefreshError("Twitch OAuth refresh transport failed", dispatched ? {
|
|
73
|
+
version: 1,
|
|
74
|
+
phase: "token-response",
|
|
75
|
+
outcome: "unknown"
|
|
76
|
+
} : {
|
|
77
|
+
version: 1,
|
|
78
|
+
phase: "before-dispatch",
|
|
79
|
+
outcome: "not-attempted",
|
|
80
|
+
recovery: {
|
|
81
|
+
kind: "later",
|
|
82
|
+
evidence: "dispatch-not-started"
|
|
83
|
+
}
|
|
84
|
+
}, { cause });
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
let payload;
|
|
88
|
+
try {
|
|
89
|
+
payload = await readProviderJsonObjectResponse(response, "Twitch OAuth refresh", { maxBytes: 262144 });
|
|
90
|
+
} catch {
|
|
91
|
+
throw createOAuthRefreshError("Twitch OAuth refresh returned an unreadable response", {
|
|
92
|
+
version: 1,
|
|
93
|
+
phase: "after-token-response",
|
|
94
|
+
outcome: "unknown",
|
|
95
|
+
status: response.status
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (!response.ok || readOAuthRefreshErrorReason(payload)) throw createOAuthRefreshResponseError("Twitch OAuth refresh", response.status, payload);
|
|
99
|
+
if (typeof payload.access_token !== "string" || !payload.access_token.trim() || typeof payload.refresh_token !== "string" || !payload.refresh_token.trim() || typeof payload.expires_in !== "number" || !Number.isFinite(payload.expires_in) || payload.expires_in < 0 || !Array.isArray(payload.scope) || !payload.scope.every((scope) => typeof scope === "string") || typeof payload.token_type !== "string" || payload.token_type.toLowerCase() !== "bearer") throw createOAuthRefreshError("Twitch OAuth refresh returned invalid tokens", {
|
|
100
|
+
version: 1,
|
|
101
|
+
phase: "after-token-response",
|
|
102
|
+
outcome: "unknown",
|
|
103
|
+
status: response.status
|
|
104
|
+
});
|
|
105
|
+
return {
|
|
106
|
+
accessToken: payload.access_token,
|
|
107
|
+
refreshToken: payload.refresh_token,
|
|
108
|
+
expiresIn: payload.expires_in,
|
|
109
|
+
scope: payload.scope,
|
|
110
|
+
obtainmentTimestamp: Date.now()
|
|
111
|
+
};
|
|
112
|
+
} finally {
|
|
113
|
+
await release();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** One durable channel-account owner, including the initial and IRC-requested refresh. */
|
|
117
|
+
async function createManagedTwitchAuthProvider(account, token, accountId) {
|
|
118
|
+
const clientId = account.clientId;
|
|
119
|
+
if (!clientId) throw new Error("Twitch OAuth requires a client ID");
|
|
120
|
+
const runtime = getTwitchRuntime();
|
|
121
|
+
const id = normalizeAccountId(accountId);
|
|
122
|
+
const lineage = lineageOf(account, token);
|
|
123
|
+
const assertCurrent = () => {
|
|
124
|
+
if (getTwitchRuntime() !== runtime) throw new Error("Twitch OAuth runtime changed");
|
|
125
|
+
const cfg = runtime.config.current({ clone: true });
|
|
126
|
+
const current = getAccountConfig(cfg, id);
|
|
127
|
+
if (cfg.channels?.twitch?.enabled === false || current?.enabled === false) throw new Error("Twitch account is disabled; enable it before using its OAuth grant");
|
|
128
|
+
const currentToken = normalizeToken(resolveTwitchToken(cfg, id).token);
|
|
129
|
+
if (!current || lineageOf(current, currentToken) !== lineage) throw new Error("Twitch OAuth account changed; retry with its current configuration");
|
|
130
|
+
};
|
|
131
|
+
assertCurrent();
|
|
132
|
+
const namespace = "oauth-" + id;
|
|
133
|
+
const key = runtime.state.resolveStateDir() + ":" + id + ":" + lineage;
|
|
134
|
+
const resolve = async (force = false) => {
|
|
135
|
+
assertCurrent();
|
|
136
|
+
let active = tasks.get(runtime);
|
|
137
|
+
if (!active) {
|
|
138
|
+
active = /* @__PURE__ */ new Map();
|
|
139
|
+
tasks.set(runtime, active);
|
|
140
|
+
}
|
|
141
|
+
const pending = active.get(key);
|
|
142
|
+
if (pending) return await pending;
|
|
143
|
+
const task = (async () => {
|
|
144
|
+
const store = runtime.state.openKeyedStoreV2({
|
|
145
|
+
namespace,
|
|
146
|
+
maxEntries: 1,
|
|
147
|
+
overflowPolicy: "reject-new"
|
|
148
|
+
}, { assertCurrent });
|
|
149
|
+
let observed = await store.observe("current");
|
|
150
|
+
if (observed.value?.lineage !== lineage) {
|
|
151
|
+
const initialized = await store.compareAndApply("current", observed.comparison, {
|
|
152
|
+
operation: "update",
|
|
153
|
+
action: "set",
|
|
154
|
+
value: {
|
|
155
|
+
lineage,
|
|
156
|
+
token: {
|
|
157
|
+
accessToken: token,
|
|
158
|
+
refreshToken: account.refreshToken ?? null,
|
|
159
|
+
expiresIn: account.expiresIn ?? null,
|
|
160
|
+
obtainmentTimestamp: account.obtainmentTimestamp ?? Date.now(),
|
|
161
|
+
scope: []
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
observed = initialized.status === "conflict" ? initialized.current : await store.observe("current");
|
|
166
|
+
}
|
|
167
|
+
const validateCompleted = async (claim) => {
|
|
168
|
+
assertCurrent();
|
|
169
|
+
const info = await getTokenInfo(claim.completed.accessToken, clientId);
|
|
170
|
+
assertCurrent();
|
|
171
|
+
const current = await store.observe("current");
|
|
172
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before validation");
|
|
173
|
+
if (!info.userId || info.userName?.toLowerCase() !== account.username.toLowerCase() || claim.expectedUserId && info.userId !== claim.expectedUserId) {
|
|
174
|
+
await store.compareAndApply("current", current.comparison, {
|
|
175
|
+
operation: "update",
|
|
176
|
+
action: "set",
|
|
177
|
+
value: {
|
|
178
|
+
lineage,
|
|
179
|
+
claim: claim.claim
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
throw new Error("Twitch OAuth refresh returned a different account; reauthorize the configured grant");
|
|
183
|
+
}
|
|
184
|
+
const replacement = {
|
|
185
|
+
...claim.completed,
|
|
186
|
+
userId: info.userId
|
|
187
|
+
};
|
|
188
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
189
|
+
operation: "update",
|
|
190
|
+
action: "set",
|
|
191
|
+
value: {
|
|
192
|
+
lineage,
|
|
193
|
+
token: replacement
|
|
194
|
+
}
|
|
195
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
196
|
+
assertCurrent();
|
|
197
|
+
return replacement;
|
|
198
|
+
};
|
|
199
|
+
if (observed.value?.lineage === lineage && "claim" in observed.value && observed.value.completed) return await validateCompleted({
|
|
200
|
+
...observed.value,
|
|
201
|
+
completed: observed.value.completed
|
|
202
|
+
});
|
|
203
|
+
assertCurrent();
|
|
204
|
+
if (!observed.value || observed.value.lineage !== lineage || !("token" in observed.value)) throw new Error("Twitch OAuth refresh is pending or its outcome is uncertain; reauthorize the configured grant");
|
|
205
|
+
const original = observed.value.token;
|
|
206
|
+
if (!force && !accessTokenIsExpired(original)) return original;
|
|
207
|
+
if (!original.refreshToken) throw new Error("Twitch OAuth refresh requires a refresh token");
|
|
208
|
+
const claim = {
|
|
209
|
+
lineage,
|
|
210
|
+
claim: randomUUID()
|
|
211
|
+
};
|
|
212
|
+
if ((await store.compareAndApply("current", observed.comparison, {
|
|
213
|
+
operation: "update",
|
|
214
|
+
action: "set",
|
|
215
|
+
value: claim
|
|
216
|
+
})).status !== "applied") throw new Error("Twitch OAuth grant changed before refresh; retry with its current owner");
|
|
217
|
+
const settle = async (replacement) => {
|
|
218
|
+
const current = await store.observe("current");
|
|
219
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
220
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
221
|
+
operation: "update",
|
|
222
|
+
action: "set",
|
|
223
|
+
value: {
|
|
224
|
+
lineage,
|
|
225
|
+
token: replacement
|
|
226
|
+
}
|
|
227
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
228
|
+
assertCurrent();
|
|
229
|
+
};
|
|
230
|
+
assertCurrent();
|
|
231
|
+
let refreshed;
|
|
232
|
+
try {
|
|
233
|
+
refreshed = await exchange(account, original.refreshToken, assertCurrent);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (isRecoverableOAuthRefreshFailure(error)) await settle(original);
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
const completed = {
|
|
239
|
+
...claim,
|
|
240
|
+
completed: refreshed,
|
|
241
|
+
...original.userId ? { expectedUserId: original.userId } : {}
|
|
242
|
+
};
|
|
243
|
+
const current = await store.observe("current");
|
|
244
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before completion");
|
|
245
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
246
|
+
operation: "update",
|
|
247
|
+
action: "set",
|
|
248
|
+
value: completed
|
|
249
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before completion");
|
|
250
|
+
return await validateCompleted(completed);
|
|
251
|
+
})();
|
|
252
|
+
active.set(key, task);
|
|
253
|
+
try {
|
|
254
|
+
return await task;
|
|
255
|
+
} finally {
|
|
256
|
+
if (active.get(key) === task) active.delete(key);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
let grant = await resolve();
|
|
260
|
+
let staticProvider = new StaticAuthProvider(clientId, grant);
|
|
261
|
+
const prepare = async (force = false) => {
|
|
262
|
+
const current = await resolve(force);
|
|
263
|
+
if (current.accessToken !== grant.accessToken) staticProvider = new StaticAuthProvider(clientId, current);
|
|
264
|
+
grant = current;
|
|
265
|
+
assertCurrent();
|
|
266
|
+
return staticProvider;
|
|
267
|
+
};
|
|
268
|
+
return {
|
|
269
|
+
clientId,
|
|
270
|
+
hasClientSecret: true,
|
|
271
|
+
getCurrentScopesForUser: () => staticProvider.getCurrentScopesForUser(),
|
|
272
|
+
async getAccessTokenForUser(user, ...scopeSets) {
|
|
273
|
+
const result = await (await prepare()).getAccessTokenForUser(user, ...scopeSets);
|
|
274
|
+
assertCurrent();
|
|
275
|
+
return result;
|
|
276
|
+
},
|
|
277
|
+
async getAccessTokenForIntent(intent, ...scopeSets) {
|
|
278
|
+
if (intent !== "chat") return null;
|
|
279
|
+
const result = await (await prepare()).getAccessTokenForIntent(intent, ...scopeSets);
|
|
280
|
+
assertCurrent();
|
|
281
|
+
return result;
|
|
282
|
+
},
|
|
283
|
+
async getAnyAccessToken() {
|
|
284
|
+
const result = await (await prepare()).getAnyAccessToken();
|
|
285
|
+
assertCurrent();
|
|
286
|
+
return result;
|
|
287
|
+
},
|
|
288
|
+
async refreshAccessTokenForIntent(intent) {
|
|
289
|
+
if (intent !== "chat") throw new Error("Unknown Twitch OAuth intent");
|
|
290
|
+
const result = await (await prepare(true)).getAccessTokenForIntent(intent);
|
|
291
|
+
assertCurrent();
|
|
292
|
+
return result;
|
|
293
|
+
},
|
|
294
|
+
async refreshAccessTokenForUser(user) {
|
|
295
|
+
const result = await (await prepare(true)).getAccessTokenForUser(user);
|
|
296
|
+
assertCurrent();
|
|
297
|
+
return result;
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
// extensions/twitch/src/twitch-client.ts
|
|
302
|
+
var TwitchClientManager = class {
|
|
303
|
+
constructor(logger, statusSink) {
|
|
304
|
+
this.logger = logger;
|
|
305
|
+
this.statusSink = statusSink;
|
|
306
|
+
}
|
|
307
|
+
setStatusSink(statusSink) {
|
|
308
|
+
if (statusSink) this.statusSink = statusSink;
|
|
309
|
+
}
|
|
310
|
+
publishReady() {
|
|
311
|
+
this.statusSink?.(channelReadyPatch());
|
|
312
|
+
}
|
|
313
|
+
publishRecovering(lastError) {
|
|
314
|
+
this.statusSink?.({
|
|
315
|
+
connected: false,
|
|
316
|
+
lifecycle: "recovering",
|
|
317
|
+
lastError
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
async getClient(account, cfg, accountId) {
|
|
321
|
+
if (this.client) return this.client;
|
|
322
|
+
if (this.connectionPromise) return this.connectionPromise;
|
|
323
|
+
const connection = this.createConnectedClient(account, () => this.connectionPromise === connection, cfg, accountId);
|
|
324
|
+
this.connectionPromise = connection;
|
|
325
|
+
try {
|
|
326
|
+
return await connection;
|
|
327
|
+
} finally {
|
|
328
|
+
if (this.connectionPromise === connection) this.connectionPromise = void 0;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async createConnectedClient(account, ownsConnection, cfg, accountId) {
|
|
332
|
+
const tokenResolution = resolveTwitchToken(cfg, accountId);
|
|
333
|
+
if (!tokenResolution.token) {
|
|
334
|
+
const resolvedAccountId = accountId ?? DEFAULT_ACCOUNT_ID;
|
|
335
|
+
const tokenConfigPath = cfg?.channels?.twitch?.accounts ? `channels.twitch.accounts.${resolvedAccountId}.accessToken` : "channels.twitch.accessToken";
|
|
336
|
+
throw new Error(`Missing Twitch token for account ${resolvedAccountId} (set ${tokenConfigPath} or OPENCLAW_TWITCH_ACCESS_TOKEN for default)`);
|
|
337
|
+
}
|
|
338
|
+
if (!account.clientId) throw new Error(`Missing Twitch client ID for account ${account.username}`);
|
|
339
|
+
const normalizedToken = normalizeToken(tokenResolution.token);
|
|
340
|
+
const clientId = account.clientId;
|
|
341
|
+
const authProvider = await (account.clientSecret && account.refreshToken ? createManagedTwitchAuthProvider(account, normalizedToken, accountId) : new StaticAuthProvider(clientId, normalizedToken));
|
|
342
|
+
if (!ownsConnection()) throw new Error(`Twitch connection cancelled for ${account.username}`);
|
|
343
|
+
const client = new ChatClient({
|
|
344
|
+
authProvider,
|
|
345
|
+
channels: [account.channel],
|
|
346
|
+
rejoinChannelsOnReconnect: true,
|
|
347
|
+
requestMembershipEvents: true,
|
|
348
|
+
logger: {
|
|
349
|
+
minLevel: LogLevel.WARNING,
|
|
350
|
+
custom: { log: (level, message) => {
|
|
351
|
+
switch (level) {
|
|
352
|
+
case LogLevel.CRITICAL:
|
|
353
|
+
case LogLevel.ERROR:
|
|
354
|
+
this.logger.error(message.startsWith("Error parsing message: ") ? "Twitch IRC message parsing failed" : message);
|
|
355
|
+
break;
|
|
356
|
+
case LogLevel.WARNING:
|
|
357
|
+
this.logger.warn(message);
|
|
358
|
+
break;
|
|
359
|
+
case LogLevel.INFO:
|
|
360
|
+
this.logger.info(message);
|
|
361
|
+
break;
|
|
362
|
+
case LogLevel.DEBUG:
|
|
363
|
+
case LogLevel.TRACE: this.logger.debug?.(message);
|
|
364
|
+
}
|
|
365
|
+
} }
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
this.pendingClient = client;
|
|
369
|
+
try {
|
|
370
|
+
const connectTimeoutMs = 15e3;
|
|
371
|
+
await new Promise((resolve, reject) => {
|
|
372
|
+
let settled = false;
|
|
373
|
+
let authRetryPending = false;
|
|
374
|
+
const listeners = [];
|
|
375
|
+
const finish = (error) => {
|
|
376
|
+
if (settled) return;
|
|
377
|
+
settled = true;
|
|
378
|
+
clearTimeout(timeout);
|
|
379
|
+
for (const listener of listeners) listener.unbind();
|
|
380
|
+
if (error) {
|
|
381
|
+
try {
|
|
382
|
+
client.quit();
|
|
383
|
+
} catch {}
|
|
384
|
+
reject(error);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
resolve();
|
|
388
|
+
};
|
|
389
|
+
listeners.push(client.onAuthenticationSuccess(() => {
|
|
390
|
+
this.publishReady();
|
|
391
|
+
finish();
|
|
392
|
+
}), client.onAuthenticationFailure((text) => {
|
|
393
|
+
authRetryPending = true;
|
|
394
|
+
this.publishRecovering(text);
|
|
395
|
+
this.logger.warn(`Twitch authentication failed for ${account.username}; waiting for retry, disconnect, or timeout: ${text}`);
|
|
396
|
+
}), client.onDisconnect((manual, reason) => {
|
|
397
|
+
if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
|
|
398
|
+
if (authRetryPending && !manual) return;
|
|
399
|
+
finish(reason ?? /* @__PURE__ */ new Error(manual ? `Twitch connection cancelled for ${account.username}` : `Twitch disconnected before ready for ${account.username}`));
|
|
400
|
+
}));
|
|
401
|
+
const timeout = setTimeout(() => finish(/* @__PURE__ */ new Error(`Timed out connecting to Twitch as ${account.username}`)), connectTimeoutMs);
|
|
402
|
+
timeout.unref?.();
|
|
403
|
+
try {
|
|
404
|
+
client.connect();
|
|
405
|
+
} catch (error) {
|
|
406
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
if (this.pendingClient !== client) {
|
|
410
|
+
client.quit();
|
|
411
|
+
throw new Error(`Twitch connection cancelled for ${account.username}`);
|
|
412
|
+
}
|
|
413
|
+
} finally {
|
|
414
|
+
if (this.pendingClient === client) this.pendingClient = void 0;
|
|
415
|
+
}
|
|
416
|
+
client.onMessage((channelName, _user, messageText, msg) => {
|
|
417
|
+
const handler = this.messageHandler?.handler;
|
|
418
|
+
if (handler) handler({
|
|
419
|
+
username: msg.userInfo.userName,
|
|
420
|
+
displayName: msg.userInfo.displayName,
|
|
421
|
+
userId: msg.userInfo.userId,
|
|
422
|
+
message: messageText,
|
|
423
|
+
channel: channelName,
|
|
424
|
+
id: msg.id,
|
|
425
|
+
timestamp: Date.now(),
|
|
426
|
+
isMod: msg.userInfo.isMod,
|
|
427
|
+
isOwner: msg.userInfo.isBroadcaster,
|
|
428
|
+
isVip: msg.userInfo.isVip,
|
|
429
|
+
isSub: msg.userInfo.isSubscriber,
|
|
430
|
+
chatType: "group"
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
client.onAuthenticationSuccess(() => this.publishReady());
|
|
434
|
+
client.onAuthenticationFailure((text) => {
|
|
435
|
+
this.publishRecovering(text);
|
|
436
|
+
});
|
|
437
|
+
client.onDisconnect((manual, reason) => {
|
|
438
|
+
if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
|
|
439
|
+
});
|
|
440
|
+
this.client = client;
|
|
441
|
+
this.logger.info(`Connected to Twitch as ${account.username}`);
|
|
442
|
+
return client;
|
|
443
|
+
}
|
|
444
|
+
onMessage(handler) {
|
|
445
|
+
const registration = { handler };
|
|
446
|
+
this.messageHandler = registration;
|
|
447
|
+
return () => {
|
|
448
|
+
if (this.messageHandler === registration) this.messageHandler = void 0;
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
async disconnectAll() {
|
|
452
|
+
this.pendingClient?.quit();
|
|
453
|
+
this.client?.quit();
|
|
454
|
+
this.pendingClient = void 0;
|
|
455
|
+
this.connectionPromise = void 0;
|
|
456
|
+
this.client = void 0;
|
|
457
|
+
this.messageHandler = void 0;
|
|
458
|
+
}
|
|
459
|
+
async sendMessage(account, channel, message, cfg, accountId) {
|
|
460
|
+
const effect = captureEffectAuthority();
|
|
461
|
+
let preparingUse = false;
|
|
462
|
+
try {
|
|
463
|
+
const client = await this.getClient(account, cfg, accountId);
|
|
464
|
+
const messageId = crypto.randomUUID();
|
|
465
|
+
const chunks = chunkTextForOutbound(message, 500);
|
|
466
|
+
preparingUse = true;
|
|
467
|
+
const results = await effect.initiate(() => {
|
|
468
|
+
preparingUse = false;
|
|
469
|
+
return Promise.allSettled(chunks.map(async (chunk) => client.say(channel, chunk)));
|
|
470
|
+
});
|
|
471
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
472
|
+
if (failure) {
|
|
473
|
+
if (results.some((result) => result.status === "fulfilled")) throw createChannelPartialDeliveryError(failure.reason, {
|
|
474
|
+
messageIds: [messageId],
|
|
475
|
+
visibleReplySent: true
|
|
476
|
+
});
|
|
477
|
+
throw failure.reason;
|
|
478
|
+
}
|
|
479
|
+
return {
|
|
480
|
+
ok: true,
|
|
481
|
+
messageId
|
|
482
|
+
};
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (preparingUse || isChannelPartialDeliveryError(error)) throw error;
|
|
485
|
+
return {
|
|
486
|
+
ok: false,
|
|
487
|
+
error: formatErrorMessage(error)
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
// extensions/twitch/src/client-manager-registry.ts
|
|
493
|
+
const registry = /* @__PURE__ */ new Map();
|
|
494
|
+
function getOrCreateClientManager(accountId, logger, statusSink) {
|
|
495
|
+
const existing = registry.get(accountId);
|
|
496
|
+
if (existing) {
|
|
497
|
+
existing.setStatusSink(statusSink);
|
|
498
|
+
return existing;
|
|
499
|
+
}
|
|
500
|
+
const manager = new TwitchClientManager(logger, statusSink);
|
|
501
|
+
registry.set(accountId, manager);
|
|
502
|
+
return manager;
|
|
503
|
+
}
|
|
504
|
+
function getClientManager(accountId) {
|
|
505
|
+
return registry.get(accountId);
|
|
506
|
+
}
|
|
507
|
+
async function removeClientManager(accountId) {
|
|
508
|
+
const manager = registry.get(accountId);
|
|
509
|
+
if (!manager) return;
|
|
510
|
+
registry.delete(accountId);
|
|
511
|
+
await manager.disconnectAll();
|
|
512
|
+
}
|
|
513
|
+
// extensions/twitch/src/config-schema.ts
|
|
514
|
+
const TwitchRoleSchema = z.enum([
|
|
515
|
+
"moderator",
|
|
516
|
+
"owner",
|
|
517
|
+
"vip",
|
|
518
|
+
"subscriber",
|
|
519
|
+
"all"
|
|
520
|
+
]);
|
|
521
|
+
const TwitchAccountShape = {
|
|
522
|
+
username: z.string(),
|
|
523
|
+
/** Twitch OAuth access token (requires chat:read and chat:write scopes) */
|
|
524
|
+
accessToken: z.string(),
|
|
525
|
+
/** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
|
|
526
|
+
clientId: z.string().optional(),
|
|
527
|
+
channel: z.string().min(1),
|
|
528
|
+
enabled: z.boolean().optional(),
|
|
529
|
+
/** Allow channel-initiated configuration writes */
|
|
530
|
+
configWrites: z.boolean().optional(),
|
|
531
|
+
/** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
|
|
532
|
+
allowFrom: z.array(z.string()).optional(),
|
|
533
|
+
allowedRoles: z.array(TwitchRoleSchema).optional(),
|
|
534
|
+
/** Require @mention to trigger bot responses */
|
|
535
|
+
requireMention: z.boolean().optional(),
|
|
536
|
+
responsePrefix: z.string().optional(),
|
|
537
|
+
/** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
|
|
538
|
+
clientSecret: z.string().optional(),
|
|
539
|
+
/** Refresh token (required for automatic token refresh) */
|
|
540
|
+
refreshToken: z.string().optional(),
|
|
541
|
+
/** Token expiry time in seconds (optional, for token refresh tracking) */
|
|
542
|
+
expiresIn: z.number().nullable().optional(),
|
|
543
|
+
/** Timestamp when token was obtained (optional, for token refresh tracking) */
|
|
544
|
+
obtainmentTimestamp: z.number().optional()
|
|
545
|
+
};
|
|
546
|
+
const TwitchAccountSchema = z.object(TwitchAccountShape);
|
|
547
|
+
const TwitchConfigBaseShape = {
|
|
548
|
+
name: z.string().optional(),
|
|
549
|
+
enabled: z.boolean().optional(),
|
|
550
|
+
configWrites: z.boolean().optional(),
|
|
551
|
+
markdown: MarkdownConfigSchema.optional(),
|
|
552
|
+
defaultAccount: z.string().optional(),
|
|
553
|
+
historyLimit: z.number().int().min(0).optional(),
|
|
554
|
+
responsePrefix: z.string().optional()
|
|
555
|
+
};
|
|
556
|
+
const SimplifiedSchema = z.object({
|
|
557
|
+
...TwitchConfigBaseShape,
|
|
558
|
+
...TwitchAccountShape
|
|
559
|
+
});
|
|
560
|
+
const MultiAccountSchema = z.object({
|
|
561
|
+
...TwitchConfigBaseShape,
|
|
562
|
+
accounts: z.record(z.string(), TwitchAccountSchema)
|
|
563
|
+
}).refine((val) => Object.keys(val.accounts).length > 0, { message: "accounts must contain at least one entry" });
|
|
564
|
+
const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
|
|
565
|
+
// extensions/twitch/src/send.ts
|
|
566
|
+
function createTwitchSendReceipt(messageId, channel) {
|
|
567
|
+
return createMessageReceiptFromOutboundResults({
|
|
568
|
+
results: messageId ? [{
|
|
569
|
+
channel: "twitch",
|
|
570
|
+
messageId,
|
|
571
|
+
conversationId: channel
|
|
572
|
+
}] : [],
|
|
573
|
+
kind: "text"
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
async function sendMessageTwitchInternal(params) {
|
|
577
|
+
const cleanedText = stripMarkdown(params.text, { linkStyle: "label-and-url" }).replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n/g, " ").replace(/[ \t]{2,}/g, " ").trim();
|
|
578
|
+
if (!cleanedText) return {
|
|
579
|
+
outcome: "not_sent",
|
|
580
|
+
messageId: "",
|
|
581
|
+
receipt: createTwitchSendReceipt()
|
|
582
|
+
};
|
|
583
|
+
if (!params.clientManager) throw new Error(`Client manager not found for account: ${params.accountId}. Please start the Twitch gateway first.`);
|
|
584
|
+
const result = await params.clientManager.sendMessage(params.account, params.channel, cleanedText, params.cfg, params.accountId);
|
|
585
|
+
if (!result.ok) throw new Error(result.error);
|
|
586
|
+
const { messageId } = result;
|
|
587
|
+
return {
|
|
588
|
+
messageId,
|
|
589
|
+
receipt: createTwitchSendReceipt(messageId, params.channel)
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
// extensions/twitch/src/target.ts
|
|
593
|
+
function parseTwitchMessagingTarget(target) {
|
|
594
|
+
const providerTarget = stripChannelTargetPrefix(target, "twitch", "twitch-chat");
|
|
595
|
+
const kindMatch = /^(user|dm|channel|group|conversation|room):/i.exec(providerTarget);
|
|
596
|
+
const kind = kindMatch?.[1]?.toLowerCase();
|
|
597
|
+
return {
|
|
598
|
+
channelTarget: kindMatch ? providerTarget.slice(kindMatch[0].length) : providerTarget,
|
|
599
|
+
isDirectMessage: kind === "user" || kind === "dm"
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Normalizes a Twitch messaging target to the bare channel name used by routing
|
|
604
|
+
* and the chat transport. Accepts internal addresses such as
|
|
605
|
+
* `twitch:channel:<channel>` and their `twitch-chat:` alias. Direct-message
|
|
606
|
+
* targets are unsupported and normalize to an empty string.
|
|
607
|
+
*/
|
|
608
|
+
function normalizeTwitchMessagingTarget(target) {
|
|
609
|
+
const parsed = parseTwitchMessagingTarget(target);
|
|
610
|
+
return parsed.isDirectMessage ? "" : normalizeTwitchChannel(parsed.channelTarget);
|
|
611
|
+
}
|
|
612
|
+
/** Direct-message/user addresses are unsupported and must not fall back to a channel. */
|
|
613
|
+
function isTwitchDirectMessageTarget(target) {
|
|
614
|
+
return parseTwitchMessagingTarget(target).isDirectMessage;
|
|
615
|
+
}
|
|
616
|
+
// extensions/twitch/src/outbound.ts
|
|
617
|
+
const twitchOutbound = {
|
|
618
|
+
deliveryMode: "direct",
|
|
619
|
+
deliveryCapabilities: { durableFinal: {
|
|
620
|
+
text: true,
|
|
621
|
+
media: true,
|
|
622
|
+
messageSendingHooks: true
|
|
623
|
+
} },
|
|
624
|
+
textChunkLimit: 500,
|
|
625
|
+
sanitizeText: ({ text }) => sanitizeAssistantVisibleText(text),
|
|
626
|
+
resolveTarget: ({ to, allowFrom, mode }) => {
|
|
627
|
+
const trimmed = to?.trim() ?? "";
|
|
628
|
+
const allowListRaw = normalizeStringEntries(allowFrom ?? []);
|
|
629
|
+
const hasWildcard = allowListRaw.includes("*");
|
|
630
|
+
const allowList = allowListRaw.filter((entry) => entry !== "*").map((entry) => normalizeTwitchMessagingTarget(entry)).filter((entry) => entry.length > 0);
|
|
631
|
+
const normalizedTo = normalizeTwitchMessagingTarget(trimmed);
|
|
632
|
+
if (normalizedTo && (!(mode === "implicit" || mode === "heartbeat") || hasWildcard || allowList.length === 0 || allowList.includes(normalizedTo))) return {
|
|
633
|
+
ok: true,
|
|
634
|
+
to: normalizedTo
|
|
635
|
+
};
|
|
636
|
+
return {
|
|
637
|
+
ok: false,
|
|
638
|
+
error: /* @__PURE__ */ new Error("Delivering to Twitch requires target <channel-name>")
|
|
639
|
+
};
|
|
640
|
+
},
|
|
641
|
+
sendText: async (params) => {
|
|
642
|
+
const { cfg, to, text, accountId } = params;
|
|
643
|
+
if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
|
|
644
|
+
const { account, accountId: normalizedAccountId, availableAccountIds, configured } = resolveTwitchAccountContext(cfg, accountId);
|
|
645
|
+
if (!account) throw new Error(`Twitch account not found: ${accountId ?? normalizedAccountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`);
|
|
646
|
+
const target = to.trim();
|
|
647
|
+
if (isTwitchDirectMessageTarget(target)) throw new Error("Delivering to Twitch requires target <channel-name>");
|
|
648
|
+
const deliveryChannel = normalizeTwitchMessagingTarget(target) || normalizeTwitchChannel(account.channel);
|
|
649
|
+
if (!deliveryChannel) throw new Error("No channel specified and no default channel in account config");
|
|
650
|
+
if (!configured) throw new Error(`Account ${normalizedAccountId} is not properly configured. Required: username, clientId, and accessToken (config or env for default account).`);
|
|
651
|
+
const result = await sendMessageTwitchInternal({
|
|
652
|
+
channel: deliveryChannel,
|
|
653
|
+
text,
|
|
654
|
+
cfg,
|
|
655
|
+
account,
|
|
656
|
+
accountId: normalizedAccountId,
|
|
657
|
+
clientManager: getClientManager(normalizedAccountId)
|
|
658
|
+
});
|
|
659
|
+
return {
|
|
660
|
+
channel: "twitch",
|
|
661
|
+
...result.outcome ? { outcome: result.outcome } : {},
|
|
662
|
+
messageId: result.messageId,
|
|
663
|
+
receipt: result.receipt,
|
|
664
|
+
timestamp: Date.now()
|
|
665
|
+
};
|
|
666
|
+
},
|
|
667
|
+
sendMedia: async (params) => {
|
|
668
|
+
const { text, mediaUrl } = params;
|
|
669
|
+
const message = mediaUrl ? `${text || ""} ${mediaUrl}`.trim() : text;
|
|
670
|
+
return twitchOutbound.sendText({
|
|
671
|
+
...params,
|
|
672
|
+
text: message
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
const twitchMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
677
|
+
id: "twitch",
|
|
678
|
+
outbound: twitchOutbound
|
|
679
|
+
});
|
|
680
|
+
// extensions/twitch/src/resolver.ts
|
|
681
|
+
const TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS = 1e4;
|
|
682
|
+
async function resolveTwitchTargets(inputs, account, _kind, log) {
|
|
683
|
+
if (!account.clientId || !account.accessToken) {
|
|
684
|
+
log?.error("Missing Twitch client ID or accessToken");
|
|
685
|
+
return inputs.map((input) => ({
|
|
686
|
+
input,
|
|
687
|
+
resolved: false,
|
|
688
|
+
note: "missing Twitch credentials"
|
|
689
|
+
}));
|
|
690
|
+
}
|
|
691
|
+
const normalizedToken = normalizeToken(account.accessToken);
|
|
692
|
+
const clientId = account.clientId;
|
|
693
|
+
let tokenValidated = false;
|
|
694
|
+
async function resolveHelixUser(query) {
|
|
695
|
+
const controller = new AbortController();
|
|
696
|
+
const fetchOptions = { signal: controller.signal };
|
|
697
|
+
const request = (async () => {
|
|
698
|
+
if (!tokenValidated) {
|
|
699
|
+
let tokenInfo;
|
|
700
|
+
try {
|
|
701
|
+
tokenInfo = await callTwitchApi({
|
|
702
|
+
type: "auth",
|
|
703
|
+
url: "validate"
|
|
704
|
+
}, clientId, normalizedToken, void 0, fetchOptions);
|
|
705
|
+
} catch (error) {
|
|
706
|
+
if (error instanceof HttpStatusCodeError && error.statusCode === 401) throw new Error("Invalid token supplied", { cause: error });
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
if (!tokenInfo.user_id) throw new Error("Trying to use an app access token as a user access token");
|
|
710
|
+
tokenValidated = true;
|
|
711
|
+
}
|
|
712
|
+
return (await callTwitchApi({
|
|
713
|
+
type: "helix",
|
|
714
|
+
url: "users",
|
|
715
|
+
query
|
|
716
|
+
}, clientId, normalizedToken, void 0, fetchOptions)).data[0] ?? null;
|
|
717
|
+
})();
|
|
718
|
+
try {
|
|
719
|
+
return await withTimeout(request, TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS, "Twitch Helix user lookup");
|
|
720
|
+
} finally {
|
|
721
|
+
controller.abort();
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
const results = [];
|
|
725
|
+
for (const input of inputs) {
|
|
726
|
+
const trimmed = input.trim();
|
|
727
|
+
const normalized = normalizeLowercaseStringOrEmpty(trimmed.startsWith("@") ? trimmed.slice(1) : trimmed);
|
|
728
|
+
if (!normalized) {
|
|
729
|
+
results.push({
|
|
730
|
+
input,
|
|
731
|
+
resolved: false,
|
|
732
|
+
note: "empty input"
|
|
733
|
+
});
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
const looksLikeUserId = /^\d+$/.test(normalized);
|
|
737
|
+
try {
|
|
738
|
+
const user = await resolveHelixUser(looksLikeUserId ? { id: normalized } : { login: normalized });
|
|
739
|
+
if (user) {
|
|
740
|
+
results.push({
|
|
741
|
+
input,
|
|
742
|
+
resolved: true,
|
|
743
|
+
id: user.id,
|
|
744
|
+
name: user.login,
|
|
745
|
+
...!looksLikeUserId ? { note: user.display_name !== user.login ? `display: ${user.display_name}` : void 0 } : {}
|
|
746
|
+
});
|
|
747
|
+
log?.debug?.(looksLikeUserId ? `Resolved user ID ${normalized} -> ${user.login}` : `Resolved username ${normalized} -> ${user.id} (${user.login})`);
|
|
748
|
+
} else {
|
|
749
|
+
results.push({
|
|
750
|
+
input,
|
|
751
|
+
resolved: false,
|
|
752
|
+
note: looksLikeUserId ? "user ID not found" : "username not found"
|
|
753
|
+
});
|
|
754
|
+
log?.warn(`${looksLikeUserId ? "User ID" : "Username"} ${normalized} not found`);
|
|
755
|
+
}
|
|
756
|
+
} catch (error) {
|
|
757
|
+
const errorMessage = formatErrorMessage(error);
|
|
758
|
+
results.push({
|
|
759
|
+
input,
|
|
760
|
+
resolved: false,
|
|
761
|
+
note: `API error: ${errorMessage}`
|
|
762
|
+
});
|
|
763
|
+
log?.error(`Failed to resolve ${input}: ${errorMessage}`);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return results;
|
|
767
|
+
}
|
|
768
|
+
// extensions/twitch/src/plugin.ts
|
|
769
|
+
function readSendValue(value) {
|
|
770
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value).trim() : void 0;
|
|
771
|
+
}
|
|
772
|
+
const twitchPlugin = createChatChannelPlugin({
|
|
773
|
+
pairing: {
|
|
774
|
+
idLabel: "twitchUserId",
|
|
775
|
+
normalizeAllowEntry: createPairingPrefixStripper(/^(twitch:)?user:?/i),
|
|
776
|
+
notifyApproval: createLoggedPairingApprovalNotifier(({ id }) => `Pairing approved for user ${id} (notification sent via chat if possible)`, console.warn)
|
|
777
|
+
},
|
|
778
|
+
threading: { matchesToolContextTarget: ({ target, toolContext }) => {
|
|
779
|
+
const channel = normalizeTwitchMessagingTarget(target);
|
|
780
|
+
return Boolean(channel) && [toolContext.currentChannelId, toolContext.currentMessagingTarget].some((current) => current != null && normalizeTwitchMessagingTarget(current) === channel);
|
|
781
|
+
} },
|
|
782
|
+
outbound: twitchOutbound,
|
|
783
|
+
base: {
|
|
784
|
+
id: "twitch",
|
|
785
|
+
meta: {
|
|
786
|
+
id: "twitch",
|
|
787
|
+
label: "Twitch",
|
|
788
|
+
selectionLabel: "Twitch (Chat)",
|
|
789
|
+
docsPath: "/channels/twitch",
|
|
790
|
+
blurb: "Twitch chat integration",
|
|
791
|
+
aliases: ["twitch-chat"]
|
|
792
|
+
},
|
|
793
|
+
setupContract: twitchSetupPlugin.setupContract,
|
|
794
|
+
setupWizard: twitchSetupPlugin.setupWizard,
|
|
795
|
+
reload: twitchSetupPlugin.reload,
|
|
796
|
+
capabilities: { chatTypes: ["group"] },
|
|
797
|
+
messaging: {
|
|
798
|
+
normalizeTarget: normalizeTwitchMessagingTarget,
|
|
799
|
+
targetResolver: {
|
|
800
|
+
looksLikeId: (input) => Boolean(normalizeTwitchMessagingTarget(input)),
|
|
801
|
+
hint: "<channel-name>"
|
|
802
|
+
},
|
|
803
|
+
inferTargetChatType: ({ to }) => normalizeTwitchMessagingTarget(to) ? "group" : void 0,
|
|
804
|
+
resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
|
|
805
|
+
const channel = normalizeTwitchMessagingTarget(target);
|
|
806
|
+
if (!channel) return null;
|
|
807
|
+
return buildChannelOutboundSessionRoute({
|
|
808
|
+
cfg,
|
|
809
|
+
agentId,
|
|
810
|
+
channel: "twitch",
|
|
811
|
+
accountId,
|
|
812
|
+
recipientSessionExact: true,
|
|
813
|
+
peer: {
|
|
814
|
+
kind: "group",
|
|
815
|
+
id: channel
|
|
816
|
+
},
|
|
817
|
+
chatType: "group",
|
|
818
|
+
from: `twitch:channel:${channel}`,
|
|
819
|
+
to: channel
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
},
|
|
823
|
+
message: twitchMessageAdapter,
|
|
824
|
+
configSchema: buildChannelConfigSchema(TwitchConfigSchema),
|
|
825
|
+
config: {
|
|
826
|
+
...twitchConfigAdapter,
|
|
827
|
+
describeAccount: (account) => account ? describeAccountSnapshot({
|
|
828
|
+
account,
|
|
829
|
+
configured: isAccountConfigured(account, account.accessToken)
|
|
830
|
+
}) : {
|
|
831
|
+
accountId: DEFAULT_ACCOUNT_ID$1,
|
|
832
|
+
enabled: false,
|
|
833
|
+
configured: false
|
|
834
|
+
}
|
|
835
|
+
},
|
|
836
|
+
actions: {
|
|
837
|
+
describeMessageTool: () => ({ actions: ["send"] }),
|
|
838
|
+
supportsAction: ({ action }) => action === "send",
|
|
839
|
+
extractToolSend: ({ args }) => {
|
|
840
|
+
const to = readSendValue(args.to);
|
|
841
|
+
const message = readSendValue(args.message);
|
|
842
|
+
return to && message ? {
|
|
843
|
+
to,
|
|
844
|
+
message
|
|
845
|
+
} : null;
|
|
846
|
+
}
|
|
847
|
+
},
|
|
848
|
+
resolver: { resolveTargets: async ({ cfg, accountId, inputs, kind, runtime }) => {
|
|
849
|
+
const account = getAccountConfig(cfg, accountId ?? resolveDefaultTwitchAccountId(cfg));
|
|
850
|
+
if (!account) return inputs.map((input) => ({
|
|
851
|
+
input,
|
|
852
|
+
resolved: false,
|
|
853
|
+
note: "account not configured"
|
|
854
|
+
}));
|
|
855
|
+
return await resolveTwitchTargets(inputs, account, kind, {
|
|
856
|
+
info: (msg) => runtime.log(msg),
|
|
857
|
+
warn: (msg) => runtime.log(msg),
|
|
858
|
+
error: (msg) => runtime.error(msg),
|
|
859
|
+
debug: (msg) => runtime.log(msg)
|
|
860
|
+
});
|
|
861
|
+
} },
|
|
862
|
+
status: createComputedAccountStatusAdapter({
|
|
863
|
+
defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$1),
|
|
864
|
+
buildChannelSummary: ({ snapshot }) => buildPassiveProbedChannelStatusSummary(snapshot),
|
|
865
|
+
probeAccount: async ({ account, timeoutMs }) => {
|
|
866
|
+
let client;
|
|
867
|
+
try {
|
|
868
|
+
return await runChannelProbe(void 0, async () => {
|
|
869
|
+
if (!account.accessToken || !account.username) return {
|
|
870
|
+
ok: false,
|
|
871
|
+
error: "missing credentials (accessToken, username)",
|
|
872
|
+
username: account.username
|
|
873
|
+
};
|
|
874
|
+
const rawToken = normalizeToken(account.accessToken.trim());
|
|
875
|
+
const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
|
|
876
|
+
const probeClient = new ChatClient({ authProvider });
|
|
877
|
+
client = probeClient;
|
|
878
|
+
const connectionPromise = new Promise((resolve, reject) => {
|
|
879
|
+
let settled = false;
|
|
880
|
+
const cleanup = () => {
|
|
881
|
+
if (settled) return;
|
|
882
|
+
settled = true;
|
|
883
|
+
authSuccessListener.unbind();
|
|
884
|
+
disconnectListener.unbind();
|
|
885
|
+
authFailListener.unbind();
|
|
886
|
+
};
|
|
887
|
+
const authSuccessListener = probeClient.onAuthenticationSuccess(() => {
|
|
888
|
+
cleanup();
|
|
889
|
+
resolve();
|
|
890
|
+
});
|
|
891
|
+
const disconnectListener = probeClient.onDisconnect((_manually, reason) => {
|
|
892
|
+
cleanup();
|
|
893
|
+
reject(reason || /* @__PURE__ */ new Error("Disconnected"));
|
|
894
|
+
});
|
|
895
|
+
const authFailListener = probeClient.onAuthenticationFailure(() => {
|
|
896
|
+
cleanup();
|
|
897
|
+
reject(/* @__PURE__ */ new Error("Authentication failed"));
|
|
898
|
+
});
|
|
899
|
+
});
|
|
900
|
+
await raceWithTimeout(() => {
|
|
901
|
+
probeClient.connect();
|
|
902
|
+
return connectionPromise;
|
|
903
|
+
}, timeoutMs, () => {
|
|
904
|
+
throw new Error(`timeout after ${timeoutMs}ms`);
|
|
905
|
+
});
|
|
906
|
+
client.quit();
|
|
907
|
+
client = void 0;
|
|
908
|
+
return {
|
|
909
|
+
ok: true,
|
|
910
|
+
connected: true,
|
|
911
|
+
username: account.username,
|
|
912
|
+
channel: account.channel
|
|
913
|
+
};
|
|
914
|
+
}, (error) => ({
|
|
915
|
+
ok: false,
|
|
916
|
+
error: formatErrorMessage(error),
|
|
917
|
+
username: account.username,
|
|
918
|
+
channel: account.channel
|
|
919
|
+
}));
|
|
920
|
+
} finally {
|
|
921
|
+
if (client) try {
|
|
922
|
+
client.quit();
|
|
923
|
+
} catch {}
|
|
924
|
+
}
|
|
925
|
+
},
|
|
926
|
+
collectStatusIssues: (accounts) => {
|
|
927
|
+
const issues = [];
|
|
928
|
+
for (const entry of accounts) {
|
|
929
|
+
const accountId = entry.accountId;
|
|
930
|
+
if (!accountId) continue;
|
|
931
|
+
const addIssue = (kind, message, fix) => issues.push({
|
|
932
|
+
channel: "twitch",
|
|
933
|
+
accountId,
|
|
934
|
+
kind,
|
|
935
|
+
message,
|
|
936
|
+
fix
|
|
937
|
+
});
|
|
938
|
+
if (!entry.configured) {
|
|
939
|
+
addIssue("config", "Twitch account is not properly configured", "Add required fields: username, accessToken, and clientId to your account configuration");
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
if (entry.enabled === false) {
|
|
943
|
+
addIssue("config", "Twitch account is disabled", "Set enabled: true in your account configuration to enable this account");
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
if (entry.lastError) addIssue("runtime", `Last error: ${entry.lastError}`, "Check your token validity and network connection. Check that the bot has the required OAuth scopes.");
|
|
947
|
+
if (!entry.running && !entry.lastStartAt && !entry.lastInboundAt && !entry.lastOutboundAt) addIssue("runtime", "Account has never connected successfully", "Start the Twitch gateway to begin receiving messages. Check logs for connection errors.");
|
|
948
|
+
if (entry.running && entry.lastStartAt) {
|
|
949
|
+
const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
|
|
950
|
+
if (daysSinceStart > 7) addIssue("runtime", `Connection has been running for ${Math.floor(daysSinceStart)} days`, "Consider restarting the connection periodically to refresh the connection. Twitch tokens may expire after long periods.");
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return issues;
|
|
954
|
+
},
|
|
955
|
+
resolveAccountSnapshot: ({ account, cfg }) => {
|
|
956
|
+
const { configured } = resolveTwitchAccountContext(cfg, account.accountId);
|
|
957
|
+
return {
|
|
958
|
+
accountId: account.accountId,
|
|
959
|
+
enabled: account.enabled !== false,
|
|
960
|
+
configured
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
}),
|
|
964
|
+
gateway: {
|
|
965
|
+
startAccount: async (ctx) => {
|
|
966
|
+
const account = ctx.account;
|
|
967
|
+
const accountId = ctx.accountId;
|
|
968
|
+
const channelRuntime = ctx.channelRuntime;
|
|
969
|
+
if (!channelRuntime?.inbound?.buildContext) throw new Error("Twitch requires its registered channel runtime context builder");
|
|
970
|
+
const statusSink = createAccountStatusSink({
|
|
971
|
+
accountId,
|
|
972
|
+
setStatus: ctx.setStatus
|
|
973
|
+
});
|
|
974
|
+
statusSink({
|
|
975
|
+
running: true,
|
|
976
|
+
lastStartAt: Date.now(),
|
|
977
|
+
lastError: null,
|
|
978
|
+
lifecycle: "starting"
|
|
979
|
+
});
|
|
980
|
+
ctx.log?.info(`Starting Twitch connection for ${account.username}`);
|
|
981
|
+
try {
|
|
982
|
+
await runPassiveAccountLifecycle({
|
|
983
|
+
abortSignal: ctx.abortSignal,
|
|
984
|
+
start: async () => {
|
|
985
|
+
const { monitorTwitchProvider } = await import("./monitor-DfA87gBg.mjs");
|
|
986
|
+
return monitorTwitchProvider({
|
|
987
|
+
account,
|
|
988
|
+
accountId,
|
|
989
|
+
channelRuntime,
|
|
990
|
+
config: ctx.cfg,
|
|
991
|
+
runtime: ctx.runtime,
|
|
992
|
+
abortSignal: ctx.abortSignal,
|
|
993
|
+
statusSink
|
|
994
|
+
});
|
|
995
|
+
},
|
|
996
|
+
stop: async (monitor) => {
|
|
997
|
+
await monitor.stop();
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
ctx.setStatus?.({
|
|
1002
|
+
accountId,
|
|
1003
|
+
running: false,
|
|
1004
|
+
lastStopAt: Date.now()
|
|
1005
|
+
});
|
|
1006
|
+
throw error;
|
|
1007
|
+
}
|
|
1008
|
+
},
|
|
1009
|
+
stopAccount: async (ctx) => {
|
|
1010
|
+
const account = ctx.account;
|
|
1011
|
+
const accountId = ctx.accountId;
|
|
1012
|
+
await removeClientManager(accountId);
|
|
1013
|
+
ctx.setStatus?.({
|
|
1014
|
+
accountId,
|
|
1015
|
+
running: false,
|
|
1016
|
+
lastStopAt: Date.now()
|
|
1017
|
+
});
|
|
1018
|
+
ctx.log?.info(`Stopped Twitch connection for ${account.username}`);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
export { setTwitchRuntime as a, getTwitchRuntime as i, sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };
|