@openclaw/twitch 2026.9.1-beta.1 → 2026.9.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/README.md +1 -1
- package/dist/api.js +1 -1
- package/dist/channel-plugin-api.js +1 -1
- package/dist/{monitor-iY6U867S.js → monitor-dCA7_7aW.js} +30 -31
- package/dist/{plugin-BkpBoc94.js → plugin-DwymE1gC.js} +212 -438
- package/dist/setup-plugin-api.js +1 -1
- package/dist/{setup-surface-1wrrTKpx.js → setup-surface-BZ2FXBoo.js} +5 -15
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -74,7 +74,7 @@ Multi-account config (advanced):
|
|
|
74
74
|
1. Create a dedicated Twitch account for the bot, then generate credentials: [Twitch Token Generator](https://twitchtokengenerator.com/)
|
|
75
75
|
- Select **Bot Token**
|
|
76
76
|
- Verify scopes `chat:read` and `chat:write` are selected
|
|
77
|
-
- Copy the **Access Token** to `
|
|
77
|
+
- Copy the **Access Token** to `accessToken` property
|
|
78
78
|
- Copy the **Client ID** to `clientId` property
|
|
79
79
|
2. Start the gateway
|
|
80
80
|
|
package/dist/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as twitchPlugin } from "./plugin-
|
|
1
|
+
import { t as twitchPlugin } from "./plugin-DwymE1gC.js";
|
|
2
2
|
export { twitchPlugin };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { n as sendMessageTwitchInternal, r as getOrCreateClientManager } from "./plugin-DwymE1gC.js";
|
|
2
|
+
import { p as normalizeTwitchChannel } from "./setup-surface-BZ2FXBoo.js";
|
|
3
3
|
import { t as getTwitchRuntime } from "./runtime-B5If4b0g.js";
|
|
4
4
|
import { createChannelIngressError, createChannelIngressMonitor } from "openclaw/plugin-sdk/channel-outbound";
|
|
5
5
|
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
@@ -14,21 +14,19 @@ const twitchUserIdentity = defineStableChannelIngressIdentity({
|
|
|
14
14
|
entryIdPrefix: "twitch-user-entry"
|
|
15
15
|
});
|
|
16
16
|
const twitchRoleIdentity = defineStableChannelIngressIdentity({
|
|
17
|
-
key: "
|
|
18
|
-
|
|
19
|
-
normalizeEntry: normalizeTwitchRole,
|
|
20
|
-
normalizeSubject: normalizeTwitchRole,
|
|
17
|
+
key: "sender-id",
|
|
18
|
+
normalizeEntry: () => null,
|
|
21
19
|
aliases: [
|
|
20
|
+
"moderator",
|
|
22
21
|
"owner",
|
|
23
22
|
"vip",
|
|
24
23
|
"subscriber"
|
|
25
24
|
].map((role) => ({
|
|
26
25
|
key: `role-${role}`,
|
|
27
26
|
kind: "role",
|
|
28
|
-
normalizeEntry: () => null,
|
|
27
|
+
normalizeEntry: (entry) => normalizeTwitchRole(entry) === role ? role : null,
|
|
29
28
|
normalizeSubject: normalizeTwitchRole
|
|
30
29
|
})),
|
|
31
|
-
isWildcardEntry: (entry) => normalizeTwitchRole(entry) === "all",
|
|
32
30
|
resolveEntryId: ({ entryIndex }) => `twitch-role-entry-${entryIndex + 1}`
|
|
33
31
|
});
|
|
34
32
|
async function checkTwitchAccessControl(params) {
|
|
@@ -36,10 +34,10 @@ async function checkTwitchAccessControl(params) {
|
|
|
36
34
|
const policyKind = resolveTwitchPolicyKind(account);
|
|
37
35
|
const resolved = await createChannelIngressResolver({
|
|
38
36
|
channelId: "twitch",
|
|
39
|
-
accountId:
|
|
37
|
+
accountId: params.accountId,
|
|
40
38
|
identity: policyKind === "role" ? twitchRoleIdentity : twitchUserIdentity
|
|
41
39
|
}).message({
|
|
42
|
-
subject:
|
|
40
|
+
subject: twitchSubject(message),
|
|
43
41
|
conversation: {
|
|
44
42
|
kind: "group",
|
|
45
43
|
id: message.channel
|
|
@@ -57,7 +55,7 @@ async function checkTwitchAccessControl(params) {
|
|
|
57
55
|
allowTextCommands: false,
|
|
58
56
|
order: "before-sender"
|
|
59
57
|
} },
|
|
60
|
-
groupAllowFrom: policyKind === "allowFrom" ? account.allowFrom : policyKind === "role" ? account.allowedRoles : void 0
|
|
58
|
+
groupAllowFrom: policyKind === "allowFrom" ? account.allowFrom : policyKind === "role" ? account.allowedRoles?.map((role) => role === "all" ? "*" : role) : void 0
|
|
61
59
|
});
|
|
62
60
|
const decision = resolved.ingress;
|
|
63
61
|
if (decision.decisiveGateId === "activation" && decision.admission !== "dispatch") return {
|
|
@@ -106,10 +104,11 @@ function resolveTwitchPolicyKind(account) {
|
|
|
106
104
|
if (account.allowedRoles && account.allowedRoles.length > 0) return "role";
|
|
107
105
|
return "open";
|
|
108
106
|
}
|
|
109
|
-
function
|
|
107
|
+
function twitchSubject(message) {
|
|
110
108
|
return {
|
|
111
|
-
stableId: message.
|
|
109
|
+
stableId: message.userId,
|
|
112
110
|
aliases: {
|
|
111
|
+
"role-moderator": message.isMod ? "moderator" : void 0,
|
|
113
112
|
"role-owner": message.isOwner ? "owner" : void 0,
|
|
114
113
|
"role-vip": message.isVip ? "vip" : void 0,
|
|
115
114
|
"role-subscriber": message.isSub ? "subscriber" : void 0
|
|
@@ -118,8 +117,7 @@ function twitchRoleSubject(message) {
|
|
|
118
117
|
}
|
|
119
118
|
function normalizeTwitchRole(value) {
|
|
120
119
|
const role = normalizeLowercaseStringOrEmpty(value);
|
|
121
|
-
|
|
122
|
-
return role === "moderator" || role === "owner" || role === "vip" || role === "subscriber" || role === "all" ? role : null;
|
|
120
|
+
return role === "moderator" || role === "owner" || role === "vip" || role === "subscriber" ? role : null;
|
|
123
121
|
}
|
|
124
122
|
function reasonForTwitchIngressDecision(decision) {
|
|
125
123
|
switch (decision.reasonCode) {
|
|
@@ -217,6 +215,7 @@ function createTwitchIngress(options) {
|
|
|
217
215
|
handedOff = true;
|
|
218
216
|
lifecycle.onDeferred();
|
|
219
217
|
},
|
|
218
|
+
onDeferredHeartbeat: () => lifecycle.onDeferredHeartbeat?.(),
|
|
220
219
|
onAbandoned: async () => {
|
|
221
220
|
handedOff = true;
|
|
222
221
|
await lifecycle.onAbandoned();
|
|
@@ -286,9 +285,9 @@ function createTwitchIngress(options) {
|
|
|
286
285
|
* Process an incoming Twitch message and dispatch to agent.
|
|
287
286
|
*/
|
|
288
287
|
async function processTwitchMessage(params) {
|
|
289
|
-
const { message, account, accountId, config, runtime,
|
|
288
|
+
const { message, account, accountId, config, runtime, channelRuntime, turnAdoptionLifecycle, statusSink } = params;
|
|
290
289
|
const cfg = config;
|
|
291
|
-
const route =
|
|
290
|
+
const route = channelRuntime.routing.resolveAgentRoute({
|
|
292
291
|
cfg,
|
|
293
292
|
channel: "twitch",
|
|
294
293
|
accountId,
|
|
@@ -300,6 +299,7 @@ async function processTwitchMessage(params) {
|
|
|
300
299
|
const exactAccess = await checkTwitchAccessControl({
|
|
301
300
|
message,
|
|
302
301
|
account,
|
|
302
|
+
accountId,
|
|
303
303
|
botUsername: normalizeLowercaseStringOrEmpty(account.username),
|
|
304
304
|
contextBinding: {
|
|
305
305
|
agentId: route.agentId,
|
|
@@ -309,7 +309,7 @@ async function processTwitchMessage(params) {
|
|
|
309
309
|
}
|
|
310
310
|
});
|
|
311
311
|
if (!exactAccess.allowed) return;
|
|
312
|
-
await
|
|
312
|
+
await channelRuntime.inbound.run({
|
|
313
313
|
channel: "twitch",
|
|
314
314
|
accountId,
|
|
315
315
|
raw: message,
|
|
@@ -335,7 +335,7 @@ async function processTwitchMessage(params) {
|
|
|
335
335
|
timestamp: input.timestamp,
|
|
336
336
|
body: input.rawText
|
|
337
337
|
});
|
|
338
|
-
const ctxPayload =
|
|
338
|
+
const ctxPayload = channelRuntime.inbound.buildContext({
|
|
339
339
|
channelIngress: exactAccess.channelIngress,
|
|
340
340
|
channel: "twitch",
|
|
341
341
|
accountId,
|
|
@@ -366,11 +366,6 @@ async function processTwitchMessage(params) {
|
|
|
366
366
|
commandBody: input.textForCommands
|
|
367
367
|
}
|
|
368
368
|
});
|
|
369
|
-
const tableMode = core.channel.text.resolveMarkdownTableMode({
|
|
370
|
-
cfg,
|
|
371
|
-
channel: "twitch",
|
|
372
|
-
accountId
|
|
373
|
-
});
|
|
374
369
|
return {
|
|
375
370
|
cfg,
|
|
376
371
|
channel: "twitch",
|
|
@@ -390,7 +385,6 @@ async function processTwitchMessage(params) {
|
|
|
390
385
|
account,
|
|
391
386
|
accountId,
|
|
392
387
|
config,
|
|
393
|
-
tableMode,
|
|
394
388
|
runtime
|
|
395
389
|
});
|
|
396
390
|
},
|
|
@@ -422,13 +416,17 @@ async function deliverTwitchReply(params) {
|
|
|
422
416
|
error: (msg) => runtime.error?.(msg),
|
|
423
417
|
debug: (msg) => runtime.log?.(msg)
|
|
424
418
|
});
|
|
425
|
-
|
|
426
|
-
|
|
419
|
+
if ((await sendMessageTwitchInternal({
|
|
420
|
+
channel,
|
|
421
|
+
text: [payload.text, ...resolveOutboundMediaUrls(payload)].filter(Boolean).join(" "),
|
|
422
|
+
cfg: config,
|
|
423
|
+
account,
|
|
424
|
+
accountId,
|
|
425
|
+
clientManager
|
|
426
|
+
})).outcome === "not_sent") {
|
|
427
427
|
runtime.error?.(`No text to send in reply payload`);
|
|
428
428
|
return { visibleReplySent: false };
|
|
429
429
|
}
|
|
430
|
-
const result = await clientManager.sendMessage(account, channel, textToSend, config, accountId);
|
|
431
|
-
if (!result.ok) throw new Error(result.error ?? "Send failed");
|
|
432
430
|
return { visibleReplySent: true };
|
|
433
431
|
} catch (err) {
|
|
434
432
|
runtime.error?.(`Failed to send reply: ${String(err)}`);
|
|
@@ -441,7 +439,7 @@ async function deliverTwitchReply(params) {
|
|
|
441
439
|
* Sets up message handlers and processes incoming messages.
|
|
442
440
|
*/
|
|
443
441
|
async function monitorTwitchProvider(options) {
|
|
444
|
-
const { account, accountId, config, runtime, abortSignal, statusSink } = options;
|
|
442
|
+
const { account, accountId, channelRuntime, config, runtime, abortSignal, statusSink } = options;
|
|
445
443
|
const core = getTwitchRuntime();
|
|
446
444
|
let stopped = false;
|
|
447
445
|
let stopTask;
|
|
@@ -472,6 +470,7 @@ async function monitorTwitchProvider(options) {
|
|
|
472
470
|
if (!(await checkTwitchAccessControl({
|
|
473
471
|
message,
|
|
474
472
|
account,
|
|
473
|
+
accountId,
|
|
475
474
|
botUsername
|
|
476
475
|
})).allowed) return;
|
|
477
476
|
statusSink?.({ lastInboundAt: Date.now() });
|
|
@@ -481,7 +480,7 @@ async function monitorTwitchProvider(options) {
|
|
|
481
480
|
accountId,
|
|
482
481
|
config,
|
|
483
482
|
runtime,
|
|
484
|
-
|
|
483
|
+
channelRuntime,
|
|
485
484
|
turnAdoptionLifecycle,
|
|
486
485
|
statusSink
|
|
487
486
|
});
|
|
@@ -1,20 +1,85 @@
|
|
|
1
|
-
import { a as getAccountConfig, c as resolveTwitchSnapshotAccountId, d as
|
|
1
|
+
import { a as getAccountConfig, c as resolveTwitchSnapshotAccountId, d as missingTargetError, f as normalizeToken, i as DEFAULT_ACCOUNT_ID, l as twitchConfigAdapter, m as resolveTwitchToken, o as resolveDefaultTwitchAccountId, p as normalizeTwitchChannel, r as twitchSetupWizard, s as resolveTwitchAccountContext, t as twitchSetupContract, u as isAccountConfigured } from "./setup-surface-BZ2FXBoo.js";
|
|
2
2
|
import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
|
|
3
3
|
import { MarkdownConfigSchema, buildChannelConfigSchema } from "openclaw/plugin-sdk/channel-config-schema";
|
|
4
4
|
import { buildChannelOutboundSessionRoute, createChatChannelPlugin, stripChannelTargetPrefix } from "openclaw/plugin-sdk/channel-core";
|
|
5
|
-
import { createAccountStatusSink,
|
|
5
|
+
import { createAccountStatusSink, createChannelMessageAdapterFromOutbound, createMessageReceiptFromOutboundResults, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
|
|
6
6
|
import { createLoggedPairingApprovalNotifier, createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
|
|
7
7
|
import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
|
|
8
8
|
import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
|
|
9
|
-
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
10
|
-
import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
11
|
-
import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
|
|
12
9
|
import { RefreshingAuthProvider, StaticAuthProvider } from "@twurple/auth";
|
|
13
10
|
import { ChatClient, LogLevel } from "@twurple/chat";
|
|
11
|
+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
14
12
|
import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
|
|
13
|
+
import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
|
|
15
14
|
import { runChannelProbe, sliceUtf16Safe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
15
|
+
import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
16
16
|
import { z } from "zod";
|
|
17
17
|
import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
|
|
18
|
+
//#region extensions/twitch/src/actions.ts
|
|
19
|
+
/**
|
|
20
|
+
* Read a string parameter from action arguments.
|
|
21
|
+
*
|
|
22
|
+
* @param args - Action arguments
|
|
23
|
+
* @param key - Parameter key
|
|
24
|
+
* @param options - Options for reading the parameter
|
|
25
|
+
* @returns The parameter value or undefined if not found
|
|
26
|
+
*/
|
|
27
|
+
function readStringParam(args, key, options = {}) {
|
|
28
|
+
const value = args[key];
|
|
29
|
+
if (value === void 0 || value === null) {
|
|
30
|
+
if (options.required) throw new Error(`Missing required parameter: ${key}`);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === "string") return options.trim !== false ? value.trim() : value;
|
|
34
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
35
|
+
const str = String(value);
|
|
36
|
+
return options.trim !== false ? str.trim() : str;
|
|
37
|
+
}
|
|
38
|
+
throw new Error(`Parameter ${key} must be a string, number, or boolean`);
|
|
39
|
+
}
|
|
40
|
+
/** Supported Twitch actions */
|
|
41
|
+
const TWITCH_ACTIONS = /* @__PURE__ */ new Set(["send"]);
|
|
42
|
+
/**
|
|
43
|
+
* Twitch message actions adapter.
|
|
44
|
+
*/
|
|
45
|
+
const twitchMessageActions = {
|
|
46
|
+
/**
|
|
47
|
+
* List available actions for this channel.
|
|
48
|
+
*/
|
|
49
|
+
describeMessageTool: () => ({ actions: [...TWITCH_ACTIONS] }),
|
|
50
|
+
/**
|
|
51
|
+
* Check if an action is supported.
|
|
52
|
+
*/
|
|
53
|
+
supportsAction: ({ action }) => TWITCH_ACTIONS.has(action),
|
|
54
|
+
/**
|
|
55
|
+
* Extract tool send parameters from action arguments.
|
|
56
|
+
*
|
|
57
|
+
* Parses and validates the "to" and "message" parameters for sending.
|
|
58
|
+
*
|
|
59
|
+
* @param params - Arguments from the tool call
|
|
60
|
+
* @returns Parsed send parameters or null if invalid
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* const result = twitchMessageActions.extractToolSend!({
|
|
64
|
+
* args: { to: "#mychannel", message: "Hello!" }
|
|
65
|
+
* });
|
|
66
|
+
* // Returns: { to: "#mychannel", message: "Hello!" }
|
|
67
|
+
*/
|
|
68
|
+
extractToolSend: ({ args }) => {
|
|
69
|
+
try {
|
|
70
|
+
const to = readStringParam(args, "to", { required: true });
|
|
71
|
+
const message = readStringParam(args, "message", { required: true });
|
|
72
|
+
if (!to || !message) return null;
|
|
73
|
+
return {
|
|
74
|
+
to,
|
|
75
|
+
message
|
|
76
|
+
};
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
//#endregion
|
|
18
83
|
//#region extensions/twitch/src/twitch-client.ts
|
|
19
84
|
const TWITCH_CHAT_AUTH_INTENTS = ["chat"];
|
|
20
85
|
/**
|
|
@@ -132,9 +197,7 @@ var TwitchClientManager = class {
|
|
|
132
197
|
case LogLevel.DEBUG:
|
|
133
198
|
this.logger.debug?.(message);
|
|
134
199
|
break;
|
|
135
|
-
case LogLevel.TRACE:
|
|
136
|
-
this.logger.debug?.(message);
|
|
137
|
-
break;
|
|
200
|
+
case LogLevel.TRACE: this.logger.debug?.(message);
|
|
138
201
|
}
|
|
139
202
|
} }
|
|
140
203
|
}
|
|
@@ -301,10 +364,11 @@ var TwitchClientManager = class {
|
|
|
301
364
|
messageId
|
|
302
365
|
};
|
|
303
366
|
} catch (error) {
|
|
304
|
-
|
|
367
|
+
const errorMessage = formatErrorMessage(error);
|
|
368
|
+
this.logger.error(`Failed to send message: ${errorMessage}`);
|
|
305
369
|
return {
|
|
306
370
|
ok: false,
|
|
307
|
-
error:
|
|
371
|
+
error: errorMessage
|
|
308
372
|
};
|
|
309
373
|
}
|
|
310
374
|
}
|
|
@@ -314,15 +378,6 @@ var TwitchClientManager = class {
|
|
|
314
378
|
getAccountKey(account) {
|
|
315
379
|
return `${account.username}:${account.channel}`;
|
|
316
380
|
}
|
|
317
|
-
/**
|
|
318
|
-
* Clear all clients and handlers (for testing)
|
|
319
|
-
*/
|
|
320
|
-
clearForTest() {
|
|
321
|
-
this.clients.clear();
|
|
322
|
-
this.pendingClients.clear();
|
|
323
|
-
this.connectionPromises.clear();
|
|
324
|
-
this.messageHandlers.clear();
|
|
325
|
-
}
|
|
326
381
|
};
|
|
327
382
|
//#endregion
|
|
328
383
|
//#region extensions/twitch/src/client-manager-registry.ts
|
|
@@ -386,6 +441,94 @@ async function removeClientManager(accountId) {
|
|
|
386
441
|
}
|
|
387
442
|
}
|
|
388
443
|
//#endregion
|
|
444
|
+
//#region extensions/twitch/src/config-schema.ts
|
|
445
|
+
/**
|
|
446
|
+
* Twitch user roles that can be allowed to interact with the bot
|
|
447
|
+
*/
|
|
448
|
+
const TwitchRoleSchema = z.enum([
|
|
449
|
+
"moderator",
|
|
450
|
+
"owner",
|
|
451
|
+
"vip",
|
|
452
|
+
"subscriber",
|
|
453
|
+
"all"
|
|
454
|
+
]);
|
|
455
|
+
const TwitchAccountShape = {
|
|
456
|
+
/** Twitch username */
|
|
457
|
+
username: z.string(),
|
|
458
|
+
/** Twitch OAuth access token (requires chat:read and chat:write scopes) */
|
|
459
|
+
accessToken: z.string(),
|
|
460
|
+
/** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
|
|
461
|
+
clientId: z.string().optional(),
|
|
462
|
+
/** Channel name to join */
|
|
463
|
+
channel: z.string().min(1),
|
|
464
|
+
/** Enable this account */
|
|
465
|
+
enabled: z.boolean().optional(),
|
|
466
|
+
/** Allow channel-initiated configuration writes */
|
|
467
|
+
configWrites: z.boolean().optional(),
|
|
468
|
+
/** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
|
|
469
|
+
allowFrom: z.array(z.string()).optional(),
|
|
470
|
+
/** Roles allowed to interact with the bot (e.g., ["moderator", "vip", "subscriber"]) */
|
|
471
|
+
allowedRoles: z.array(TwitchRoleSchema).optional(),
|
|
472
|
+
/** Require @mention to trigger bot responses */
|
|
473
|
+
requireMention: z.boolean().optional(),
|
|
474
|
+
/** Outbound response prefix override for this channel/account. */
|
|
475
|
+
responsePrefix: z.string().optional(),
|
|
476
|
+
/** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
|
|
477
|
+
clientSecret: z.string().optional(),
|
|
478
|
+
/** Refresh token (required for automatic token refresh) */
|
|
479
|
+
refreshToken: z.string().optional(),
|
|
480
|
+
/** Token expiry time in seconds (optional, for token refresh tracking) */
|
|
481
|
+
expiresIn: z.number().nullable().optional(),
|
|
482
|
+
/** Timestamp when token was obtained (optional, for token refresh tracking) */
|
|
483
|
+
obtainmentTimestamp: z.number().optional()
|
|
484
|
+
};
|
|
485
|
+
/**
|
|
486
|
+
* Twitch account configuration schema
|
|
487
|
+
*/
|
|
488
|
+
const TwitchAccountSchema = z.object(TwitchAccountShape);
|
|
489
|
+
/**
|
|
490
|
+
* Base configuration properties shared by both single and multi-account modes
|
|
491
|
+
*/
|
|
492
|
+
const TwitchConfigBaseShape = {
|
|
493
|
+
name: z.string().optional(),
|
|
494
|
+
enabled: z.boolean().optional(),
|
|
495
|
+
configWrites: z.boolean().optional(),
|
|
496
|
+
markdown: MarkdownConfigSchema.optional(),
|
|
497
|
+
defaultAccount: z.string().optional(),
|
|
498
|
+
historyLimit: z.number().int().min(0).optional(),
|
|
499
|
+
responsePrefix: z.string().optional()
|
|
500
|
+
};
|
|
501
|
+
/**
|
|
502
|
+
* Simplified single-account configuration schema
|
|
503
|
+
*
|
|
504
|
+
* Use this for single-account setups. Properties are at the top level,
|
|
505
|
+
* creating an implicit "default" account.
|
|
506
|
+
*/
|
|
507
|
+
const SimplifiedSchema = z.object({
|
|
508
|
+
...TwitchConfigBaseShape,
|
|
509
|
+
...TwitchAccountShape
|
|
510
|
+
});
|
|
511
|
+
/**
|
|
512
|
+
* Multi-account configuration schema
|
|
513
|
+
*
|
|
514
|
+
* Use this for multi-account setups. Each key is an account ID (e.g., "default", "secondary").
|
|
515
|
+
*/
|
|
516
|
+
const MultiAccountSchema = z.object({
|
|
517
|
+
...TwitchConfigBaseShape,
|
|
518
|
+
/** Per-account configuration (for multi-account setups) */
|
|
519
|
+
accounts: z.record(z.string(), TwitchAccountSchema)
|
|
520
|
+
}).refine((val) => Object.keys(val.accounts || {}).length > 0, { message: "accounts must contain at least one entry" });
|
|
521
|
+
/**
|
|
522
|
+
* Twitch plugin configuration schema
|
|
523
|
+
*
|
|
524
|
+
* Supports two mutually exclusive patterns:
|
|
525
|
+
* 1. Simplified single-account: username, accessToken, clientId, channel at top level
|
|
526
|
+
* 2. Multi-account: accounts object with named account configs
|
|
527
|
+
*
|
|
528
|
+
* The union ensures clear discrimination between the two modes.
|
|
529
|
+
*/
|
|
530
|
+
const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
|
|
531
|
+
//#endregion
|
|
389
532
|
//#region extensions/twitch/src/utils/markdown.ts
|
|
390
533
|
/**
|
|
391
534
|
* Markdown utilities for Twitch chat
|
|
@@ -396,158 +539,33 @@ async function removeClientManager(accountId) {
|
|
|
396
539
|
function stripMarkdownForTwitch(markdown) {
|
|
397
540
|
return stripMarkdown(markdown, { linkStyle: "label-and-url" }).replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n/g, " ").replace(/[ \t]{2,}/g, " ").trim();
|
|
398
541
|
}
|
|
399
|
-
/**
|
|
400
|
-
* Simple word-boundary chunker for Twitch (500 char limit).
|
|
401
|
-
* Strips markdown before chunking to avoid breaking markdown patterns.
|
|
402
|
-
*
|
|
403
|
-
* @param text - The text to chunk
|
|
404
|
-
* @param limit - Maximum characters per chunk (Twitch limit is 500)
|
|
405
|
-
* @returns Array of text chunks
|
|
406
|
-
*/
|
|
407
|
-
function chunkTextForTwitch(text, limit) {
|
|
408
|
-
const cleaned = stripMarkdownForTwitch(text);
|
|
409
|
-
if (!cleaned) return [];
|
|
410
|
-
return chunkTextForOutbound(cleaned, limit);
|
|
411
|
-
}
|
|
412
542
|
//#endregion
|
|
413
543
|
//#region extensions/twitch/src/send.ts
|
|
414
|
-
|
|
415
|
-
* Twitch message sending functions with dependency injection support.
|
|
416
|
-
*
|
|
417
|
-
* These functions are the primary interface for sending messages to Twitch.
|
|
418
|
-
* They support dependency injection via the `deps` parameter for testability.
|
|
419
|
-
*/
|
|
420
|
-
function createTwitchSendReceipt(params) {
|
|
421
|
-
const messageId = params.messageId.trim();
|
|
422
|
-
const conversationId = params.channel?.trim();
|
|
544
|
+
function createTwitchSendReceipt(messageId, channel) {
|
|
423
545
|
return createMessageReceiptFromOutboundResults({
|
|
424
|
-
results:
|
|
546
|
+
results: messageId ? [{
|
|
425
547
|
channel: "twitch",
|
|
426
548
|
messageId,
|
|
427
|
-
|
|
549
|
+
conversationId: channel
|
|
428
550
|
}] : [],
|
|
429
551
|
kind: "text"
|
|
430
552
|
});
|
|
431
553
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
*
|
|
435
|
-
* This function has access to the full OpenClaw config and handles
|
|
436
|
-
* account resolution, markdown stripping, and actual message sending.
|
|
437
|
-
*
|
|
438
|
-
* @param channel - The channel name
|
|
439
|
-
* @param text - The message text
|
|
440
|
-
* @param cfg - Full OpenClaw configuration
|
|
441
|
-
* @param accountId - Account ID to use
|
|
442
|
-
* @param stripMarkdown - Whether to strip markdown (default: true)
|
|
443
|
-
* @param logger - Logger instance
|
|
444
|
-
* @returns Result with message ID and status
|
|
445
|
-
*
|
|
446
|
-
* @example
|
|
447
|
-
* const result = await sendMessageTwitchInternal(
|
|
448
|
-
* "#mychannel",
|
|
449
|
-
* "Hello Twitch!",
|
|
450
|
-
* openclawConfig,
|
|
451
|
-
* "default",
|
|
452
|
-
* true,
|
|
453
|
-
* console,
|
|
454
|
-
* );
|
|
455
|
-
*/
|
|
456
|
-
async function sendMessageTwitchInternal(channel, text, cfg, accountId, stripMarkdown = true, logger = console) {
|
|
457
|
-
const { account, configured, availableAccountIds, accountId: resolvedAccountId } = resolveTwitchAccountContext(cfg, accountId);
|
|
458
|
-
if (!account) return {
|
|
459
|
-
ok: false,
|
|
460
|
-
messageId: generateMessageId(),
|
|
461
|
-
receipt: createTwitchSendReceipt({
|
|
462
|
-
messageId: "",
|
|
463
|
-
channel,
|
|
464
|
-
visible: false
|
|
465
|
-
}),
|
|
466
|
-
error: `Account not found: ${accountId ?? "(default)"}. Available accounts: ${availableAccountIds.join(", ") || "none"}`
|
|
467
|
-
};
|
|
468
|
-
if (!configured) return {
|
|
469
|
-
ok: false,
|
|
470
|
-
messageId: generateMessageId(),
|
|
471
|
-
receipt: createTwitchSendReceipt({
|
|
472
|
-
messageId: "",
|
|
473
|
-
channel,
|
|
474
|
-
visible: false
|
|
475
|
-
}),
|
|
476
|
-
error: `Account ${resolvedAccountId} is not properly configured. Required: username, clientId, and token (config or env for default account).`
|
|
477
|
-
};
|
|
478
|
-
const normalizedChannel = channel || account.channel;
|
|
479
|
-
if (!normalizedChannel) return {
|
|
480
|
-
ok: false,
|
|
481
|
-
messageId: generateMessageId(),
|
|
482
|
-
receipt: createTwitchSendReceipt({
|
|
483
|
-
messageId: "",
|
|
484
|
-
channel: normalizedChannel,
|
|
485
|
-
visible: false
|
|
486
|
-
}),
|
|
487
|
-
error: "No channel specified and no default channel in account config"
|
|
488
|
-
};
|
|
489
|
-
const deliveryChannel = normalizeTwitchChannel(normalizedChannel);
|
|
490
|
-
const cleanedText = stripMarkdown ? stripMarkdownForTwitch(text) : text;
|
|
554
|
+
async function sendMessageTwitchInternal(params) {
|
|
555
|
+
const cleanedText = stripMarkdownForTwitch(params.text);
|
|
491
556
|
if (!cleanedText) return {
|
|
492
|
-
|
|
493
|
-
messageId: "
|
|
494
|
-
receipt: createTwitchSendReceipt(
|
|
495
|
-
messageId: "skipped",
|
|
496
|
-
channel: deliveryChannel,
|
|
497
|
-
visible: false
|
|
498
|
-
})
|
|
557
|
+
outcome: "not_sent",
|
|
558
|
+
messageId: "",
|
|
559
|
+
receipt: createTwitchSendReceipt()
|
|
499
560
|
};
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
visible: false
|
|
508
|
-
}),
|
|
509
|
-
error: `Client manager not found for account: ${resolvedAccountId}. Please start the Twitch gateway first.`
|
|
561
|
+
if (!params.clientManager) throw new Error(`Client manager not found for account: ${params.accountId}. Please start the Twitch gateway first.`);
|
|
562
|
+
const result = await params.clientManager.sendMessage(params.account, params.channel, cleanedText, params.cfg, params.accountId);
|
|
563
|
+
if (!result.ok) throw new Error(result.error);
|
|
564
|
+
const { messageId } = result;
|
|
565
|
+
return {
|
|
566
|
+
messageId,
|
|
567
|
+
receipt: createTwitchSendReceipt(messageId, params.channel)
|
|
510
568
|
};
|
|
511
|
-
try {
|
|
512
|
-
const result = await clientManager.sendMessage(account, deliveryChannel, cleanedText, cfg, resolvedAccountId);
|
|
513
|
-
if (!result.ok) {
|
|
514
|
-
const messageId = result.messageId ?? generateMessageId();
|
|
515
|
-
return {
|
|
516
|
-
ok: false,
|
|
517
|
-
messageId,
|
|
518
|
-
receipt: createTwitchSendReceipt({
|
|
519
|
-
messageId,
|
|
520
|
-
channel: deliveryChannel,
|
|
521
|
-
visible: false
|
|
522
|
-
}),
|
|
523
|
-
error: result.error ?? "Send failed"
|
|
524
|
-
};
|
|
525
|
-
}
|
|
526
|
-
const messageId = result.messageId ?? generateMessageId();
|
|
527
|
-
return {
|
|
528
|
-
ok: true,
|
|
529
|
-
messageId,
|
|
530
|
-
receipt: createTwitchSendReceipt({
|
|
531
|
-
messageId,
|
|
532
|
-
channel: deliveryChannel,
|
|
533
|
-
visible: true
|
|
534
|
-
})
|
|
535
|
-
};
|
|
536
|
-
} catch (error) {
|
|
537
|
-
const errorMsg = formatErrorMessage(error);
|
|
538
|
-
const messageId = generateMessageId();
|
|
539
|
-
logger.error(`Failed to send message: ${errorMsg}`);
|
|
540
|
-
return {
|
|
541
|
-
ok: false,
|
|
542
|
-
messageId,
|
|
543
|
-
receipt: createTwitchSendReceipt({
|
|
544
|
-
messageId,
|
|
545
|
-
channel: deliveryChannel,
|
|
546
|
-
visible: false
|
|
547
|
-
}),
|
|
548
|
-
error: errorMsg
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
569
|
}
|
|
552
570
|
//#endregion
|
|
553
571
|
//#region extensions/twitch/src/outbound.ts
|
|
@@ -571,12 +589,9 @@ const twitchOutbound = {
|
|
|
571
589
|
media: true,
|
|
572
590
|
messageSendingHooks: true
|
|
573
591
|
} },
|
|
574
|
-
/** Twitch chat message limit is 500 characters */
|
|
575
592
|
textChunkLimit: 500,
|
|
576
593
|
/** Strip internal assistant tool-trace scaffolding before delivery */
|
|
577
594
|
sanitizeText: ({ text }) => sanitizeAssistantVisibleText(text),
|
|
578
|
-
/** Word-boundary chunker with markdown stripping */
|
|
579
|
-
chunker: chunkTextForTwitch,
|
|
580
595
|
/**
|
|
581
596
|
* Resolve target from context.
|
|
582
597
|
*
|
|
@@ -624,7 +639,7 @@ const twitchOutbound = {
|
|
|
624
639
|
/**
|
|
625
640
|
* Send a text message to a Twitch channel.
|
|
626
641
|
*
|
|
627
|
-
* Strips
|
|
642
|
+
* Strips Markdown, validates account configuration,
|
|
628
643
|
* and sends the message via the Twitch client.
|
|
629
644
|
*
|
|
630
645
|
* @param params - Send parameters including target, text, and config
|
|
@@ -642,14 +657,24 @@ const twitchOutbound = {
|
|
|
642
657
|
const { cfg, to, text, accountId } = params;
|
|
643
658
|
if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
|
|
644
659
|
const resolvedAccountId = accountId ?? resolveTwitchAccountContext(cfg).accountId;
|
|
645
|
-
const { account, availableAccountIds } = resolveTwitchAccountContext(cfg, resolvedAccountId);
|
|
660
|
+
const { account, accountId: normalizedAccountId, availableAccountIds, configured } = resolveTwitchAccountContext(cfg, resolvedAccountId);
|
|
646
661
|
if (!account) throw new Error(`Twitch account not found: ${resolvedAccountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`);
|
|
647
662
|
const channel = to || account.channel;
|
|
648
663
|
if (!channel) throw new Error("No channel specified and no default channel in account config");
|
|
649
|
-
|
|
650
|
-
|
|
664
|
+
if (!configured) throw new Error(`Account ${normalizedAccountId} is not properly configured. Required: username, clientId, and accessToken (config or env for default account).`);
|
|
665
|
+
const deliveryChannel = normalizeTwitchChannel(channel) || account.channel;
|
|
666
|
+
if (!deliveryChannel) throw new Error("No channel specified and no default channel in account config");
|
|
667
|
+
const result = await sendMessageTwitchInternal({
|
|
668
|
+
channel: normalizeTwitchChannel(deliveryChannel),
|
|
669
|
+
text,
|
|
670
|
+
cfg,
|
|
671
|
+
account,
|
|
672
|
+
accountId: normalizedAccountId,
|
|
673
|
+
clientManager: getClientManager(normalizedAccountId)
|
|
674
|
+
});
|
|
651
675
|
return {
|
|
652
676
|
channel: "twitch",
|
|
677
|
+
...result.outcome ? { outcome: result.outcome } : {},
|
|
653
678
|
messageId: result.messageId,
|
|
654
679
|
receipt: result.receipt,
|
|
655
680
|
timestamp: Date.now()
|
|
@@ -684,276 +709,11 @@ const twitchOutbound = {
|
|
|
684
709
|
});
|
|
685
710
|
}
|
|
686
711
|
};
|
|
687
|
-
|
|
688
|
-
const receipt = result.receipt ?? createMessageReceiptFromOutboundResults({
|
|
689
|
-
results: result.messageId ? [{
|
|
690
|
-
channel: "twitch",
|
|
691
|
-
messageId: result.messageId
|
|
692
|
-
}] : [],
|
|
693
|
-
kind
|
|
694
|
-
});
|
|
695
|
-
return {
|
|
696
|
-
messageId: result.messageId || receipt.primaryPlatformMessageId,
|
|
697
|
-
receipt
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
const twitchMessageAdapter = defineChannelMessageAdapter({
|
|
712
|
+
const twitchMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
701
713
|
id: "twitch",
|
|
702
|
-
|
|
703
|
-
text: true,
|
|
704
|
-
media: true,
|
|
705
|
-
messageSendingHooks: true
|
|
706
|
-
} },
|
|
707
|
-
send: {
|
|
708
|
-
text: async (ctx) => {
|
|
709
|
-
if (!twitchOutbound.sendText) throw new Error("Twitch text sending is not available.");
|
|
710
|
-
const { onDeliveryResult, ...outboundCtx } = ctx;
|
|
711
|
-
return toTwitchMessageSendResult(await twitchOutbound.sendText({
|
|
712
|
-
...outboundCtx,
|
|
713
|
-
...onDeliveryResult ? { onDeliveryResult: async (progress) => {
|
|
714
|
-
await onDeliveryResult(toTwitchMessageSendResult(progress, "text"));
|
|
715
|
-
} } : {}
|
|
716
|
-
}), "text");
|
|
717
|
-
},
|
|
718
|
-
media: async (ctx) => {
|
|
719
|
-
if (!twitchOutbound.sendMedia) throw new Error("Twitch media sending is not available.");
|
|
720
|
-
const { onDeliveryResult, ...outboundCtx } = ctx;
|
|
721
|
-
return toTwitchMessageSendResult(await twitchOutbound.sendMedia({
|
|
722
|
-
...outboundCtx,
|
|
723
|
-
...onDeliveryResult ? { onDeliveryResult: async (progress) => {
|
|
724
|
-
await onDeliveryResult(toTwitchMessageSendResult(progress, "media"));
|
|
725
|
-
} } : {}
|
|
726
|
-
}), "media");
|
|
727
|
-
}
|
|
728
|
-
}
|
|
714
|
+
outbound: twitchOutbound
|
|
729
715
|
});
|
|
730
716
|
//#endregion
|
|
731
|
-
//#region extensions/twitch/src/actions.ts
|
|
732
|
-
/**
|
|
733
|
-
* Twitch message actions adapter.
|
|
734
|
-
*
|
|
735
|
-
* Handles tool-based actions for Twitch, such as sending messages.
|
|
736
|
-
*/
|
|
737
|
-
/**
|
|
738
|
-
* Create a tool result with error content.
|
|
739
|
-
*/
|
|
740
|
-
function errorResponse(error) {
|
|
741
|
-
return {
|
|
742
|
-
content: [{
|
|
743
|
-
type: "text",
|
|
744
|
-
text: JSON.stringify({
|
|
745
|
-
ok: false,
|
|
746
|
-
error
|
|
747
|
-
})
|
|
748
|
-
}],
|
|
749
|
-
details: { ok: false }
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
/**
|
|
753
|
-
* Read a string parameter from action arguments.
|
|
754
|
-
*
|
|
755
|
-
* @param args - Action arguments
|
|
756
|
-
* @param key - Parameter key
|
|
757
|
-
* @param options - Options for reading the parameter
|
|
758
|
-
* @returns The parameter value or undefined if not found
|
|
759
|
-
*/
|
|
760
|
-
function readStringParam(args, key, options = {}) {
|
|
761
|
-
const value = args[key];
|
|
762
|
-
if (value === void 0 || value === null) {
|
|
763
|
-
if (options.required) throw new Error(`Missing required parameter: ${key}`);
|
|
764
|
-
return;
|
|
765
|
-
}
|
|
766
|
-
if (typeof value === "string") return options.trim !== false ? value.trim() : value;
|
|
767
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
768
|
-
const str = String(value);
|
|
769
|
-
return options.trim !== false ? str.trim() : str;
|
|
770
|
-
}
|
|
771
|
-
throw new Error(`Parameter ${key} must be a string, number, or boolean`);
|
|
772
|
-
}
|
|
773
|
-
/** Supported Twitch actions */
|
|
774
|
-
const TWITCH_ACTIONS = /* @__PURE__ */ new Set(["send"]);
|
|
775
|
-
/**
|
|
776
|
-
* Twitch message actions adapter.
|
|
777
|
-
*/
|
|
778
|
-
const twitchMessageActions = {
|
|
779
|
-
/**
|
|
780
|
-
* List available actions for this channel.
|
|
781
|
-
*/
|
|
782
|
-
describeMessageTool: () => ({ actions: [...TWITCH_ACTIONS] }),
|
|
783
|
-
/**
|
|
784
|
-
* Check if an action is supported.
|
|
785
|
-
*/
|
|
786
|
-
supportsAction: ({ action }) => TWITCH_ACTIONS.has(action),
|
|
787
|
-
/**
|
|
788
|
-
* Extract tool send parameters from action arguments.
|
|
789
|
-
*
|
|
790
|
-
* Parses and validates the "to" and "message" parameters for sending.
|
|
791
|
-
*
|
|
792
|
-
* @param params - Arguments from the tool call
|
|
793
|
-
* @returns Parsed send parameters or null if invalid
|
|
794
|
-
*
|
|
795
|
-
* @example
|
|
796
|
-
* const result = twitchMessageActions.extractToolSend!({
|
|
797
|
-
* args: { to: "#mychannel", message: "Hello!" }
|
|
798
|
-
* });
|
|
799
|
-
* // Returns: { to: "#mychannel", message: "Hello!" }
|
|
800
|
-
*/
|
|
801
|
-
extractToolSend: ({ args }) => {
|
|
802
|
-
try {
|
|
803
|
-
const to = readStringParam(args, "to", { required: true });
|
|
804
|
-
const message = readStringParam(args, "message", { required: true });
|
|
805
|
-
if (!to || !message) return null;
|
|
806
|
-
return {
|
|
807
|
-
to,
|
|
808
|
-
message
|
|
809
|
-
};
|
|
810
|
-
} catch {
|
|
811
|
-
return null;
|
|
812
|
-
}
|
|
813
|
-
},
|
|
814
|
-
/**
|
|
815
|
-
* Handle an action execution.
|
|
816
|
-
*
|
|
817
|
-
* Processes the "send" action to send messages to Twitch.
|
|
818
|
-
*
|
|
819
|
-
* @param ctx - Action context including action type, parameters, and config
|
|
820
|
-
* @returns Tool result with content or null if action not supported
|
|
821
|
-
*
|
|
822
|
-
* @example
|
|
823
|
-
* const result = await twitchMessageActions.handleAction!({
|
|
824
|
-
* action: "send",
|
|
825
|
-
* params: { message: "Hello Twitch!", to: "#mychannel" },
|
|
826
|
-
* cfg: openclawConfig,
|
|
827
|
-
* accountId: "default",
|
|
828
|
-
* });
|
|
829
|
-
*/
|
|
830
|
-
handleAction: async (ctx) => {
|
|
831
|
-
if (ctx.action !== "send") return {
|
|
832
|
-
content: [{
|
|
833
|
-
type: "text",
|
|
834
|
-
text: "Unsupported action"
|
|
835
|
-
}],
|
|
836
|
-
details: {
|
|
837
|
-
ok: false,
|
|
838
|
-
error: "Unsupported action"
|
|
839
|
-
}
|
|
840
|
-
};
|
|
841
|
-
const message = readStringParam(ctx.params, "message", { required: true });
|
|
842
|
-
const to = readStringParam(ctx.params, "to", { required: false });
|
|
843
|
-
const accountId = ctx.accountId ?? resolveTwitchAccountContext(ctx.cfg).accountId;
|
|
844
|
-
const { account, availableAccountIds } = resolveTwitchAccountContext(ctx.cfg, accountId);
|
|
845
|
-
if (!account) return errorResponse(`Account not found: ${accountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`);
|
|
846
|
-
const targetChannel = to || account.channel;
|
|
847
|
-
if (!targetChannel) return errorResponse("No channel specified and no default channel in account config");
|
|
848
|
-
if (!twitchOutbound.sendText) return errorResponse("sendText not implemented");
|
|
849
|
-
try {
|
|
850
|
-
const result = await twitchOutbound.sendText({
|
|
851
|
-
cfg: ctx.cfg,
|
|
852
|
-
to: targetChannel,
|
|
853
|
-
text: message ?? "",
|
|
854
|
-
accountId
|
|
855
|
-
});
|
|
856
|
-
return {
|
|
857
|
-
content: [{
|
|
858
|
-
type: "text",
|
|
859
|
-
text: JSON.stringify(result)
|
|
860
|
-
}],
|
|
861
|
-
details: { ok: true }
|
|
862
|
-
};
|
|
863
|
-
} catch (error) {
|
|
864
|
-
return errorResponse(formatErrorMessage(error));
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
};
|
|
868
|
-
//#endregion
|
|
869
|
-
//#region extensions/twitch/src/config-schema.ts
|
|
870
|
-
/**
|
|
871
|
-
* Twitch user roles that can be allowed to interact with the bot
|
|
872
|
-
*/
|
|
873
|
-
const TwitchRoleSchema = z.enum([
|
|
874
|
-
"moderator",
|
|
875
|
-
"owner",
|
|
876
|
-
"vip",
|
|
877
|
-
"subscriber",
|
|
878
|
-
"all"
|
|
879
|
-
]);
|
|
880
|
-
const TwitchAccountShape = {
|
|
881
|
-
/** Twitch username */
|
|
882
|
-
username: z.string(),
|
|
883
|
-
/** Twitch OAuth access token (requires chat:read and chat:write scopes) */
|
|
884
|
-
accessToken: z.string(),
|
|
885
|
-
/** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
|
|
886
|
-
clientId: z.string().optional(),
|
|
887
|
-
/** Channel name to join */
|
|
888
|
-
channel: z.string().min(1),
|
|
889
|
-
/** Enable this account */
|
|
890
|
-
enabled: z.boolean().optional(),
|
|
891
|
-
/** Allow channel-initiated configuration writes */
|
|
892
|
-
configWrites: z.boolean().optional(),
|
|
893
|
-
/** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
|
|
894
|
-
allowFrom: z.array(z.string()).optional(),
|
|
895
|
-
/** Roles allowed to interact with the bot (e.g., ["moderator", "vip", "subscriber"]) */
|
|
896
|
-
allowedRoles: z.array(TwitchRoleSchema).optional(),
|
|
897
|
-
/** Require @mention to trigger bot responses */
|
|
898
|
-
requireMention: z.boolean().optional(),
|
|
899
|
-
/** Outbound response prefix override for this channel/account. */
|
|
900
|
-
responsePrefix: z.string().optional(),
|
|
901
|
-
/** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
|
|
902
|
-
clientSecret: z.string().optional(),
|
|
903
|
-
/** Refresh token (required for automatic token refresh) */
|
|
904
|
-
refreshToken: z.string().optional(),
|
|
905
|
-
/** Token expiry time in seconds (optional, for token refresh tracking) */
|
|
906
|
-
expiresIn: z.number().nullable().optional(),
|
|
907
|
-
/** Timestamp when token was obtained (optional, for token refresh tracking) */
|
|
908
|
-
obtainmentTimestamp: z.number().optional()
|
|
909
|
-
};
|
|
910
|
-
/**
|
|
911
|
-
* Twitch account configuration schema
|
|
912
|
-
*/
|
|
913
|
-
const TwitchAccountSchema = z.object(TwitchAccountShape);
|
|
914
|
-
/**
|
|
915
|
-
* Base configuration properties shared by both single and multi-account modes
|
|
916
|
-
*/
|
|
917
|
-
const TwitchConfigBaseShape = {
|
|
918
|
-
name: z.string().optional(),
|
|
919
|
-
enabled: z.boolean().optional(),
|
|
920
|
-
configWrites: z.boolean().optional(),
|
|
921
|
-
markdown: MarkdownConfigSchema.optional(),
|
|
922
|
-
defaultAccount: z.string().optional(),
|
|
923
|
-
historyLimit: z.number().int().min(0).optional(),
|
|
924
|
-
responsePrefix: z.string().optional()
|
|
925
|
-
};
|
|
926
|
-
/**
|
|
927
|
-
* Simplified single-account configuration schema
|
|
928
|
-
*
|
|
929
|
-
* Use this for single-account setups. Properties are at the top level,
|
|
930
|
-
* creating an implicit "default" account.
|
|
931
|
-
*/
|
|
932
|
-
const SimplifiedSchema = z.object({
|
|
933
|
-
...TwitchConfigBaseShape,
|
|
934
|
-
...TwitchAccountShape
|
|
935
|
-
});
|
|
936
|
-
/**
|
|
937
|
-
* Multi-account configuration schema
|
|
938
|
-
*
|
|
939
|
-
* Use this for multi-account setups. Each key is an account ID (e.g., "default", "secondary").
|
|
940
|
-
*/
|
|
941
|
-
const MultiAccountSchema = z.object({
|
|
942
|
-
...TwitchConfigBaseShape,
|
|
943
|
-
/** Per-account configuration (for multi-account setups) */
|
|
944
|
-
accounts: z.record(z.string(), TwitchAccountSchema)
|
|
945
|
-
}).refine((val) => Object.keys(val.accounts || {}).length > 0, { message: "accounts must contain at least one entry" });
|
|
946
|
-
/**
|
|
947
|
-
* Twitch plugin configuration schema
|
|
948
|
-
*
|
|
949
|
-
* Supports two mutually exclusive patterns:
|
|
950
|
-
* 1. Simplified single-account: username, accessToken, clientId, channel at top level
|
|
951
|
-
* 2. Multi-account: accounts object with named account configs
|
|
952
|
-
*
|
|
953
|
-
* The union ensures clear discrimination between the two modes.
|
|
954
|
-
*/
|
|
955
|
-
const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
|
|
956
|
-
//#endregion
|
|
957
717
|
//#region extensions/twitch/src/probe.ts
|
|
958
718
|
/**
|
|
959
719
|
* Probe a Twitch account to verify the connection is working
|
|
@@ -971,7 +731,8 @@ async function probeTwitch(account, timeoutMs) {
|
|
|
971
731
|
username: account.username
|
|
972
732
|
};
|
|
973
733
|
const rawToken = normalizeToken(account.accessToken.trim());
|
|
974
|
-
|
|
734
|
+
const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
|
|
735
|
+
client = new ChatClient({ authProvider });
|
|
975
736
|
const connectionPromise = new Promise((resolve, reject) => {
|
|
976
737
|
let settled = false;
|
|
977
738
|
const cleanup = () => {
|
|
@@ -1275,7 +1036,7 @@ function collectTwitchStatusIssues(accounts, getCfg) {
|
|
|
1275
1036
|
fix: "Start the Twitch gateway to begin receiving messages. Check logs for connection errors."
|
|
1276
1037
|
});
|
|
1277
1038
|
if (entry.running && entry.lastStartAt) {
|
|
1278
|
-
const daysSinceStart = (Date.now() - entry.lastStartAt) /
|
|
1039
|
+
const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
|
|
1279
1040
|
if (daysSinceStart > 7) issues.push({
|
|
1280
1041
|
channel: "twitch",
|
|
1281
1042
|
accountId,
|
|
@@ -1300,7 +1061,8 @@ function normalizeTwitchMessagingTarget(target) {
|
|
|
1300
1061
|
const kindMatch = /^(user|dm|channel|group|conversation|room):/i.exec(providerTarget);
|
|
1301
1062
|
const kind = kindMatch?.[1]?.toLowerCase();
|
|
1302
1063
|
if (kind === "user" || kind === "dm") return "";
|
|
1303
|
-
|
|
1064
|
+
const channelTarget = kindMatch ? providerTarget.slice(kindMatch[0].length) : providerTarget;
|
|
1065
|
+
return normalizeTwitchChannel(channelTarget);
|
|
1304
1066
|
}
|
|
1305
1067
|
/**
|
|
1306
1068
|
* Twitch channel plugin.
|
|
@@ -1315,6 +1077,10 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
1315
1077
|
normalizeAllowEntry: createPairingPrefixStripper(/^(twitch:)?user:?/i),
|
|
1316
1078
|
notifyApproval: createLoggedPairingApprovalNotifier(({ id }) => `Pairing approved for user ${id} (notification sent via chat if possible)`, console.warn)
|
|
1317
1079
|
},
|
|
1080
|
+
threading: { matchesToolContextTarget: ({ target, toolContext }) => {
|
|
1081
|
+
const channel = normalizeTwitchMessagingTarget(target);
|
|
1082
|
+
return Boolean(channel) && [toolContext.currentChannelId, toolContext.currentMessagingTarget].some((current) => current != null && normalizeTwitchMessagingTarget(current) === channel);
|
|
1083
|
+
} },
|
|
1318
1084
|
outbound: twitchOutbound,
|
|
1319
1085
|
base: {
|
|
1320
1086
|
id: "twitch",
|
|
@@ -1330,6 +1096,11 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
1330
1096
|
setupWizard: twitchSetupWizard,
|
|
1331
1097
|
capabilities: { chatTypes: ["group"] },
|
|
1332
1098
|
messaging: {
|
|
1099
|
+
normalizeTarget: normalizeTwitchMessagingTarget,
|
|
1100
|
+
targetResolver: {
|
|
1101
|
+
looksLikeId: (input) => Boolean(normalizeTwitchMessagingTarget(input)),
|
|
1102
|
+
hint: "<channel-name>"
|
|
1103
|
+
},
|
|
1333
1104
|
inferTargetChatType: ({ to }) => normalizeTwitchMessagingTarget(to) ? "group" : void 0,
|
|
1334
1105
|
resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
|
|
1335
1106
|
const channel = normalizeTwitchMessagingTarget(target);
|
|
@@ -1397,6 +1168,8 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
1397
1168
|
startAccount: async (ctx) => {
|
|
1398
1169
|
const account = ctx.account;
|
|
1399
1170
|
const accountId = ctx.accountId;
|
|
1171
|
+
const channelRuntime = ctx.channelRuntime;
|
|
1172
|
+
if (!channelRuntime?.inbound?.buildContext) throw new Error("Twitch requires its registered channel runtime context builder");
|
|
1400
1173
|
const statusSink = createAccountStatusSink({
|
|
1401
1174
|
accountId,
|
|
1402
1175
|
setStatus: ctx.setStatus
|
|
@@ -1412,10 +1185,11 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
1412
1185
|
await runPassiveAccountLifecycle({
|
|
1413
1186
|
abortSignal: ctx.abortSignal,
|
|
1414
1187
|
start: async () => {
|
|
1415
|
-
const { monitorTwitchProvider } = await import("./monitor-
|
|
1188
|
+
const { monitorTwitchProvider } = await import("./monitor-dCA7_7aW.js");
|
|
1416
1189
|
return monitorTwitchProvider({
|
|
1417
1190
|
account,
|
|
1418
1191
|
accountId,
|
|
1192
|
+
channelRuntime,
|
|
1419
1193
|
config: ctx.cfg,
|
|
1420
1194
|
runtime: ctx.runtime,
|
|
1421
1195
|
abortSignal: ctx.abortSignal,
|
|
@@ -1450,4 +1224,4 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
1450
1224
|
}
|
|
1451
1225
|
});
|
|
1452
1226
|
//#endregion
|
|
1453
|
-
export {
|
|
1227
|
+
export { sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };
|
package/dist/setup-plugin-api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as twitchSetupPlugin } from "./setup-surface-
|
|
1
|
+
import { n as twitchSetupPlugin } from "./setup-surface-BZ2FXBoo.js";
|
|
2
2
|
export { twitchSetupPlugin };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { createAccountListHelpers } from "openclaw/plugin-sdk/account-helpers";
|
|
2
2
|
import { DEFAULT_ACCOUNT_ID, DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, normalizeAccountId, resolveNormalizedAccountEntry } from "openclaw/plugin-sdk/account-resolution";
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
4
3
|
import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
5
4
|
import { normalizeOptionalAccountId } from "openclaw/plugin-sdk/account-id";
|
|
6
5
|
import { createChannelDmPolicy } from "openclaw/plugin-sdk/channel-dm-policy";
|
|
@@ -96,17 +95,6 @@ function missingTargetError(provider, hint) {
|
|
|
96
95
|
return /* @__PURE__ */ new Error(`Delivering to ${provider} requires target${hint ? ` ${hint}` : ""}`);
|
|
97
96
|
}
|
|
98
97
|
/**
|
|
99
|
-
* Generate a unique message ID for Twitch messages.
|
|
100
|
-
*
|
|
101
|
-
* Twurple's say() doesn't return the message ID, so we generate one
|
|
102
|
-
* for tracking purposes.
|
|
103
|
-
*
|
|
104
|
-
* @returns A unique message ID
|
|
105
|
-
*/
|
|
106
|
-
function generateMessageId() {
|
|
107
|
-
return `${Date.now()}-${randomUUID()}`;
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
98
|
* Normalize OAuth token by removing the "oauth:" prefix if present.
|
|
111
99
|
*
|
|
112
100
|
* Twurple doesn't require the "oauth:" prefix, so we strip it for consistency.
|
|
@@ -218,6 +206,7 @@ const twitchConfigAdapter = {
|
|
|
218
206
|
listAccountIds,
|
|
219
207
|
resolveAccount: resolveTwitchAccount,
|
|
220
208
|
defaultAccountId: resolveDefaultTwitchAccountId,
|
|
209
|
+
resolveDefaultTo: ({ cfg, accountId }) => resolveTwitchAccountContext(cfg, accountId).account?.channel,
|
|
221
210
|
isConfigured: (account, cfg) => resolveTwitchAccountContext(cfg, account.accountId).configured,
|
|
222
211
|
isEnabled: (account) => account?.enabled !== false
|
|
223
212
|
};
|
|
@@ -424,11 +413,12 @@ const twitchDmPolicy = createChannelDmPolicy({
|
|
|
424
413
|
const resolvedAccountId = resolveSetupAccountId(cfg, accountId);
|
|
425
414
|
const account = getAccountConfig(cfg, resolvedAccountId);
|
|
426
415
|
const existingAllowFrom = account?.allowFrom ?? [];
|
|
427
|
-
const
|
|
416
|
+
const entry = await prompter.text({
|
|
428
417
|
message: t("wizard.twitch.allowFromPrompt"),
|
|
429
418
|
placeholder: "123456789",
|
|
430
419
|
initialValue: existingAllowFrom[0] || void 0
|
|
431
|
-
})
|
|
420
|
+
});
|
|
421
|
+
const allowFrom = normalizeStringEntries((entry ?? "").split(/[\n,;]+/g));
|
|
432
422
|
return setTwitchAccount(cfg, {
|
|
433
423
|
...account ?? void 0,
|
|
434
424
|
allowFrom
|
|
@@ -520,4 +510,4 @@ const twitchSetupPlugin = {
|
|
|
520
510
|
setupWizard: twitchSetupWizard
|
|
521
511
|
};
|
|
522
512
|
//#endregion
|
|
523
|
-
export { getAccountConfig as a, resolveTwitchSnapshotAccountId as c,
|
|
513
|
+
export { getAccountConfig as a, resolveTwitchSnapshotAccountId as c, missingTargetError as d, normalizeToken as f, DEFAULT_ACCOUNT_ID$1 as i, twitchConfigAdapter as l, resolveTwitchToken as m, twitchSetupPlugin as n, resolveDefaultTwitchAccountId as o, normalizeTwitchChannel as p, twitchSetupWizard as r, resolveTwitchAccountContext as s, twitchSetupContract as t, isAccountConfigured as u };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openclaw/twitch",
|
|
3
|
-
"version": "2026.9.1
|
|
3
|
+
"version": "2026.9.1",
|
|
4
4
|
"description": "OpenClaw Twitch channel plugin for chat and moderation workflows.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -30,10 +30,10 @@
|
|
|
30
30
|
"minHostVersion": ">=2026.4.10"
|
|
31
31
|
},
|
|
32
32
|
"compat": {
|
|
33
|
-
"pluginApi": ">=2026.9.1
|
|
33
|
+
"pluginApi": ">=2026.9.1"
|
|
34
34
|
},
|
|
35
35
|
"build": {
|
|
36
|
-
"openclawVersion": "2026.9.1
|
|
36
|
+
"openclawVersion": "2026.9.1"
|
|
37
37
|
},
|
|
38
38
|
"channel": {
|
|
39
39
|
"id": "twitch",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"README.md"
|
|
72
72
|
],
|
|
73
73
|
"peerDependencies": {
|
|
74
|
-
"openclaw": ">=2026.9.1
|
|
74
|
+
"openclaw": ">=2026.9.1"
|
|
75
75
|
},
|
|
76
76
|
"peerDependenciesMeta": {
|
|
77
77
|
"openclaw": {
|