@openclaw/twitch 2026.9.1-beta.1 → 2026.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 `token` property
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,3 +1,3 @@
1
- import { t as twitchPlugin } from "./plugin-BkpBoc94.js";
1
+ import { t as twitchPlugin } from "./plugin-DpUZvxJa.js";
2
2
  import { n as setTwitchRuntime } from "./runtime-B5If4b0g.js";
3
3
  export { setTwitchRuntime, twitchPlugin };
@@ -1,2 +1,2 @@
1
- import { t as twitchPlugin } from "./plugin-BkpBoc94.js";
1
+ import { t as twitchPlugin } from "./plugin-DpUZvxJa.js";
2
2
  export { twitchPlugin };
@@ -1,5 +1,5 @@
1
- import { m as normalizeTwitchChannel } from "./setup-surface-1wrrTKpx.js";
2
- import { n as stripMarkdownForTwitch, r as getOrCreateClientManager } from "./plugin-BkpBoc94.js";
1
+ import { n as sendMessageTwitchInternal, r as getOrCreateClientManager } from "./plugin-DpUZvxJa.js";
2
+ import { d as normalizeTwitchChannel } from "./setup-surface-fSAA11EJ.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: "role-moderator",
18
- kind: "role",
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: "default",
37
+ accountId: params.accountId,
40
38
  identity: policyKind === "role" ? twitchRoleIdentity : twitchUserIdentity
41
39
  }).message({
42
- subject: policyKind === "role" ? twitchRoleSubject(message) : { stableId: message.userId },
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 twitchRoleSubject(message) {
107
+ function twitchSubject(message) {
110
108
  return {
111
- stableId: message.isMod ? "moderator" : void 0,
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
- if (role === "*") return "all";
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, core, turnAdoptionLifecycle, statusSink } = params;
288
+ const { message, account, accountId, config, runtime, channelRuntime, turnAdoptionLifecycle, statusSink } = params;
290
289
  const cfg = config;
291
- const route = core.channel.routing.resolveAgentRoute({
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 core.channel.inbound.run({
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 = core.channel.inbound.buildContext({
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
- const textToSend = stripMarkdownForTwitch([payload.text, ...resolveOutboundMediaUrls(payload)].filter(Boolean).join(" "));
426
- if (!textToSend) {
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
- core,
483
+ channelRuntime,
485
484
  turnAdoptionLifecycle,
486
485
  statusSink
487
486
  });
@@ -1,20 +1,86 @@
1
- import { a as getAccountConfig, c as resolveTwitchSnapshotAccountId, d as isAccountConfigured, f as missingTargetError, h as resolveTwitchToken, i as DEFAULT_ACCOUNT_ID, l as twitchConfigAdapter, m as normalizeTwitchChannel, o as resolveDefaultTwitchAccountId, p as normalizeToken, r as twitchSetupWizard, s as resolveTwitchAccountContext, t as twitchSetupContract, u as generateMessageId } from "./setup-surface-1wrrTKpx.js";
1
+ import { a as resolveTwitchAccountContext, c as isAccountConfigured, d as normalizeTwitchChannel, f as resolveTwitchToken, i as resolveDefaultTwitchAccountId, l as missingTargetError, n as DEFAULT_ACCOUNT_ID$1, o as resolveTwitchSnapshotAccountId, r as getAccountConfig, s as twitchConfigAdapter, t as twitchSetupPlugin, u as normalizeToken } from "./setup-surface-fSAA11EJ.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, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
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 { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-resolution";
12
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
14
13
  import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
14
+ import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
15
15
  import { runChannelProbe, sliceUtf16Safe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
16
+ import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
16
17
  import { z } from "zod";
17
18
  import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
19
+ //#region extensions/twitch/src/actions.ts
20
+ /**
21
+ * Read a string parameter from action arguments.
22
+ *
23
+ * @param args - Action arguments
24
+ * @param key - Parameter key
25
+ * @param options - Options for reading the parameter
26
+ * @returns The parameter value or undefined if not found
27
+ */
28
+ function readStringParam(args, key, options = {}) {
29
+ const value = args[key];
30
+ if (value === void 0 || value === null) {
31
+ if (options.required) throw new Error(`Missing required parameter: ${key}`);
32
+ return;
33
+ }
34
+ if (typeof value === "string") return options.trim !== false ? value.trim() : value;
35
+ if (typeof value === "number" || typeof value === "boolean") {
36
+ const str = String(value);
37
+ return options.trim !== false ? str.trim() : str;
38
+ }
39
+ throw new Error(`Parameter ${key} must be a string, number, or boolean`);
40
+ }
41
+ /** Supported Twitch actions */
42
+ const TWITCH_ACTIONS = /* @__PURE__ */ new Set(["send"]);
43
+ /**
44
+ * Twitch message actions adapter.
45
+ */
46
+ const twitchMessageActions = {
47
+ /**
48
+ * List available actions for this channel.
49
+ */
50
+ describeMessageTool: () => ({ actions: [...TWITCH_ACTIONS] }),
51
+ /**
52
+ * Check if an action is supported.
53
+ */
54
+ supportsAction: ({ action }) => TWITCH_ACTIONS.has(action),
55
+ /**
56
+ * Extract tool send parameters from action arguments.
57
+ *
58
+ * Parses and validates the "to" and "message" parameters for sending.
59
+ *
60
+ * @param params - Arguments from the tool call
61
+ * @returns Parsed send parameters or null if invalid
62
+ *
63
+ * @example
64
+ * const result = twitchMessageActions.extractToolSend!({
65
+ * args: { to: "#mychannel", message: "Hello!" }
66
+ * });
67
+ * // Returns: { to: "#mychannel", message: "Hello!" }
68
+ */
69
+ extractToolSend: ({ args }) => {
70
+ try {
71
+ const to = readStringParam(args, "to", { required: true });
72
+ const message = readStringParam(args, "message", { required: true });
73
+ if (!to || !message) return null;
74
+ return {
75
+ to,
76
+ message
77
+ };
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+ };
83
+ //#endregion
18
84
  //#region extensions/twitch/src/twitch-client.ts
19
85
  const TWITCH_CHAT_AUTH_INTENTS = ["chat"];
20
86
  /**
@@ -97,8 +163,9 @@ var TwitchClientManager = class {
97
163
  async createConnectedClient(key, account, ownsConnection, cfg, accountId) {
98
164
  const tokenResolution = resolveTwitchToken(cfg, { accountId });
99
165
  if (!tokenResolution.token) {
100
- this.logger.error(`Missing Twitch token for account ${account.username} (set channels.twitch.accounts.${account.username}.token or OPENCLAW_TWITCH_ACCESS_TOKEN for default)`);
101
- throw new Error("Missing Twitch token");
166
+ const resolvedAccountId = accountId ?? DEFAULT_ACCOUNT_ID;
167
+ const tokenConfigPath = cfg?.channels?.twitch?.accounts ? `channels.twitch.accounts.${resolvedAccountId}.accessToken` : "channels.twitch.accessToken";
168
+ throw new Error(`Missing Twitch token for account ${resolvedAccountId} (set ${tokenConfigPath} or OPENCLAW_TWITCH_ACCESS_TOKEN for default)`);
102
169
  }
103
170
  this.logger.debug?.(`Using ${tokenResolution.source} token source for ${account.username}`);
104
171
  if (!account.clientId) {
@@ -132,9 +199,7 @@ var TwitchClientManager = class {
132
199
  case LogLevel.DEBUG:
133
200
  this.logger.debug?.(message);
134
201
  break;
135
- case LogLevel.TRACE:
136
- this.logger.debug?.(message);
137
- break;
202
+ case LogLevel.TRACE: this.logger.debug?.(message);
138
203
  }
139
204
  } }
140
205
  }
@@ -301,10 +366,11 @@ var TwitchClientManager = class {
301
366
  messageId
302
367
  };
303
368
  } catch (error) {
304
- this.logger.error(`Failed to send message: ${formatErrorMessage(error)}`);
369
+ const errorMessage = formatErrorMessage(error);
370
+ this.logger.error(`Failed to send message: ${errorMessage}`);
305
371
  return {
306
372
  ok: false,
307
- error: formatErrorMessage(error)
373
+ error: errorMessage
308
374
  };
309
375
  }
310
376
  }
@@ -314,15 +380,6 @@ var TwitchClientManager = class {
314
380
  getAccountKey(account) {
315
381
  return `${account.username}:${account.channel}`;
316
382
  }
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
383
  };
327
384
  //#endregion
328
385
  //#region extensions/twitch/src/client-manager-registry.ts
@@ -386,6 +443,94 @@ async function removeClientManager(accountId) {
386
443
  }
387
444
  }
388
445
  //#endregion
446
+ //#region extensions/twitch/src/config-schema.ts
447
+ /**
448
+ * Twitch user roles that can be allowed to interact with the bot
449
+ */
450
+ const TwitchRoleSchema = z.enum([
451
+ "moderator",
452
+ "owner",
453
+ "vip",
454
+ "subscriber",
455
+ "all"
456
+ ]);
457
+ const TwitchAccountShape = {
458
+ /** Twitch username */
459
+ username: z.string(),
460
+ /** Twitch OAuth access token (requires chat:read and chat:write scopes) */
461
+ accessToken: z.string(),
462
+ /** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
463
+ clientId: z.string().optional(),
464
+ /** Channel name to join */
465
+ channel: z.string().min(1),
466
+ /** Enable this account */
467
+ enabled: z.boolean().optional(),
468
+ /** Allow channel-initiated configuration writes */
469
+ configWrites: z.boolean().optional(),
470
+ /** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
471
+ allowFrom: z.array(z.string()).optional(),
472
+ /** Roles allowed to interact with the bot (e.g., ["moderator", "vip", "subscriber"]) */
473
+ allowedRoles: z.array(TwitchRoleSchema).optional(),
474
+ /** Require @mention to trigger bot responses */
475
+ requireMention: z.boolean().optional(),
476
+ /** Outbound response prefix override for this channel/account. */
477
+ responsePrefix: z.string().optional(),
478
+ /** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
479
+ clientSecret: z.string().optional(),
480
+ /** Refresh token (required for automatic token refresh) */
481
+ refreshToken: z.string().optional(),
482
+ /** Token expiry time in seconds (optional, for token refresh tracking) */
483
+ expiresIn: z.number().nullable().optional(),
484
+ /** Timestamp when token was obtained (optional, for token refresh tracking) */
485
+ obtainmentTimestamp: z.number().optional()
486
+ };
487
+ /**
488
+ * Twitch account configuration schema
489
+ */
490
+ const TwitchAccountSchema = z.object(TwitchAccountShape);
491
+ /**
492
+ * Base configuration properties shared by both single and multi-account modes
493
+ */
494
+ const TwitchConfigBaseShape = {
495
+ name: z.string().optional(),
496
+ enabled: z.boolean().optional(),
497
+ configWrites: z.boolean().optional(),
498
+ markdown: MarkdownConfigSchema.optional(),
499
+ defaultAccount: z.string().optional(),
500
+ historyLimit: z.number().int().min(0).optional(),
501
+ responsePrefix: z.string().optional()
502
+ };
503
+ /**
504
+ * Simplified single-account configuration schema
505
+ *
506
+ * Use this for single-account setups. Properties are at the top level,
507
+ * creating an implicit "default" account.
508
+ */
509
+ const SimplifiedSchema = z.object({
510
+ ...TwitchConfigBaseShape,
511
+ ...TwitchAccountShape
512
+ });
513
+ /**
514
+ * Multi-account configuration schema
515
+ *
516
+ * Use this for multi-account setups. Each key is an account ID (e.g., "default", "secondary").
517
+ */
518
+ const MultiAccountSchema = z.object({
519
+ ...TwitchConfigBaseShape,
520
+ /** Per-account configuration (for multi-account setups) */
521
+ accounts: z.record(z.string(), TwitchAccountSchema)
522
+ }).refine((val) => Object.keys(val.accounts || {}).length > 0, { message: "accounts must contain at least one entry" });
523
+ /**
524
+ * Twitch plugin configuration schema
525
+ *
526
+ * Supports two mutually exclusive patterns:
527
+ * 1. Simplified single-account: username, accessToken, clientId, channel at top level
528
+ * 2. Multi-account: accounts object with named account configs
529
+ *
530
+ * The union ensures clear discrimination between the two modes.
531
+ */
532
+ const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
533
+ //#endregion
389
534
  //#region extensions/twitch/src/utils/markdown.ts
390
535
  /**
391
536
  * Markdown utilities for Twitch chat
@@ -396,158 +541,33 @@ async function removeClientManager(accountId) {
396
541
  function stripMarkdownForTwitch(markdown) {
397
542
  return stripMarkdown(markdown, { linkStyle: "label-and-url" }).replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n/g, " ").replace(/[ \t]{2,}/g, " ").trim();
398
543
  }
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
544
  //#endregion
413
545
  //#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();
546
+ function createTwitchSendReceipt(messageId, channel) {
423
547
  return createMessageReceiptFromOutboundResults({
424
- results: params.visible === true && messageId && messageId !== "skipped" ? [{
548
+ results: messageId ? [{
425
549
  channel: "twitch",
426
550
  messageId,
427
- ...conversationId ? { conversationId } : {}
551
+ conversationId: channel
428
552
  }] : [],
429
553
  kind: "text"
430
554
  });
431
555
  }
432
- /**
433
- * Internal send function used by the outbound adapter.
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;
556
+ async function sendMessageTwitchInternal(params) {
557
+ const cleanedText = stripMarkdownForTwitch(params.text);
491
558
  if (!cleanedText) return {
492
- ok: true,
493
- messageId: "skipped",
494
- receipt: createTwitchSendReceipt({
495
- messageId: "skipped",
496
- channel: deliveryChannel,
497
- visible: false
498
- })
559
+ outcome: "not_sent",
560
+ messageId: "",
561
+ receipt: createTwitchSendReceipt()
499
562
  };
500
- const clientManager = getClientManager(resolvedAccountId);
501
- if (!clientManager) return {
502
- ok: false,
503
- messageId: generateMessageId(),
504
- receipt: createTwitchSendReceipt({
505
- messageId: "",
506
- channel: deliveryChannel,
507
- visible: false
508
- }),
509
- error: `Client manager not found for account: ${resolvedAccountId}. Please start the Twitch gateway first.`
563
+ if (!params.clientManager) throw new Error(`Client manager not found for account: ${params.accountId}. Please start the Twitch gateway first.`);
564
+ const result = await params.clientManager.sendMessage(params.account, params.channel, cleanedText, params.cfg, params.accountId);
565
+ if (!result.ok) throw new Error(result.error);
566
+ const { messageId } = result;
567
+ return {
568
+ messageId,
569
+ receipt: createTwitchSendReceipt(messageId, params.channel)
510
570
  };
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
571
  }
552
572
  //#endregion
553
573
  //#region extensions/twitch/src/outbound.ts
@@ -571,12 +591,9 @@ const twitchOutbound = {
571
591
  media: true,
572
592
  messageSendingHooks: true
573
593
  } },
574
- /** Twitch chat message limit is 500 characters */
575
594
  textChunkLimit: 500,
576
595
  /** Strip internal assistant tool-trace scaffolding before delivery */
577
596
  sanitizeText: ({ text }) => sanitizeAssistantVisibleText(text),
578
- /** Word-boundary chunker with markdown stripping */
579
- chunker: chunkTextForTwitch,
580
597
  /**
581
598
  * Resolve target from context.
582
599
  *
@@ -624,7 +641,7 @@ const twitchOutbound = {
624
641
  /**
625
642
  * Send a text message to a Twitch channel.
626
643
  *
627
- * Strips markdown if enabled, validates account configuration,
644
+ * Strips Markdown, validates account configuration,
628
645
  * and sends the message via the Twitch client.
629
646
  *
630
647
  * @param params - Send parameters including target, text, and config
@@ -642,14 +659,24 @@ const twitchOutbound = {
642
659
  const { cfg, to, text, accountId } = params;
643
660
  if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
644
661
  const resolvedAccountId = accountId ?? resolveTwitchAccountContext(cfg).accountId;
645
- const { account, availableAccountIds } = resolveTwitchAccountContext(cfg, resolvedAccountId);
662
+ const { account, accountId: normalizedAccountId, availableAccountIds, configured } = resolveTwitchAccountContext(cfg, resolvedAccountId);
646
663
  if (!account) throw new Error(`Twitch account not found: ${resolvedAccountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`);
647
664
  const channel = to || account.channel;
648
665
  if (!channel) throw new Error("No channel specified and no default channel in account config");
649
- const result = await sendMessageTwitchInternal(normalizeTwitchChannel(channel), text, cfg, resolvedAccountId, true, console);
650
- if (!result.ok) throw new Error(result.error ?? "Send failed");
666
+ if (!configured) throw new Error(`Account ${normalizedAccountId} is not properly configured. Required: username, clientId, and accessToken (config or env for default account).`);
667
+ const deliveryChannel = normalizeTwitchChannel(channel) || account.channel;
668
+ if (!deliveryChannel) throw new Error("No channel specified and no default channel in account config");
669
+ const result = await sendMessageTwitchInternal({
670
+ channel: normalizeTwitchChannel(deliveryChannel),
671
+ text,
672
+ cfg,
673
+ account,
674
+ accountId: normalizedAccountId,
675
+ clientManager: getClientManager(normalizedAccountId)
676
+ });
651
677
  return {
652
678
  channel: "twitch",
679
+ ...result.outcome ? { outcome: result.outcome } : {},
653
680
  messageId: result.messageId,
654
681
  receipt: result.receipt,
655
682
  timestamp: Date.now()
@@ -684,276 +711,11 @@ const twitchOutbound = {
684
711
  });
685
712
  }
686
713
  };
687
- function toTwitchMessageSendResult(result, kind) {
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({
714
+ const twitchMessageAdapter = createChannelMessageAdapterFromOutbound({
701
715
  id: "twitch",
702
- durableFinal: { capabilities: {
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
- }
716
+ outbound: twitchOutbound
729
717
  });
730
718
  //#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
719
  //#region extensions/twitch/src/probe.ts
958
720
  /**
959
721
  * Probe a Twitch account to verify the connection is working
@@ -971,7 +733,8 @@ async function probeTwitch(account, timeoutMs) {
971
733
  username: account.username
972
734
  };
973
735
  const rawToken = normalizeToken(account.accessToken.trim());
974
- client = new ChatClient({ authProvider: new StaticAuthProvider(account.clientId ?? "", rawToken) });
736
+ const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
737
+ client = new ChatClient({ authProvider });
975
738
  const connectionPromise = new Promise((resolve, reject) => {
976
739
  let settled = false;
977
740
  const cleanup = () => {
@@ -1275,7 +1038,7 @@ function collectTwitchStatusIssues(accounts, getCfg) {
1275
1038
  fix: "Start the Twitch gateway to begin receiving messages. Check logs for connection errors."
1276
1039
  });
1277
1040
  if (entry.running && entry.lastStartAt) {
1278
- const daysSinceStart = (Date.now() - entry.lastStartAt) / (1e3 * 60 * 60 * 24);
1041
+ const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
1279
1042
  if (daysSinceStart > 7) issues.push({
1280
1043
  channel: "twitch",
1281
1044
  accountId,
@@ -1300,7 +1063,8 @@ function normalizeTwitchMessagingTarget(target) {
1300
1063
  const kindMatch = /^(user|dm|channel|group|conversation|room):/i.exec(providerTarget);
1301
1064
  const kind = kindMatch?.[1]?.toLowerCase();
1302
1065
  if (kind === "user" || kind === "dm") return "";
1303
- return normalizeTwitchChannel(kindMatch ? providerTarget.slice(kindMatch[0].length) : providerTarget);
1066
+ const channelTarget = kindMatch ? providerTarget.slice(kindMatch[0].length) : providerTarget;
1067
+ return normalizeTwitchChannel(channelTarget);
1304
1068
  }
1305
1069
  /**
1306
1070
  * Twitch channel plugin.
@@ -1315,6 +1079,10 @@ const twitchPlugin = createChatChannelPlugin({
1315
1079
  normalizeAllowEntry: createPairingPrefixStripper(/^(twitch:)?user:?/i),
1316
1080
  notifyApproval: createLoggedPairingApprovalNotifier(({ id }) => `Pairing approved for user ${id} (notification sent via chat if possible)`, console.warn)
1317
1081
  },
1082
+ threading: { matchesToolContextTarget: ({ target, toolContext }) => {
1083
+ const channel = normalizeTwitchMessagingTarget(target);
1084
+ return Boolean(channel) && [toolContext.currentChannelId, toolContext.currentMessagingTarget].some((current) => current != null && normalizeTwitchMessagingTarget(current) === channel);
1085
+ } },
1318
1086
  outbound: twitchOutbound,
1319
1087
  base: {
1320
1088
  id: "twitch",
@@ -1326,10 +1094,16 @@ const twitchPlugin = createChatChannelPlugin({
1326
1094
  blurb: "Twitch chat integration",
1327
1095
  aliases: ["twitch-chat"]
1328
1096
  },
1329
- setupContract: twitchSetupContract,
1330
- setupWizard: twitchSetupWizard,
1097
+ setupContract: twitchSetupPlugin.setupContract,
1098
+ setupWizard: twitchSetupPlugin.setupWizard,
1099
+ reload: twitchSetupPlugin.reload,
1331
1100
  capabilities: { chatTypes: ["group"] },
1332
1101
  messaging: {
1102
+ normalizeTarget: normalizeTwitchMessagingTarget,
1103
+ targetResolver: {
1104
+ looksLikeId: (input) => Boolean(normalizeTwitchMessagingTarget(input)),
1105
+ hint: "<channel-name>"
1106
+ },
1333
1107
  inferTargetChatType: ({ to }) => normalizeTwitchMessagingTarget(to) ? "group" : void 0,
1334
1108
  resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
1335
1109
  const channel = normalizeTwitchMessagingTarget(target);
@@ -1358,7 +1132,7 @@ const twitchPlugin = createChatChannelPlugin({
1358
1132
  account,
1359
1133
  configured: isAccountConfigured(account, account.accessToken)
1360
1134
  }) : {
1361
- accountId: DEFAULT_ACCOUNT_ID,
1135
+ accountId: DEFAULT_ACCOUNT_ID$1,
1362
1136
  enabled: false,
1363
1137
  configured: false
1364
1138
  }
@@ -1379,7 +1153,7 @@ const twitchPlugin = createChatChannelPlugin({
1379
1153
  });
1380
1154
  } },
1381
1155
  status: createComputedAccountStatusAdapter({
1382
- defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
1156
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$1),
1383
1157
  buildChannelSummary: ({ snapshot }) => buildPassiveProbedChannelStatusSummary(snapshot),
1384
1158
  probeAccount: async ({ account, timeoutMs }) => await probeTwitch(account, timeoutMs),
1385
1159
  collectStatusIssues: collectTwitchStatusIssues,
@@ -1397,6 +1171,8 @@ const twitchPlugin = createChatChannelPlugin({
1397
1171
  startAccount: async (ctx) => {
1398
1172
  const account = ctx.account;
1399
1173
  const accountId = ctx.accountId;
1174
+ const channelRuntime = ctx.channelRuntime;
1175
+ if (!channelRuntime?.inbound?.buildContext) throw new Error("Twitch requires its registered channel runtime context builder");
1400
1176
  const statusSink = createAccountStatusSink({
1401
1177
  accountId,
1402
1178
  setStatus: ctx.setStatus
@@ -1412,10 +1188,11 @@ const twitchPlugin = createChatChannelPlugin({
1412
1188
  await runPassiveAccountLifecycle({
1413
1189
  abortSignal: ctx.abortSignal,
1414
1190
  start: async () => {
1415
- const { monitorTwitchProvider } = await import("./monitor-iY6U867S.js");
1191
+ const { monitorTwitchProvider } = await import("./monitor-BTccCPPI.js");
1416
1192
  return monitorTwitchProvider({
1417
1193
  account,
1418
1194
  accountId,
1195
+ channelRuntime,
1419
1196
  config: ctx.cfg,
1420
1197
  runtime: ctx.runtime,
1421
1198
  abortSignal: ctx.abortSignal,
@@ -1450,4 +1227,4 @@ const twitchPlugin = createChatChannelPlugin({
1450
1227
  }
1451
1228
  });
1452
1229
  //#endregion
1453
- export { stripMarkdownForTwitch as n, getOrCreateClientManager as r, twitchPlugin as t };
1230
+ export { sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };
@@ -1,2 +1,2 @@
1
- import { n as twitchSetupPlugin } from "./setup-surface-1wrrTKpx.js";
1
+ import { t as twitchSetupPlugin } from "./setup-surface-fSAA11EJ.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 allowFrom = normalizeStringEntries((await prompter.text({
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
- }) ?? "").split(/[\n,;]+/g));
420
+ });
421
+ const allowFrom = normalizeStringEntries((entry ?? "").split(/[\n,;]+/g));
432
422
  return setTwitchAccount(cfg, {
433
423
  ...account ?? void 0,
434
424
  allowFrom
@@ -514,10 +504,11 @@ const twitchSetupWizard = {
514
504
  const twitchSetupPlugin = {
515
505
  id: channel,
516
506
  meta: getChatChannelMeta(channel),
507
+ reload: { configPrefixes: ["channels.twitch"] },
517
508
  capabilities: { chatTypes: ["group"] },
518
509
  config: twitchConfigAdapter,
519
510
  setupContract: twitchSetupContract,
520
511
  setupWizard: twitchSetupWizard
521
512
  };
522
513
  //#endregion
523
- export { getAccountConfig as a, resolveTwitchSnapshotAccountId as c, isAccountConfigured as d, missingTargetError as f, resolveTwitchToken as h, DEFAULT_ACCOUNT_ID$1 as i, twitchConfigAdapter as l, normalizeTwitchChannel as m, twitchSetupPlugin as n, resolveDefaultTwitchAccountId as o, normalizeToken as p, twitchSetupWizard as r, resolveTwitchAccountContext as s, twitchSetupContract as t, generateMessageId as u };
514
+ export { resolveTwitchAccountContext as a, isAccountConfigured as c, normalizeTwitchChannel as d, resolveTwitchToken as f, resolveDefaultTwitchAccountId as i, missingTargetError as l, DEFAULT_ACCOUNT_ID$1 as n, resolveTwitchSnapshotAccountId as o, getAccountConfig as r, twitchConfigAdapter as s, twitchSetupPlugin as t, normalizeToken as u };
@@ -2,7 +2,6 @@
2
2
  "id": "twitch",
3
3
  "name": "Twitch",
4
4
  "description": "OpenClaw Twitch channel plugin for chat and moderation workflows.",
5
- "icon": "https://cdn.simpleicons.org/twitch",
6
5
  "activation": {
7
6
  "onStartup": false
8
7
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/twitch",
3
- "version": "2026.9.1-beta.1",
3
+ "version": "2026.9.2",
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-beta.1"
33
+ "pluginApi": ">=2026.9.2"
34
34
  },
35
35
  "build": {
36
- "openclawVersion": "2026.9.1-beta.1"
36
+ "openclawVersion": "2026.9.2"
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-beta.1"
74
+ "openclaw": ">=2026.9.2"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "openclaw": {