@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.
@@ -1,851 +0,0 @@
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-8f7RsuJw.mjs";
2
- import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
3
- import { MarkdownConfigSchema, buildChannelConfigSchema } from "openclaw/plugin-sdk/channel-config-schema";
4
- import { buildChannelOutboundSessionRoute, createChatChannelPlugin, stripChannelTargetPrefix } from "openclaw/plugin-sdk/channel-core";
5
- import { createAccountStatusSink, createChannelMessageAdapterFromOutbound, createMessageReceiptFromOutboundResults, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
6
- import { createLoggedPairingApprovalNotifier, createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
7
- import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
8
- import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
9
- import { RefreshingAuthProvider, StaticAuthProvider } from "@twurple/auth";
10
- import { ChatClient, LogLevel } from "@twurple/chat";
11
- import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-resolution";
12
- import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
13
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
14
- import { captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
15
- import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
16
- import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
17
- import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
18
- import { z } from "zod";
19
- import { runChannelProbe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
20
- import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
21
- import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
22
- // extensions/twitch/src/actions.ts
23
- function readSendValue(value) {
24
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value).trim() : void 0;
25
- }
26
- const twitchMessageActions = {
27
- describeMessageTool: () => ({ actions: ["send"] }),
28
- supportsAction: ({ action }) => action === "send",
29
- extractToolSend: ({ args }) => {
30
- const to = readSendValue(args.to);
31
- const message = readSendValue(args.message);
32
- return to && message ? {
33
- to,
34
- message
35
- } : null;
36
- }
37
- };
38
- // extensions/twitch/src/twitch-client.ts
39
- const TWITCH_CHAT_AUTH_INTENTS = ["chat"];
40
- var TwitchClientManager = class {
41
- constructor(logger, statusSink) {
42
- this.logger = logger;
43
- this.statusSink = statusSink;
44
- this.clients = /* @__PURE__ */ new Map();
45
- this.pendingClients = /* @__PURE__ */ new Map();
46
- this.connectionPromises = /* @__PURE__ */ new Map();
47
- this.messageHandlers = /* @__PURE__ */ new Map();
48
- }
49
- setStatusSink(statusSink) {
50
- if (statusSink) this.statusSink = statusSink;
51
- }
52
- publishReady() {
53
- this.statusSink?.(channelReadyPatch());
54
- }
55
- publishRecovering(lastError) {
56
- this.statusSink?.({
57
- connected: false,
58
- lifecycle: "recovering",
59
- lastError
60
- });
61
- }
62
- async createAuthProvider(account, normalizedToken, clientId) {
63
- if (account.clientSecret) {
64
- const authProvider = new RefreshingAuthProvider({
65
- clientId,
66
- clientSecret: account.clientSecret
67
- });
68
- try {
69
- const userId = await authProvider.addUserForToken({
70
- accessToken: normalizedToken,
71
- refreshToken: account.refreshToken ?? null,
72
- expiresIn: account.expiresIn ?? null,
73
- obtainmentTimestamp: account.obtainmentTimestamp ?? Date.now()
74
- }, TWITCH_CHAT_AUTH_INTENTS);
75
- this.logger.info(`Added user ${userId} to RefreshingAuthProvider for ${account.username}`);
76
- } catch (err) {
77
- throw new Error(`Failed to add user to RefreshingAuthProvider: ${formatErrorMessage(err)}`, { cause: err });
78
- }
79
- authProvider.onRefresh((userId, token) => {
80
- this.logger.info(`Access token refreshed for user ${userId} (expires in ${token.expiresIn ? `${token.expiresIn}s` : "unknown"})`);
81
- });
82
- authProvider.onRefreshFailure((userId, error) => {
83
- this.logger.error(`Failed to refresh access token for user ${userId}: ${error.message}`);
84
- });
85
- const refreshStatus = account.refreshToken ? "automatic token refresh enabled" : "token refresh disabled (no refresh token)";
86
- this.logger.info(`Using RefreshingAuthProvider for ${account.username} (${refreshStatus})`);
87
- return authProvider;
88
- }
89
- this.logger.info(`Using StaticAuthProvider for ${account.username} (no clientSecret provided)`);
90
- return new StaticAuthProvider(clientId, normalizedToken);
91
- }
92
- async getClient(account, cfg, accountId) {
93
- const key = this.getAccountKey(account);
94
- const existing = this.clients.get(key);
95
- if (existing) return existing;
96
- const pending = this.connectionPromises.get(key);
97
- if (pending) return pending;
98
- const connection = this.createConnectedClient(key, account, () => this.connectionPromises.get(key) === connection, cfg, accountId);
99
- this.connectionPromises.set(key, connection);
100
- try {
101
- return await connection;
102
- } finally {
103
- if (this.connectionPromises.get(key) === connection) this.connectionPromises.delete(key);
104
- }
105
- }
106
- async createConnectedClient(key, account, ownsConnection, cfg, accountId) {
107
- const tokenResolution = resolveTwitchToken(cfg, { accountId });
108
- if (!tokenResolution.token) {
109
- const resolvedAccountId = accountId ?? DEFAULT_ACCOUNT_ID;
110
- const tokenConfigPath = cfg?.channels?.twitch?.accounts ? `channels.twitch.accounts.${resolvedAccountId}.accessToken` : "channels.twitch.accessToken";
111
- throw new Error(`Missing Twitch token for account ${resolvedAccountId} (set ${tokenConfigPath} or OPENCLAW_TWITCH_ACCESS_TOKEN for default)`);
112
- }
113
- this.logger.debug?.(`Using ${tokenResolution.source} token source for ${account.username}`);
114
- if (!account.clientId) {
115
- this.logger.error(`Missing Twitch client ID for account ${account.username}`);
116
- throw new Error("Missing Twitch client ID");
117
- }
118
- const normalizedToken = normalizeToken(tokenResolution.token);
119
- const authProvider = await this.createAuthProvider(account, normalizedToken, account.clientId);
120
- if (!ownsConnection()) throw new Error(`Twitch connection cancelled for ${account.username}`);
121
- const client = new ChatClient({
122
- authProvider,
123
- channels: [account.channel],
124
- rejoinChannelsOnReconnect: true,
125
- requestMembershipEvents: true,
126
- logger: {
127
- minLevel: LogLevel.WARNING,
128
- custom: { log: (level, message) => {
129
- switch (level) {
130
- case LogLevel.CRITICAL:
131
- case LogLevel.ERROR:
132
- this.logger.error(message);
133
- break;
134
- case LogLevel.WARNING:
135
- this.logger.warn(message);
136
- break;
137
- case LogLevel.INFO:
138
- this.logger.info(message);
139
- break;
140
- case LogLevel.DEBUG:
141
- case LogLevel.TRACE: this.logger.debug?.(message);
142
- }
143
- } }
144
- }
145
- });
146
- this.pendingClients.set(key, client);
147
- try {
148
- await this.connectClient(client, account);
149
- if (this.pendingClients.get(key) !== client) {
150
- client.quit();
151
- throw new Error(`Twitch connection cancelled for ${account.username}`);
152
- }
153
- } finally {
154
- if (this.pendingClients.get(key) === client) this.pendingClients.delete(key);
155
- }
156
- this.setupClientHandlers(client, account);
157
- this.clients.set(key, client);
158
- this.logger.info(`Connected to Twitch as ${account.username}`);
159
- return client;
160
- }
161
- async connectClient(client, account) {
162
- const connectTimeoutMs = 15e3;
163
- await new Promise((resolve, reject) => {
164
- let settled = false;
165
- let authRetryPending = false;
166
- const listeners = [];
167
- const finish = (error) => {
168
- if (settled) return;
169
- settled = true;
170
- clearTimeout(timeout);
171
- for (const listener of listeners) listener.unbind();
172
- if (error) {
173
- try {
174
- client.quit();
175
- } catch {}
176
- reject(error);
177
- return;
178
- }
179
- resolve();
180
- };
181
- listeners.push(client.onAuthenticationSuccess(() => {
182
- this.publishReady();
183
- finish();
184
- }), client.onAuthenticationFailure((text) => {
185
- authRetryPending = true;
186
- this.publishRecovering(text);
187
- this.logger.warn(`Twitch authentication failed for ${account.username}; waiting for retry, disconnect, or timeout: ${text}`);
188
- }), client.onDisconnect((manual, reason) => {
189
- if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
190
- if (authRetryPending && !manual) {
191
- this.logger.debug?.(`Twitch disconnected during auth retry for ${account.username}: ${formatErrorMessage(reason)}`);
192
- return;
193
- }
194
- finish(reason ?? /* @__PURE__ */ new Error(manual ? `Twitch connection cancelled for ${account.username}` : `Twitch disconnected before ready for ${account.username}`));
195
- }));
196
- const timeout = setTimeout(() => finish(/* @__PURE__ */ new Error(`Timed out connecting to Twitch as ${account.username}`)), connectTimeoutMs);
197
- timeout.unref?.();
198
- try {
199
- client.connect();
200
- } catch (error) {
201
- finish(error instanceof Error ? error : new Error(String(error)));
202
- }
203
- });
204
- }
205
- setupClientHandlers(client, account) {
206
- const key = this.getAccountKey(account);
207
- client.onMessage((channelName, _user, messageText, msg) => {
208
- const handler = this.messageHandlers.get(key)?.handler;
209
- if (handler) {
210
- const from = `twitch:${msg.userInfo.userName}`;
211
- this.logger.debug?.(`twitch inbound: channel=${channelName} from=${from} len=${messageText.length}`);
212
- handler({
213
- username: msg.userInfo.userName,
214
- displayName: msg.userInfo.displayName,
215
- userId: msg.userInfo.userId,
216
- message: messageText,
217
- channel: channelName,
218
- id: msg.id,
219
- timestamp: Date.now(),
220
- isMod: msg.userInfo.isMod,
221
- isOwner: msg.userInfo.isBroadcaster,
222
- isVip: msg.userInfo.isVip,
223
- isSub: msg.userInfo.isSubscriber,
224
- chatType: "group"
225
- });
226
- }
227
- });
228
- client.onAuthenticationSuccess(() => this.publishReady());
229
- client.onAuthenticationFailure((text) => {
230
- this.publishRecovering(text);
231
- });
232
- client.onDisconnect((manual, reason) => {
233
- if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
234
- });
235
- this.logger.info(`Set up handlers for ${key}`);
236
- }
237
- onMessage(account, handler) {
238
- const key = this.getAccountKey(account);
239
- const registration = { handler };
240
- this.messageHandlers.set(key, registration);
241
- return () => {
242
- if (this.messageHandlers.get(key) === registration) this.messageHandlers.delete(key);
243
- };
244
- }
245
- async disconnect(account) {
246
- const key = this.getAccountKey(account);
247
- const client = this.clients.get(key);
248
- const pendingClient = this.pendingClients.get(key);
249
- const pendingConnection = this.connectionPromises.delete(key);
250
- if (pendingClient) {
251
- pendingClient.quit();
252
- this.pendingClients.delete(key);
253
- }
254
- if (client) {
255
- client.quit();
256
- this.clients.delete(key);
257
- this.logger.info(`Disconnected ${key}`);
258
- }
259
- if (pendingConnection || pendingClient || client) this.messageHandlers.delete(key);
260
- }
261
- async disconnectAll() {
262
- this.pendingClients.forEach((client) => client.quit());
263
- this.clients.forEach((client) => client.quit());
264
- this.pendingClients.clear();
265
- this.connectionPromises.clear();
266
- this.clients.clear();
267
- this.messageHandlers.clear();
268
- this.logger.info(" Disconnected all clients");
269
- }
270
- async sendMessage(account, channel, message, cfg, accountId) {
271
- const effect = captureEffectAuthority();
272
- let preparingUse = false;
273
- try {
274
- const client = await this.getClient(account, cfg, accountId);
275
- const messageId = crypto.randomUUID();
276
- const chunks = chunkTextForOutbound(message, 500);
277
- preparingUse = true;
278
- const results = await effect.initiate(() => {
279
- preparingUse = false;
280
- return Promise.allSettled(chunks.map(async (chunk) => client.say(channel, chunk)));
281
- });
282
- const failure = results.find((result) => result.status === "rejected");
283
- if (failure) {
284
- if (results.some((result) => result.status === "fulfilled")) throw createChannelPartialDeliveryError(failure.reason, {
285
- messageIds: [messageId],
286
- visibleReplySent: true
287
- });
288
- throw failure.reason;
289
- }
290
- return {
291
- ok: true,
292
- messageId
293
- };
294
- } catch (error) {
295
- if (preparingUse || isChannelPartialDeliveryError(error)) throw error;
296
- const errorMessage = formatErrorMessage(error);
297
- this.logger.error(`Failed to send message: ${errorMessage}`);
298
- return {
299
- ok: false,
300
- error: errorMessage
301
- };
302
- }
303
- }
304
- getAccountKey(account) {
305
- return `${account.username}:${account.channel}`;
306
- }
307
- };
308
- // extensions/twitch/src/client-manager-registry.ts
309
- const registry = /* @__PURE__ */ new Map();
310
- function getOrCreateClientManager(accountId, logger, statusSink) {
311
- const existing = registry.get(accountId);
312
- if (existing) {
313
- existing.manager.setStatusSink(statusSink);
314
- return existing.manager;
315
- }
316
- const manager = new TwitchClientManager(logger, statusSink);
317
- registry.set(accountId, {
318
- manager,
319
- logger
320
- });
321
- logger.info(`Registered client manager for account: ${accountId}`);
322
- return manager;
323
- }
324
- function getClientManager(accountId) {
325
- return registry.get(accountId)?.manager;
326
- }
327
- async function removeClientManager(accountId) {
328
- const entry = registry.get(accountId);
329
- if (!entry) return;
330
- registry.delete(accountId);
331
- try {
332
- await entry.manager.disconnectAll();
333
- } finally {
334
- entry.logger.info(`Unregistered client manager for account: ${accountId}`);
335
- }
336
- }
337
- // extensions/twitch/src/config-schema.ts
338
- const TwitchRoleSchema = z.enum([
339
- "moderator",
340
- "owner",
341
- "vip",
342
- "subscriber",
343
- "all"
344
- ]);
345
- const TwitchAccountShape = {
346
- username: z.string(),
347
- /** Twitch OAuth access token (requires chat:read and chat:write scopes) */
348
- accessToken: z.string(),
349
- /** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
350
- clientId: z.string().optional(),
351
- channel: z.string().min(1),
352
- enabled: z.boolean().optional(),
353
- /** Allow channel-initiated configuration writes */
354
- configWrites: z.boolean().optional(),
355
- /** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
356
- allowFrom: z.array(z.string()).optional(),
357
- allowedRoles: z.array(TwitchRoleSchema).optional(),
358
- /** Require @mention to trigger bot responses */
359
- requireMention: z.boolean().optional(),
360
- responsePrefix: z.string().optional(),
361
- /** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
362
- clientSecret: z.string().optional(),
363
- /** Refresh token (required for automatic token refresh) */
364
- refreshToken: z.string().optional(),
365
- /** Token expiry time in seconds (optional, for token refresh tracking) */
366
- expiresIn: z.number().nullable().optional(),
367
- /** Timestamp when token was obtained (optional, for token refresh tracking) */
368
- obtainmentTimestamp: z.number().optional()
369
- };
370
- const TwitchAccountSchema = z.object(TwitchAccountShape);
371
- const TwitchConfigBaseShape = {
372
- name: z.string().optional(),
373
- enabled: z.boolean().optional(),
374
- configWrites: z.boolean().optional(),
375
- markdown: MarkdownConfigSchema.optional(),
376
- defaultAccount: z.string().optional(),
377
- historyLimit: z.number().int().min(0).optional(),
378
- responsePrefix: z.string().optional()
379
- };
380
- const SimplifiedSchema = z.object({
381
- ...TwitchConfigBaseShape,
382
- ...TwitchAccountShape
383
- });
384
- const MultiAccountSchema = z.object({
385
- ...TwitchConfigBaseShape,
386
- accounts: z.record(z.string(), TwitchAccountSchema)
387
- }).refine((val) => Object.keys(val.accounts).length > 0, { message: "accounts must contain at least one entry" });
388
- const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
389
- // extensions/twitch/src/send.ts
390
- function createTwitchSendReceipt(messageId, channel) {
391
- return createMessageReceiptFromOutboundResults({
392
- results: messageId ? [{
393
- channel: "twitch",
394
- messageId,
395
- conversationId: channel
396
- }] : [],
397
- kind: "text"
398
- });
399
- }
400
- async function sendMessageTwitchInternal(params) {
401
- 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();
402
- if (!cleanedText) return {
403
- outcome: "not_sent",
404
- messageId: "",
405
- receipt: createTwitchSendReceipt()
406
- };
407
- if (!params.clientManager) throw new Error(`Client manager not found for account: ${params.accountId}. Please start the Twitch gateway first.`);
408
- const result = await params.clientManager.sendMessage(params.account, params.channel, cleanedText, params.cfg, params.accountId);
409
- if (!result.ok) throw new Error(result.error);
410
- const { messageId } = result;
411
- return {
412
- messageId,
413
- receipt: createTwitchSendReceipt(messageId, params.channel)
414
- };
415
- }
416
- // extensions/twitch/src/outbound.ts
417
- const twitchOutbound = {
418
- deliveryMode: "direct",
419
- deliveryCapabilities: { durableFinal: {
420
- text: true,
421
- media: true,
422
- messageSendingHooks: true
423
- } },
424
- textChunkLimit: 500,
425
- sanitizeText: ({ text }) => sanitizeAssistantVisibleText(text),
426
- resolveTarget: ({ to, allowFrom, mode }) => {
427
- const trimmed = to?.trim() ?? "";
428
- const allowListRaw = normalizeStringEntries(allowFrom ?? []);
429
- const hasWildcard = allowListRaw.includes("*");
430
- const allowList = allowListRaw.filter((entry) => entry !== "*").map((entry) => normalizeTwitchChannel(entry)).filter((entry) => entry.length > 0);
431
- const normalizedTo = normalizeTwitchChannel(trimmed);
432
- if (normalizedTo && (!(mode === "implicit" || mode === "heartbeat") || hasWildcard || allowList.length === 0 || allowList.includes(normalizedTo))) return {
433
- ok: true,
434
- to: normalizedTo
435
- };
436
- return {
437
- ok: false,
438
- error: /* @__PURE__ */ new Error("Delivering to Twitch requires target <channel-name>")
439
- };
440
- },
441
- sendText: async (params) => {
442
- const { cfg, to, text, accountId } = params;
443
- if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
444
- const { account, accountId: normalizedAccountId, availableAccountIds, configured } = resolveTwitchAccountContext(cfg, accountId);
445
- if (!account) throw new Error(`Twitch account not found: ${accountId ?? normalizedAccountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`);
446
- const channel = to || account.channel;
447
- if (!channel) throw new Error("No channel specified and no default channel in account config");
448
- if (!configured) throw new Error(`Account ${normalizedAccountId} is not properly configured. Required: username, clientId, and accessToken (config or env for default account).`);
449
- const deliveryChannel = normalizeTwitchChannel(channel) || account.channel;
450
- if (!deliveryChannel) throw new Error("No channel specified and no default channel in account config");
451
- const result = await sendMessageTwitchInternal({
452
- channel: normalizeTwitchChannel(deliveryChannel),
453
- text,
454
- cfg,
455
- account,
456
- accountId: normalizedAccountId,
457
- clientManager: getClientManager(normalizedAccountId)
458
- });
459
- return {
460
- channel: "twitch",
461
- ...result.outcome ? { outcome: result.outcome } : {},
462
- messageId: result.messageId,
463
- receipt: result.receipt,
464
- timestamp: Date.now()
465
- };
466
- },
467
- sendMedia: async (params) => {
468
- const { text, mediaUrl } = params;
469
- if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
470
- const message = mediaUrl ? `${text || ""} ${mediaUrl}`.trim() : text;
471
- return twitchOutbound.sendText({
472
- ...params,
473
- text: message
474
- });
475
- }
476
- };
477
- const twitchMessageAdapter = createChannelMessageAdapterFromOutbound({
478
- id: "twitch",
479
- outbound: twitchOutbound
480
- });
481
- // extensions/twitch/src/probe.ts
482
- async function probeTwitch(account, timeoutMs) {
483
- let client;
484
- try {
485
- return await runChannelProbe(void 0, async () => {
486
- if (!account.accessToken || !account.username) return {
487
- ok: false,
488
- error: "missing credentials (accessToken, username)",
489
- username: account.username
490
- };
491
- const rawToken = normalizeToken(account.accessToken.trim());
492
- const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
493
- const probeClient = new ChatClient({ authProvider });
494
- client = probeClient;
495
- const connectionPromise = new Promise((resolve, reject) => {
496
- let settled = false;
497
- const cleanup = () => {
498
- if (settled) return;
499
- settled = true;
500
- connectListener.unbind();
501
- disconnectListener.unbind();
502
- authFailListener.unbind();
503
- };
504
- const connectListener = probeClient.onConnect(() => {
505
- cleanup();
506
- resolve();
507
- });
508
- const disconnectListener = probeClient.onDisconnect((_manually, reason) => {
509
- cleanup();
510
- reject(reason || /* @__PURE__ */ new Error("Disconnected"));
511
- });
512
- const authFailListener = probeClient.onAuthenticationFailure(() => {
513
- cleanup();
514
- reject(/* @__PURE__ */ new Error("Authentication failed"));
515
- });
516
- });
517
- await raceWithTimeout(() => {
518
- probeClient.connect();
519
- return connectionPromise;
520
- }, timeoutMs, () => {
521
- throw new Error(`timeout after ${timeoutMs}ms`);
522
- });
523
- client.quit();
524
- client = void 0;
525
- return {
526
- ok: true,
527
- connected: true,
528
- username: account.username,
529
- channel: account.channel
530
- };
531
- }, (error) => ({
532
- ok: false,
533
- error: formatErrorMessage(error),
534
- username: account.username,
535
- channel: account.channel
536
- }));
537
- } finally {
538
- if (client) try {
539
- client.quit();
540
- } catch {}
541
- }
542
- }
543
- // extensions/twitch/src/resolver.ts
544
- const TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS = 1e4;
545
- function normalizeUsername(input) {
546
- const trimmed = input.trim();
547
- if (trimmed.startsWith("@")) return normalizeLowercaseStringOrEmpty(trimmed.slice(1));
548
- return normalizeLowercaseStringOrEmpty(trimmed);
549
- }
550
- function createHelixUserResolver(clientId, accessToken) {
551
- let tokenValidated = false;
552
- return async (query) => {
553
- const controller = new AbortController();
554
- const fetchOptions = { signal: controller.signal };
555
- const request = (async () => {
556
- if (!tokenValidated) {
557
- let tokenInfo;
558
- try {
559
- tokenInfo = await callTwitchApi({
560
- type: "auth",
561
- url: "validate"
562
- }, clientId, accessToken, void 0, fetchOptions);
563
- } catch (error) {
564
- if (error instanceof HttpStatusCodeError && error.statusCode === 401) throw new Error("Invalid token supplied", { cause: error });
565
- throw error;
566
- }
567
- if (!tokenInfo.user_id) throw new Error("Trying to use an app access token as a user access token");
568
- tokenValidated = true;
569
- }
570
- return (await callTwitchApi({
571
- type: "helix",
572
- url: "users",
573
- query
574
- }, clientId, accessToken, void 0, fetchOptions)).data[0] ?? null;
575
- })();
576
- try {
577
- return await withTimeout(request, TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS, "Twitch Helix user lookup");
578
- } finally {
579
- controller.abort();
580
- }
581
- };
582
- }
583
- async function resolveTwitchTargets(inputs, account, _kind, log) {
584
- if (!account.clientId || !account.accessToken) {
585
- log?.error("Missing Twitch client ID or accessToken");
586
- return inputs.map((input) => ({
587
- input,
588
- resolved: false,
589
- note: "missing Twitch credentials"
590
- }));
591
- }
592
- const normalizedToken = normalizeToken(account.accessToken);
593
- const resolveHelixUser = createHelixUserResolver(account.clientId, normalizedToken);
594
- const results = [];
595
- for (const input of inputs) {
596
- const normalized = normalizeUsername(input);
597
- if (!normalized) {
598
- results.push({
599
- input,
600
- resolved: false,
601
- note: "empty input"
602
- });
603
- continue;
604
- }
605
- const looksLikeUserId = /^\d+$/.test(normalized);
606
- try {
607
- const user = await resolveHelixUser(looksLikeUserId ? { id: normalized } : { login: normalized });
608
- if (user) {
609
- results.push({
610
- input,
611
- resolved: true,
612
- id: user.id,
613
- name: user.login,
614
- ...!looksLikeUserId ? { note: user.display_name !== user.login ? `display: ${user.display_name}` : void 0 } : {}
615
- });
616
- log?.debug?.(looksLikeUserId ? `Resolved user ID ${normalized} -> ${user.login}` : `Resolved username ${normalized} -> ${user.id} (${user.login})`);
617
- } else {
618
- results.push({
619
- input,
620
- resolved: false,
621
- note: looksLikeUserId ? "user ID not found" : "username not found"
622
- });
623
- log?.warn(`${looksLikeUserId ? "User ID" : "Username"} ${normalized} not found`);
624
- }
625
- } catch (error) {
626
- const errorMessage = formatErrorMessage(error);
627
- results.push({
628
- input,
629
- resolved: false,
630
- note: `API error: ${errorMessage}`
631
- });
632
- log?.error(`Failed to resolve ${input}: ${errorMessage}`);
633
- }
634
- }
635
- return results;
636
- }
637
- // extensions/twitch/src/status.ts
638
- function collectTwitchStatusIssues(accounts) {
639
- const issues = [];
640
- for (const entry of accounts) {
641
- const accountId = entry.accountId;
642
- if (!accountId) continue;
643
- if (!entry.configured) {
644
- issues.push({
645
- channel: "twitch",
646
- accountId,
647
- kind: "config",
648
- message: "Twitch account is not properly configured",
649
- fix: "Add required fields: username, accessToken, and clientId to your account configuration"
650
- });
651
- continue;
652
- }
653
- if (entry.enabled === false) {
654
- issues.push({
655
- channel: "twitch",
656
- accountId,
657
- kind: "config",
658
- message: "Twitch account is disabled",
659
- fix: "Set enabled: true in your account configuration to enable this account"
660
- });
661
- continue;
662
- }
663
- if (entry.lastError) issues.push({
664
- channel: "twitch",
665
- accountId,
666
- kind: "runtime",
667
- message: `Last error: ${entry.lastError}`,
668
- fix: "Check your token validity and network connection. Check that the bot has the required OAuth scopes."
669
- });
670
- if (!entry.running && !entry.lastStartAt && !entry.lastInboundAt && !entry.lastOutboundAt) issues.push({
671
- channel: "twitch",
672
- accountId,
673
- kind: "runtime",
674
- message: "Account has never connected successfully",
675
- fix: "Start the Twitch gateway to begin receiving messages. Check logs for connection errors."
676
- });
677
- if (entry.running && entry.lastStartAt) {
678
- const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
679
- if (daysSinceStart > 7) issues.push({
680
- channel: "twitch",
681
- accountId,
682
- kind: "runtime",
683
- message: `Connection has been running for ${Math.floor(daysSinceStart)} days`,
684
- fix: "Consider restarting the connection periodically to refresh the connection. Twitch tokens may expire after long periods."
685
- });
686
- }
687
- }
688
- return issues;
689
- }
690
- // extensions/twitch/src/plugin.ts
691
- function normalizeTwitchMessagingTarget(target) {
692
- const providerTarget = stripChannelTargetPrefix(target, "twitch", "twitch-chat");
693
- const kindMatch = /^(user|dm|channel|group|conversation|room):/i.exec(providerTarget);
694
- const kind = kindMatch?.[1]?.toLowerCase();
695
- if (kind === "user" || kind === "dm") return "";
696
- const channelTarget = kindMatch ? providerTarget.slice(kindMatch[0].length) : providerTarget;
697
- return normalizeTwitchChannel(channelTarget);
698
- }
699
- const twitchPlugin = createChatChannelPlugin({
700
- pairing: {
701
- idLabel: "twitchUserId",
702
- normalizeAllowEntry: createPairingPrefixStripper(/^(twitch:)?user:?/i),
703
- notifyApproval: createLoggedPairingApprovalNotifier(({ id }) => `Pairing approved for user ${id} (notification sent via chat if possible)`, console.warn)
704
- },
705
- threading: { matchesToolContextTarget: ({ target, toolContext }) => {
706
- const channel = normalizeTwitchMessagingTarget(target);
707
- return Boolean(channel) && [toolContext.currentChannelId, toolContext.currentMessagingTarget].some((current) => current != null && normalizeTwitchMessagingTarget(current) === channel);
708
- } },
709
- outbound: twitchOutbound,
710
- base: {
711
- id: "twitch",
712
- meta: {
713
- id: "twitch",
714
- label: "Twitch",
715
- selectionLabel: "Twitch (Chat)",
716
- docsPath: "/channels/twitch",
717
- blurb: "Twitch chat integration",
718
- aliases: ["twitch-chat"]
719
- },
720
- setupContract: twitchSetupPlugin.setupContract,
721
- setupWizard: twitchSetupPlugin.setupWizard,
722
- reload: twitchSetupPlugin.reload,
723
- capabilities: { chatTypes: ["group"] },
724
- messaging: {
725
- normalizeTarget: normalizeTwitchMessagingTarget,
726
- targetResolver: {
727
- looksLikeId: (input) => Boolean(normalizeTwitchMessagingTarget(input)),
728
- hint: "<channel-name>"
729
- },
730
- inferTargetChatType: ({ to }) => normalizeTwitchMessagingTarget(to) ? "group" : void 0,
731
- resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
732
- const channel = normalizeTwitchMessagingTarget(target);
733
- if (!channel) return null;
734
- return buildChannelOutboundSessionRoute({
735
- cfg,
736
- agentId,
737
- channel: "twitch",
738
- accountId,
739
- recipientSessionExact: true,
740
- peer: {
741
- kind: "group",
742
- id: channel
743
- },
744
- chatType: "group",
745
- from: `twitch:channel:${channel}`,
746
- to: channel
747
- });
748
- }
749
- },
750
- message: twitchMessageAdapter,
751
- configSchema: buildChannelConfigSchema(TwitchConfigSchema),
752
- config: {
753
- ...twitchConfigAdapter,
754
- describeAccount: (account) => account ? describeAccountSnapshot({
755
- account,
756
- configured: isAccountConfigured(account, account.accessToken)
757
- }) : {
758
- accountId: DEFAULT_ACCOUNT_ID$1,
759
- enabled: false,
760
- configured: false
761
- }
762
- },
763
- actions: twitchMessageActions,
764
- resolver: { resolveTargets: async ({ cfg, accountId, inputs, kind, runtime }) => {
765
- const account = getAccountConfig(cfg, accountId ?? resolveDefaultTwitchAccountId(cfg));
766
- if (!account) return inputs.map((input) => ({
767
- input,
768
- resolved: false,
769
- note: "account not configured"
770
- }));
771
- return await resolveTwitchTargets(inputs, account, kind, {
772
- info: (msg) => runtime.log(msg),
773
- warn: (msg) => runtime.log(msg),
774
- error: (msg) => runtime.error(msg),
775
- debug: (msg) => runtime.log(msg)
776
- });
777
- } },
778
- status: createComputedAccountStatusAdapter({
779
- defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$1),
780
- buildChannelSummary: ({ snapshot }) => buildPassiveProbedChannelStatusSummary(snapshot),
781
- probeAccount: async ({ account, timeoutMs }) => await probeTwitch(account, timeoutMs),
782
- collectStatusIssues: collectTwitchStatusIssues,
783
- resolveAccountSnapshot: ({ account, cfg }) => {
784
- const { configured } = resolveTwitchAccountContext(cfg, account.accountId);
785
- return {
786
- accountId: account.accountId,
787
- enabled: account.enabled !== false,
788
- configured
789
- };
790
- }
791
- }),
792
- gateway: {
793
- startAccount: async (ctx) => {
794
- const account = ctx.account;
795
- const accountId = ctx.accountId;
796
- const channelRuntime = ctx.channelRuntime;
797
- if (!channelRuntime?.inbound?.buildContext) throw new Error("Twitch requires its registered channel runtime context builder");
798
- const statusSink = createAccountStatusSink({
799
- accountId,
800
- setStatus: ctx.setStatus
801
- });
802
- statusSink({
803
- running: true,
804
- lastStartAt: Date.now(),
805
- lastError: null,
806
- lifecycle: "starting"
807
- });
808
- ctx.log?.info(`Starting Twitch connection for ${account.username}`);
809
- try {
810
- await runPassiveAccountLifecycle({
811
- abortSignal: ctx.abortSignal,
812
- start: async () => {
813
- const { monitorTwitchProvider } = await import("./monitor-OlDdzwhV.mjs");
814
- return monitorTwitchProvider({
815
- account,
816
- accountId,
817
- channelRuntime,
818
- config: ctx.cfg,
819
- runtime: ctx.runtime,
820
- abortSignal: ctx.abortSignal,
821
- statusSink
822
- });
823
- },
824
- stop: async (monitor) => {
825
- await monitor.stop();
826
- }
827
- });
828
- } catch (error) {
829
- ctx.setStatus?.({
830
- accountId,
831
- running: false,
832
- lastStopAt: Date.now()
833
- });
834
- throw error;
835
- }
836
- },
837
- stopAccount: async (ctx) => {
838
- const account = ctx.account;
839
- const accountId = ctx.accountId;
840
- await removeClientManager(accountId);
841
- ctx.setStatus?.({
842
- accountId,
843
- running: false,
844
- lastStopAt: Date.now()
845
- });
846
- ctx.log?.info(`Stopped Twitch connection for ${account.username}`);
847
- }
848
- }
849
- }
850
- });
851
- export { sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };