@openclaw/twitch 2026.7.2-beta.5 → 2026.8.1-beta.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/dist/api.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as twitchPlugin } from "./plugin-CNFX3B8N.js";
1
+ import { t as twitchPlugin } from "./plugin-pRKPTroN.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-CNFX3B8N.js";
1
+ import { t as twitchPlugin } from "./plugin-pRKPTroN.js";
2
2
  export { twitchPlugin };
@@ -1,9 +1,9 @@
1
- import { h as normalizeTwitchChannel } from "./setup-surface-Dh9kVN1p.js";
2
- import { n as stripMarkdownForTwitch, r as getOrCreateClientManager } from "./plugin-CNFX3B8N.js";
1
+ import { m as normalizeTwitchChannel } from "./setup-surface-1wrrTKpx.js";
2
+ import { n as stripMarkdownForTwitch, r as getOrCreateClientManager } from "./plugin-pRKPTroN.js";
3
3
  import { t as getTwitchRuntime } from "./runtime-B5If4b0g.js";
4
- import { createChannelIngressMonitor } from "openclaw/plugin-sdk/channel-outbound";
4
+ import { createChannelIngressError, createChannelIngressMonitor } from "openclaw/plugin-sdk/channel-outbound";
5
5
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
6
- import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { normalizeLowercaseStringOrEmpty, normalizeNullableString } from "openclaw/plugin-sdk/string-coerce-runtime";
7
7
  import { HttpStatusCodeError } from "@twurple/api-call";
8
8
  import { createChannelInboundEnvelopeBuilder } from "openclaw/plugin-sdk/channel-inbound";
9
9
  import { createChannelIngressResolver, defineStableChannelIngressIdentity } from "openclaw/plugin-sdk/channel-ingress-runtime";
@@ -33,7 +33,7 @@ const twitchRoleIdentity = defineStableChannelIngressIdentity({
33
33
  async function checkTwitchAccessControl(params) {
34
34
  const { message, account, botUsername } = params;
35
35
  const policyKind = resolveTwitchPolicyKind(account);
36
- const decision = (await createChannelIngressResolver({
36
+ const resolved = await createChannelIngressResolver({
37
37
  channelId: "twitch",
38
38
  accountId: "default",
39
39
  identity: policyKind === "role" ? twitchRoleIdentity : twitchUserIdentity
@@ -43,6 +43,7 @@ async function checkTwitchAccessControl(params) {
43
43
  kind: "group",
44
44
  id: message.channel
45
45
  },
46
+ contextBinding: params.contextBinding,
46
47
  event: { mayPair: false },
47
48
  mentionFacts: {
48
49
  canDetectMention: true,
@@ -56,7 +57,8 @@ async function checkTwitchAccessControl(params) {
56
57
  order: "before-sender"
57
58
  } },
58
59
  groupAllowFrom: policyKind === "allowFrom" ? account.allowFrom : policyKind === "role" ? account.allowedRoles : void 0
59
- })).ingress;
60
+ });
61
+ const decision = resolved.ingress;
60
62
  if (decision.decisiveGateId === "activation" && decision.admission !== "dispatch") return {
61
63
  allowed: false,
62
64
  reason: "message does not mention the bot (requireMention is enabled)"
@@ -64,15 +66,20 @@ async function checkTwitchAccessControl(params) {
64
66
  if (decision.admission === "dispatch") {
65
67
  if (policyKind === "allowFrom") return {
66
68
  allowed: true,
69
+ channelIngress: resolved,
67
70
  matchKey: params.message.userId,
68
71
  matchSource: "allowlist"
69
72
  };
70
73
  if (policyKind === "role") return {
71
74
  allowed: true,
75
+ channelIngress: resolved,
72
76
  matchKey: params.account.allowedRoles?.join(","),
73
77
  matchSource: "role"
74
78
  };
75
- return { allowed: true };
79
+ return {
80
+ allowed: true,
81
+ channelIngress: resolved
82
+ };
76
83
  }
77
84
  if (policyKind === "allowFrom") {
78
85
  if (!params.message.userId) return {
@@ -132,26 +139,13 @@ function mentionsBot(message, botUsername) {
132
139
  //#region extensions/twitch/src/twitch-ingress.ts
133
140
  const TWITCH_INGRESS_PAYLOAD_VERSION = 1;
134
141
  const TWITCH_INGRESS_DRAIN_INTERVAL_MS = 1e3;
135
- const TWITCH_INGRESS_PRUNE_INTERVAL_MS = 3600 * 1e3;
136
- const TWITCH_INGRESS_COMPLETED_TTL_MS = 720 * 60 * 60 * 1e3;
137
- const TWITCH_INGRESS_COMPLETED_MAX_ENTRIES = 1e3;
138
- const TWITCH_INGRESS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
139
- const TWITCH_INGRESS_FAILED_MAX_ENTRIES = 1e3;
140
- var TwitchIngressPermanentError = class extends Error {
141
- constructor(message, options) {
142
- super(message, options);
143
- this.name = "TwitchIngressPermanentError";
144
- }
145
- };
146
- function nonEmptyString(value) {
147
- return typeof value === "string" && value.trim() ? value.trim() : null;
148
- }
142
+ const TwitchIngressPermanentError = createChannelIngressError("TwitchIngressPermanentError");
149
143
  function inspectTwitchIngressEvent(event) {
150
144
  if (!event || typeof event !== "object" || Array.isArray(event)) throw new TwitchIngressPermanentError("Twitch ingress event must be an object.");
151
145
  const candidate = event;
152
- const eventId = nonEmptyString(candidate.id);
146
+ const eventId = normalizeNullableString(candidate.id);
153
147
  if (!eventId) throw new TwitchIngressPermanentError("Twitch ingress event is missing its message id.");
154
- const rawChannel = nonEmptyString(candidate.channel);
148
+ const rawChannel = normalizeNullableString(candidate.channel);
155
149
  const channel = rawChannel ? normalizeTwitchChannel(rawChannel) : "";
156
150
  if (!channel) throw new TwitchIngressPermanentError("Twitch ingress event is missing its channel.");
157
151
  return {
@@ -170,8 +164,8 @@ function deserializeTwitchIngressEvent(rawEvent) {
170
164
  }
171
165
  function normalizeClaimedTwitchMessage(event, claimedId) {
172
166
  const candidate = event;
173
- const username = nonEmptyString(candidate.username);
174
- const rawChannel = nonEmptyString(candidate.channel);
167
+ const username = normalizeNullableString(candidate.username);
168
+ const rawChannel = normalizeNullableString(candidate.channel);
175
169
  if (!username || typeof candidate.message !== "string" || !rawChannel) throw new TwitchIngressPermanentError("Twitch ingress event shape is invalid.");
176
170
  return {
177
171
  ...candidate,
@@ -196,7 +190,6 @@ function createTwitchIngress(options) {
196
190
  const queue = options.queue ?? getTwitchRuntime().state.openChannelIngressQueue({ accountId: options.accountId });
197
191
  const shutdown = new AbortController();
198
192
  let stopped = false;
199
- const deferredClaims = /* @__PURE__ */ new Map();
200
193
  const monitor = createChannelIngressMonitor({
201
194
  queue,
202
195
  inspect: (message) => inspectTwitchIngressEvent(message),
@@ -210,17 +203,6 @@ function createTwitchIngress(options) {
210
203
  deliver: async (rawEvent, lifecycle, claim) => {
211
204
  const message = normalizeClaimedTwitchMessage(rawEvent, claim.id);
212
205
  let handedOff = false;
213
- let resolveDeferredClaim;
214
- const deferredClaim = new Promise((resolve) => {
215
- resolveDeferredClaim = resolve;
216
- });
217
- let deferredClaimSettled = false;
218
- const settleDeferredClaim = () => {
219
- if (deferredClaimSettled) return;
220
- deferredClaimSettled = true;
221
- if (deferredClaims.get(claim.id) === deferredClaim) deferredClaims.delete(claim.id);
222
- resolveDeferredClaim();
223
- };
224
206
  const deliveryAbortSignal = AbortSignal.any([lifecycle.abortSignal, shutdown.signal]);
225
207
  try {
226
208
  await options.deliver(message, {
@@ -228,24 +210,15 @@ function createTwitchIngress(options) {
228
210
  abortSignal: deliveryAbortSignal,
229
211
  onAdopted: async () => {
230
212
  handedOff = true;
231
- try {
232
- await lifecycle.onAdopted();
233
- } finally {
234
- settleDeferredClaim();
235
- }
213
+ await lifecycle.onAdopted();
236
214
  },
237
215
  onDeferred: () => {
238
216
  handedOff = true;
239
- if (!deferredClaimSettled) deferredClaims.set(claim.id, deferredClaim);
240
217
  lifecycle.onDeferred();
241
218
  },
242
219
  onAbandoned: async () => {
243
220
  handedOff = true;
244
- try {
245
- await lifecycle.onAbandoned();
246
- } finally {
247
- settleDeferredClaim();
248
- }
221
+ await lifecycle.onAbandoned();
249
222
  }
250
223
  });
251
224
  } catch (error) {
@@ -260,13 +233,11 @@ function createTwitchIngress(options) {
260
233
  error: stoppedError()
261
234
  };
262
235
  },
236
+ deferredClaims: "manual",
263
237
  pollIntervalMs: options.pollIntervalMs ?? TWITCH_INGRESS_DRAIN_INTERVAL_MS,
264
238
  retention: {
265
- pruneIntervalMs: TWITCH_INGRESS_PRUNE_INTERVAL_MS,
266
- completedTtlMs: TWITCH_INGRESS_COMPLETED_TTL_MS,
267
- completedMaxEntries: TWITCH_INGRESS_COMPLETED_MAX_ENTRIES,
268
- failedTtlMs: TWITCH_INGRESS_FAILED_TTL_MS,
269
- failedMaxEntries: TWITCH_INGRESS_FAILED_MAX_ENTRIES
239
+ completedMaxEntries: 1e3,
240
+ failedMaxEntries: 1e3
270
241
  },
271
242
  drain: {
272
243
  resolveNonRetryableFailure: (error) => {
@@ -301,7 +272,7 @@ function createTwitchIngress(options) {
301
272
  shutdown.abort(stoppedError());
302
273
  await monitor.pause();
303
274
  await monitor.waitForIdle();
304
- await Promise.allSettled(deferredClaims.values());
275
+ await monitor.waitForDeferredClaims();
305
276
  await monitor.stop();
306
277
  })();
307
278
  return stopTask;
@@ -311,17 +282,32 @@ function createTwitchIngress(options) {
311
282
  //#endregion
312
283
  //#region extensions/twitch/src/monitor.ts
313
284
  /**
314
- * Twitch message monitor - processes incoming messages and routes to agents.
315
- *
316
- * This monitor connects to the Twitch client manager, processes incoming messages,
317
- * resolves agent routes, and handles replies.
318
- */
319
- /**
320
285
  * Process an incoming Twitch message and dispatch to agent.
321
286
  */
322
287
  async function processTwitchMessage(params) {
323
288
  const { message, account, accountId, config, runtime, core, turnAdoptionLifecycle, statusSink } = params;
324
289
  const cfg = config;
290
+ const route = core.channel.routing.resolveAgentRoute({
291
+ cfg,
292
+ channel: "twitch",
293
+ accountId,
294
+ peer: {
295
+ kind: "group",
296
+ id: message.channel
297
+ }
298
+ });
299
+ const exactAccess = await checkTwitchAccessControl({
300
+ message,
301
+ account,
302
+ botUsername: normalizeLowercaseStringOrEmpty(account.username),
303
+ contextBinding: {
304
+ agentId: route.agentId,
305
+ sessionKey: route.sessionKey,
306
+ messageId: message.id,
307
+ inboundEventKind: "user_request"
308
+ }
309
+ });
310
+ if (!exactAccess.allowed) return;
325
311
  await core.channel.inbound.run({
326
312
  channel: "twitch",
327
313
  accountId,
@@ -337,15 +323,6 @@ async function processTwitchMessage(params) {
337
323
  raw: incoming
338
324
  }),
339
325
  resolveTurn: async (input) => {
340
- const route = core.channel.routing.resolveAgentRoute({
341
- cfg,
342
- channel: "twitch",
343
- accountId,
344
- peer: {
345
- kind: "group",
346
- id: message.channel
347
- }
348
- });
349
326
  const senderId = message.userId ?? message.username;
350
327
  const fromLabel = message.displayName ?? message.username;
351
328
  const body = createChannelInboundEnvelopeBuilder({
@@ -358,6 +335,7 @@ async function processTwitchMessage(params) {
358
335
  body: input.rawText
359
336
  });
360
337
  const ctxPayload = core.channel.inbound.buildContext({
338
+ channelIngress: exactAccess.channelIngress,
361
339
  channel: "twitch",
362
340
  accountId,
363
341
  messageId: input.id,
@@ -477,7 +455,7 @@ async function monitorTwitchProvider(options) {
477
455
  warn: (msg) => coreLogger.warn(msg),
478
456
  error: (msg) => coreLogger.error(msg),
479
457
  debug: logVerboseMessage
480
- });
458
+ }, statusSink);
481
459
  try {
482
460
  await clientManager.getClient(account, config, accountId);
483
461
  } catch (error) {
@@ -1,8 +1,8 @@
1
- import { a as DEFAULT_ACCOUNT_ID, c as resolveTwitchAccountContext, d as generateMessageId, f as isAccountConfigured, g as resolveTwitchToken, h as normalizeTwitchChannel, i as twitchSetupWizard, l as resolveTwitchSnapshotAccountId, m as normalizeToken, n as twitchSetupContract, o as getAccountConfig, p as missingTargetError, s as resolveDefaultTwitchAccountId, t as twitchSetupAdapter, u as twitchConfigAdapter } from "./setup-surface-Dh9kVN1p.js";
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";
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 { createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
5
+ import { createAccountStatusSink, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, 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";
@@ -11,7 +11,8 @@ import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "opencla
11
11
  import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
12
12
  import { RefreshingAuthProvider, StaticAuthProvider } from "@twurple/auth";
13
13
  import { ChatClient, LogLevel } from "@twurple/chat";
14
- import { sliceUtf16Safe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
14
+ import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
15
+ import { runChannelProbe, sliceUtf16Safe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
15
16
  import { z } from "zod";
16
17
  import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
17
18
  //#region extensions/twitch/src/twitch-client.ts
@@ -20,14 +21,28 @@ const TWITCH_CHAT_AUTH_INTENTS = ["chat"];
20
21
  * Manages Twitch chat client connections
21
22
  */
22
23
  var TwitchClientManager = class {
23
- constructor(logger) {
24
+ constructor(logger, statusSink) {
24
25
  this.logger = logger;
26
+ this.statusSink = statusSink;
25
27
  this.clients = /* @__PURE__ */ new Map();
26
28
  this.pendingClients = /* @__PURE__ */ new Map();
27
29
  this.connectionPromises = /* @__PURE__ */ new Map();
28
30
  this.messageHandlers = /* @__PURE__ */ new Map();
29
31
  this.messageHandlerTokens = /* @__PURE__ */ new Map();
30
32
  }
33
+ setStatusSink(statusSink) {
34
+ if (statusSink) this.statusSink = statusSink;
35
+ }
36
+ publishReady() {
37
+ this.statusSink?.(channelReadyPatch());
38
+ }
39
+ publishRecovering(lastError) {
40
+ this.statusSink?.({
41
+ connected: false,
42
+ lifecycle: "recovering",
43
+ lastError
44
+ });
45
+ }
31
46
  /**
32
47
  * Create an auth provider for the account.
33
48
  */
@@ -122,7 +137,6 @@ var TwitchClientManager = class {
122
137
  } }
123
138
  }
124
139
  });
125
- this.setupClientHandlers(client, account);
126
140
  this.pendingClients.set(key, client);
127
141
  try {
128
142
  await this.connectClient(client, account);
@@ -135,6 +149,7 @@ var TwitchClientManager = class {
135
149
  if (this.pendingClients.get(key) === client) this.pendingClients.delete(key);
136
150
  throw error;
137
151
  }
152
+ this.setupClientHandlers(client, account);
138
153
  this.clients.set(key, client);
139
154
  this.logger.info(`Connected to Twitch as ${account.username}`);
140
155
  return client;
@@ -159,10 +174,15 @@ var TwitchClientManager = class {
159
174
  }
160
175
  resolve();
161
176
  };
162
- listeners.push(client.onAuthenticationSuccess(() => finish()), client.onAuthenticationFailure((text) => {
177
+ listeners.push(client.onAuthenticationSuccess(() => {
178
+ this.publishReady();
179
+ finish();
180
+ }), client.onAuthenticationFailure((text) => {
163
181
  authRetryPending = true;
182
+ this.publishRecovering(text);
164
183
  this.logger.warn(`Twitch authentication failed for ${account.username}; waiting for retry, disconnect, or timeout: ${text}`);
165
184
  }), client.onDisconnect((manual, reason) => {
185
+ if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
166
186
  if (authRetryPending && !manual) {
167
187
  this.logger.debug?.(`Twitch disconnected during auth retry for ${account.username}: ${formatErrorMessage(reason)}`);
168
188
  return;
@@ -205,6 +225,13 @@ var TwitchClientManager = class {
205
225
  });
206
226
  }
207
227
  });
228
+ client.onAuthenticationSuccess(() => this.publishReady());
229
+ client.onAuthenticationFailure((text) => {
230
+ this.publishRecovering(text);
231
+ });
232
+ client.onDisconnect((manual, reason) => {
233
+ if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
234
+ });
208
235
  this.logger.info(`Set up handlers for ${key}`);
209
236
  }
210
237
  /**
@@ -316,10 +343,13 @@ const registry = /* @__PURE__ */ new Map();
316
343
  * @param logger - Logger instance
317
344
  * @returns The client manager
318
345
  */
319
- function getOrCreateClientManager(accountId, logger) {
346
+ function getOrCreateClientManager(accountId, logger, statusSink) {
320
347
  const existing = registry.get(accountId);
321
- if (existing) return existing.manager;
322
- const manager = new TwitchClientManager(logger);
348
+ if (existing) {
349
+ existing.manager.setStatusSink(statusSink);
350
+ return existing.manager;
351
+ }
352
+ const manager = new TwitchClientManager(logger, statusSink);
323
353
  registry.set(accountId, {
324
354
  manager,
325
355
  accountId,
@@ -857,6 +887,8 @@ const TwitchAccountShape = {
857
887
  channel: z.string().min(1),
858
888
  /** Enable this account */
859
889
  enabled: z.boolean().optional(),
890
+ /** Allow channel-initiated configuration writes */
891
+ configWrites: z.boolean().optional(),
860
892
  /** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
861
893
  allowFrom: z.array(z.string()).optional(),
862
894
  /** Roles allowed to interact with the bot (e.g., ["moderator", "vip", "subscriber"]) */
@@ -884,6 +916,7 @@ const TwitchAccountSchema = z.object(TwitchAccountShape);
884
916
  const TwitchConfigBaseShape = {
885
917
  name: z.string().optional(),
886
918
  enabled: z.boolean().optional(),
919
+ configWrites: z.boolean().optional(),
887
920
  markdown: MarkdownConfigSchema.optional(),
888
921
  defaultAccount: z.string().optional()
889
922
  };
@@ -926,66 +959,62 @@ const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
926
959
  * to the chat server and verify the bot's username.
927
960
  */
928
961
  async function probeTwitch(account, timeoutMs) {
929
- const started = Date.now();
930
- if (!account.accessToken || !account.username) return {
931
- ok: false,
932
- error: "missing credentials (accessToken, username)",
933
- username: account.username,
934
- elapsedMs: Date.now() - started
935
- };
936
- const rawToken = normalizeToken(account.accessToken.trim());
937
962
  let client;
938
963
  try {
939
- client = new ChatClient({ authProvider: new StaticAuthProvider(account.clientId ?? "", rawToken) });
940
- const connectionPromise = new Promise((resolve, reject) => {
941
- let settled = false;
942
- const cleanup = () => {
943
- if (settled) return;
944
- settled = true;
945
- connectListener?.unbind();
946
- disconnectListener?.unbind();
947
- authFailListener?.unbind();
964
+ return await runChannelProbe(void 0, async () => {
965
+ if (!account.accessToken || !account.username) return {
966
+ ok: false,
967
+ error: "missing credentials (accessToken, username)",
968
+ username: account.username
948
969
  };
949
- const connectListener = client?.onConnect(() => {
950
- cleanup();
951
- resolve();
952
- });
953
- const disconnectListener = client?.onDisconnect((_manually, reason) => {
954
- cleanup();
955
- reject(reason || /* @__PURE__ */ new Error("Disconnected"));
970
+ const rawToken = normalizeToken(account.accessToken.trim());
971
+ client = new ChatClient({ authProvider: new StaticAuthProvider(account.clientId ?? "", rawToken) });
972
+ const connectionPromise = new Promise((resolve, reject) => {
973
+ let settled = false;
974
+ const cleanup = () => {
975
+ if (settled) return;
976
+ settled = true;
977
+ connectListener?.unbind();
978
+ disconnectListener?.unbind();
979
+ authFailListener?.unbind();
980
+ };
981
+ const connectListener = client?.onConnect(() => {
982
+ cleanup();
983
+ resolve();
984
+ });
985
+ const disconnectListener = client?.onDisconnect((_manually, reason) => {
986
+ cleanup();
987
+ reject(reason || /* @__PURE__ */ new Error("Disconnected"));
988
+ });
989
+ const authFailListener = client?.onAuthenticationFailure(() => {
990
+ cleanup();
991
+ reject(/* @__PURE__ */ new Error("Authentication failed"));
992
+ });
956
993
  });
957
- const authFailListener = client?.onAuthenticationFailure(() => {
958
- cleanup();
959
- reject(/* @__PURE__ */ new Error("Authentication failed"));
994
+ let timeoutHandle;
995
+ const timeout = new Promise((_, reject) => {
996
+ timeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error(`timeout after ${timeoutMs}ms`)), timeoutMs);
960
997
  });
961
- });
962
- let timeoutHandle;
963
- const timeout = new Promise((_, reject) => {
964
- timeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error(`timeout after ${timeoutMs}ms`)), timeoutMs);
965
- });
966
- client.connect();
967
- try {
968
- await Promise.race([connectionPromise, timeout]);
969
- } finally {
970
- if (timeoutHandle) clearTimeout(timeoutHandle);
971
- }
972
- client.quit();
973
- client = void 0;
974
- return {
975
- ok: true,
976
- connected: true,
977
- username: account.username,
978
- channel: account.channel,
979
- elapsedMs: Date.now() - started
980
- };
981
- } catch (error) {
982
- return {
998
+ client.connect();
999
+ try {
1000
+ await Promise.race([connectionPromise, timeout]);
1001
+ } finally {
1002
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1003
+ }
1004
+ client.quit();
1005
+ client = void 0;
1006
+ return {
1007
+ ok: true,
1008
+ connected: true,
1009
+ username: account.username,
1010
+ channel: account.channel
1011
+ };
1012
+ }, (error) => ({
983
1013
  ok: false,
984
1014
  error: formatErrorMessage(error),
985
1015
  username: account.username,
986
- channel: account.channel,
987
- elapsedMs: Date.now() - started
988
- };
1016
+ channel: account.channel
1017
+ }));
989
1018
  } finally {
990
1019
  if (client) try {
991
1020
  client.quit();
@@ -1294,28 +1323,30 @@ const twitchPlugin = createChatChannelPlugin({
1294
1323
  blurb: "Twitch chat integration",
1295
1324
  aliases: ["twitch-chat"]
1296
1325
  },
1297
- setup: twitchSetupAdapter,
1298
1326
  setupContract: twitchSetupContract,
1299
1327
  setupWizard: twitchSetupWizard,
1300
1328
  capabilities: { chatTypes: ["group"] },
1301
- messaging: { resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
1302
- const channel = normalizeTwitchMessagingTarget(target);
1303
- if (!channel) return null;
1304
- return buildChannelOutboundSessionRoute({
1305
- cfg,
1306
- agentId,
1307
- channel: "twitch",
1308
- accountId,
1309
- recipientSessionExact: true,
1310
- peer: {
1311
- kind: "group",
1312
- id: channel
1313
- },
1314
- chatType: "group",
1315
- from: `twitch:channel:${channel}`,
1316
- to: channel
1317
- });
1318
- } },
1329
+ messaging: {
1330
+ inferTargetChatType: ({ to }) => normalizeTwitchMessagingTarget(to) ? "group" : void 0,
1331
+ resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target }) => {
1332
+ const channel = normalizeTwitchMessagingTarget(target);
1333
+ if (!channel) return null;
1334
+ return buildChannelOutboundSessionRoute({
1335
+ cfg,
1336
+ agentId,
1337
+ channel: "twitch",
1338
+ accountId,
1339
+ recipientSessionExact: true,
1340
+ peer: {
1341
+ kind: "group",
1342
+ id: channel
1343
+ },
1344
+ chatType: "group",
1345
+ from: `twitch:channel:${channel}`,
1346
+ to: channel
1347
+ });
1348
+ }
1349
+ },
1319
1350
  message: twitchMessageAdapter,
1320
1351
  configSchema: buildChannelConfigSchema(TwitchConfigSchema),
1321
1352
  config: {
@@ -1363,24 +1394,29 @@ const twitchPlugin = createChatChannelPlugin({
1363
1394
  startAccount: async (ctx) => {
1364
1395
  const account = ctx.account;
1365
1396
  const accountId = ctx.accountId;
1366
- ctx.setStatus?.({
1397
+ const statusSink = createAccountStatusSink({
1367
1398
  accountId,
1399
+ setStatus: ctx.setStatus
1400
+ });
1401
+ statusSink({
1368
1402
  running: true,
1369
1403
  lastStartAt: Date.now(),
1370
- lastError: null
1404
+ lastError: null,
1405
+ lifecycle: "starting"
1371
1406
  });
1372
1407
  ctx.log?.info(`Starting Twitch connection for ${account.username}`);
1373
1408
  try {
1374
1409
  await runPassiveAccountLifecycle({
1375
1410
  abortSignal: ctx.abortSignal,
1376
1411
  start: async () => {
1377
- const { monitorTwitchProvider } = await import("./monitor-D9sSDntu.js");
1412
+ const { monitorTwitchProvider } = await import("./monitor-D6ovNCYU.js");
1378
1413
  return monitorTwitchProvider({
1379
1414
  account,
1380
1415
  accountId,
1381
1416
  config: ctx.cfg,
1382
1417
  runtime: ctx.runtime,
1383
- abortSignal: ctx.abortSignal
1418
+ abortSignal: ctx.abortSignal,
1419
+ statusSink
1384
1420
  });
1385
1421
  },
1386
1422
  stop: async (monitor) => {
@@ -1,2 +1,2 @@
1
- import { r as twitchSetupPlugin } from "./setup-surface-Dh9kVN1p.js";
1
+ import { n as twitchSetupPlugin } from "./setup-surface-1wrrTKpx.js";
2
2
  export { twitchSetupPlugin };
@@ -287,9 +287,9 @@ async function noteTwitchSetupHelp(prompter) {
287
287
  `Docs: ${formatDocsLink("/channels/twitch", "channels/twitch")}`
288
288
  ].join("\n"), t("wizard.twitch.setupTitle"));
289
289
  }
290
- async function promptToken(prompter, account, envToken) {
290
+ async function promptToken(prompter, account) {
291
291
  const existingToken = account?.accessToken ?? "";
292
- if (existingToken && !envToken) {
292
+ if (existingToken) {
293
293
  if (await prompter.confirm({
294
294
  message: t("wizard.twitch.accessTokenKeep"),
295
295
  initialValue: true
@@ -297,7 +297,7 @@ async function promptToken(prompter, account, envToken) {
297
297
  }
298
298
  return (await prompter.text({
299
299
  message: t("wizard.twitch.oauthTokenPrompt"),
300
- initialValue: envToken ?? "",
300
+ sensitive: true,
301
301
  validate: (value) => {
302
302
  const raw = value?.trim() ?? "";
303
303
  if (!raw) return "Required";
@@ -305,26 +305,35 @@ async function promptToken(prompter, account, envToken) {
305
305
  }
306
306
  })).trim();
307
307
  }
308
- async function promptUsername(prompter, account) {
308
+ async function promptRequiredTwitchAccountValue(prompter, message, initialValue) {
309
309
  return (await prompter.text({
310
- message: t("wizard.twitch.botUsernamePrompt"),
311
- initialValue: account?.username ?? "",
310
+ message,
311
+ initialValue: initialValue ?? "",
312
312
  validate: (value) => value?.trim() ? void 0 : "Required"
313
313
  })).trim();
314
314
  }
315
+ async function promptUsername(prompter, account) {
316
+ return await promptRequiredTwitchAccountValue(prompter, t("wizard.twitch.botUsernamePrompt"), account?.username);
317
+ }
315
318
  async function promptClientId(prompter, account) {
316
- return (await prompter.text({
317
- message: t("wizard.twitch.clientIdPrompt"),
318
- initialValue: account?.clientId ?? "",
319
- validate: (value) => value?.trim() ? void 0 : "Required"
320
- })).trim();
319
+ return await promptRequiredTwitchAccountValue(prompter, t("wizard.twitch.clientIdPrompt"), account?.clientId);
321
320
  }
322
321
  async function promptChannelName(prompter, account) {
323
- return (await prompter.text({
324
- message: t("wizard.twitch.channelJoinPrompt"),
325
- initialValue: account?.channel ?? "",
326
- validate: (value) => value?.trim() ? void 0 : "Required"
327
- })).trim();
322
+ return await promptRequiredTwitchAccountValue(prompter, t("wizard.twitch.channelJoinPrompt"), account?.channel);
323
+ }
324
+ async function promptRefreshCredential(params) {
325
+ const existingValue = params.existingValue?.trim();
326
+ if (existingValue) {
327
+ if (await params.prompter.confirm({
328
+ message: params.keepMessage,
329
+ initialValue: true
330
+ })) return existingValue;
331
+ }
332
+ return (await params.prompter.text({
333
+ message: params.inputMessage,
334
+ sensitive: true,
335
+ validate: (input) => input?.trim() ? void 0 : "Required"
336
+ })).trim() || void 0;
328
337
  }
329
338
  async function promptRefreshTokenSetup(prompter, account) {
330
339
  if (!await prompter.confirm({
@@ -332,16 +341,18 @@ async function promptRefreshTokenSetup(prompter, account) {
332
341
  initialValue: Boolean(account?.clientSecret && account?.refreshToken)
333
342
  })) return {};
334
343
  return {
335
- clientSecret: (await prompter.text({
336
- message: t("wizard.twitch.clientSecretPrompt"),
337
- initialValue: account?.clientSecret ?? "",
338
- validate: (value) => value?.trim() ? void 0 : "Required"
339
- })).trim() || void 0,
340
- refreshToken: (await prompter.text({
341
- message: t("wizard.twitch.refreshTokenInputPrompt"),
342
- initialValue: account?.refreshToken ?? "",
343
- validate: (value) => value?.trim() ? void 0 : "Required"
344
- })).trim() || void 0
344
+ clientSecret: await promptRefreshCredential({
345
+ prompter,
346
+ existingValue: account?.clientSecret,
347
+ keepMessage: t("wizard.twitch.clientSecretKeep"),
348
+ inputMessage: t("wizard.twitch.clientSecretPrompt")
349
+ }),
350
+ refreshToken: await promptRefreshCredential({
351
+ prompter,
352
+ existingValue: account?.refreshToken,
353
+ keepMessage: t("wizard.twitch.refreshTokenKeep"),
354
+ inputMessage: t("wizard.twitch.refreshTokenInputPrompt")
355
+ })
345
356
  };
346
357
  }
347
358
  async function configureWithEnvToken(cfg, prompter, account, envToken, forceAllowFrom, dmPolicy, accountId = resolveSetupAccountId(cfg)) {
@@ -440,14 +451,13 @@ const twitchGroupAccess = {
440
451
  resolveAllowlist: async () => [],
441
452
  applyAllowlist: ({ cfg }) => cfg
442
453
  };
443
- const twitchSetupAdapter = {
444
- singleAccountKeysToMove: ["accessToken"],
445
- resolveAccountId: ({ cfg }) => resolveSetupAccountId(cfg),
446
- applyAccountConfig: ({ cfg, accountId }) => setTwitchAccount(cfg, { enabled: true }, accountId)
447
- };
448
454
  const twitchSetupContract = defineChannelSetupContract({
449
455
  fields: {},
450
- legacyAdapter: twitchSetupAdapter
456
+ legacyAdapter: {
457
+ singleAccountKeysToMove: ["accessToken"],
458
+ resolveAccountId: ({ cfg }) => resolveSetupAccountId(cfg),
459
+ applyAccountConfig: ({ cfg, accountId }) => setTwitchAccount(cfg, { enabled: true }, accountId)
460
+ }
451
461
  });
452
462
  const twitchSetupWizard = {
453
463
  channel,
@@ -478,7 +488,7 @@ const twitchSetupWizard = {
478
488
  if (envResult) return envResult;
479
489
  }
480
490
  const username = await promptUsername(prompter, account);
481
- const token = await promptToken(prompter, account, envToken);
491
+ const token = await promptToken(prompter, account);
482
492
  const clientId = await promptClientId(prompter, account);
483
493
  const channelName = await promptChannelName(prompter, account);
484
494
  const { clientSecret, refreshToken } = await promptRefreshTokenSetup(prompter, account);
@@ -506,9 +516,8 @@ const twitchSetupPlugin = {
506
516
  meta: getChatChannelMeta(channel),
507
517
  capabilities: { chatTypes: ["group"] },
508
518
  config: twitchConfigAdapter,
509
- setup: twitchSetupAdapter,
510
519
  setupContract: twitchSetupContract,
511
520
  setupWizard: twitchSetupWizard
512
521
  };
513
522
  //#endregion
514
- export { DEFAULT_ACCOUNT_ID$1 as a, resolveTwitchAccountContext as c, generateMessageId as d, isAccountConfigured as f, resolveTwitchToken as g, normalizeTwitchChannel as h, twitchSetupWizard as i, resolveTwitchSnapshotAccountId as l, normalizeToken as m, twitchSetupContract as n, getAccountConfig as o, missingTargetError as p, twitchSetupPlugin as r, resolveDefaultTwitchAccountId as s, twitchSetupAdapter as t, twitchConfigAdapter as u };
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 };
@@ -28,6 +28,9 @@
28
28
  "enabled": {
29
29
  "type": "boolean"
30
30
  },
31
+ "configWrites": {
32
+ "type": "boolean"
33
+ },
31
34
  "markdown": {
32
35
  "type": "object",
33
36
  "properties": {
@@ -120,6 +123,9 @@
120
123
  "enabled": {
121
124
  "type": "boolean"
122
125
  },
126
+ "configWrites": {
127
+ "type": "boolean"
128
+ },
123
129
  "markdown": {
124
130
  "type": "object",
125
131
  "properties": {
@@ -162,6 +168,9 @@
162
168
  "enabled": {
163
169
  "type": "boolean"
164
170
  },
171
+ "configWrites": {
172
+ "type": "boolean"
173
+ },
165
174
  "allowFrom": {
166
175
  "type": "array",
167
176
  "items": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/twitch",
3
- "version": "2026.7.2-beta.5",
3
+ "version": "2026.8.1-beta.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.7.2-beta.5"
33
+ "pluginApi": ">=2026.8.1-beta.2"
34
34
  },
35
35
  "build": {
36
- "openclawVersion": "2026.7.2-beta.5"
36
+ "openclawVersion": "2026.8.1-beta.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.7.2-beta.5"
74
+ "openclaw": ">=2026.8.1-beta.2"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "openclaw": {