@openclaw/twitch 2026.11.3 → 2026.11.5-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/.setup/{monitor-B-jILw-H.mjs → monitor-BStOwZKj.mjs} +92 -182
- package/dist/.setup/{plugin-CkRhClVg.mjs → plugin-D_NszQlS.mjs} +495 -340
- package/dist/.setup/setup-plugin-api-Czqbbgip.mjs +2 -0
- package/dist/.setup/{setup-surface-BHuTmMZL.mjs → setup-surface-DuCk_ZHo.mjs} +78 -91
- package/dist/.source-module-urls/e92ae748f4a308f6cf1a5ef62518f7ba0627945de435d928747fa07ea1b4421f.json +1 -0
- package/dist/api.js +1 -3
- package/dist/channel-plugin-api.js +1 -2
- package/dist/setup-entry.js +1 -1
- package/dist/setup-plugin-api.js +1 -2
- package/package.json +5 -5
- package/dist/.setup/runtime-B5If4b0g.mjs +0 -8
- package/dist/.setup/setup-plugin-api-BC-Kt0o_.mjs +0 -3
|
@@ -1,51 +1,310 @@
|
|
|
1
|
-
import { a as resolveTwitchAccountContext, c as normalizeToken, i as resolveDefaultTwitchAccountId, l as normalizeTwitchChannel, n as DEFAULT_ACCOUNT_ID$1, o as twitchConfigAdapter, r as getAccountConfig, s as isAccountConfigured, t as twitchSetupPlugin, u as resolveTwitchToken } from "./setup-surface-
|
|
1
|
+
import { a as resolveTwitchAccountContext, c as normalizeToken, i as resolveDefaultTwitchAccountId, l as normalizeTwitchChannel, n as DEFAULT_ACCOUNT_ID$1, o as twitchConfigAdapter, r as getAccountConfig, s as isAccountConfigured, t as twitchSetupPlugin, u as resolveTwitchToken } from "./setup-surface-DuCk_ZHo.mjs";
|
|
2
|
+
import { StaticAuthProvider, accessTokenIsExpired, getTokenInfo } from "@twurple/auth";
|
|
3
|
+
import { ChatClient, LogLevel } from "@twurple/chat";
|
|
2
4
|
import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
|
|
3
5
|
import { MarkdownConfigSchema, buildChannelConfigSchema } from "openclaw/plugin-sdk/channel-config-schema";
|
|
4
6
|
import { buildChannelOutboundSessionRoute, createChatChannelPlugin, stripChannelTargetPrefix } from "openclaw/plugin-sdk/channel-core";
|
|
5
7
|
import { createAccountStatusSink, createChannelMessageAdapterFromOutbound, createMessageReceiptFromOutboundResults, runPassiveAccountLifecycle } from "openclaw/plugin-sdk/channel-outbound";
|
|
6
8
|
import { createLoggedPairingApprovalNotifier, createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
|
|
9
|
+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
7
10
|
import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
|
|
8
11
|
import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-resolution";
|
|
12
|
+
import { runChannelProbe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
13
|
+
import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
|
|
14
|
+
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/account-resolution";
|
|
12
15
|
import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
|
|
13
|
-
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
14
16
|
import { captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
|
|
15
17
|
import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
|
|
16
18
|
import { chunkTextForOutbound, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
|
|
19
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
20
|
+
import { isDeepStrictEqual } from "node:util";
|
|
21
|
+
import { readProviderJsonObjectResponse } from "openclaw/plugin-sdk/provider-http";
|
|
22
|
+
import { createOAuthRefreshError, createOAuthRefreshResponseError, isRecoverableOAuthRefreshFailure, readOAuthRefreshErrorReason } from "openclaw/plugin-sdk/provider-oauth-runtime";
|
|
23
|
+
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
17
24
|
import { normalizeLowercaseStringOrEmpty, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
25
|
+
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
|
|
18
26
|
import { z } from "zod";
|
|
19
|
-
import { runChannelProbe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
20
|
-
import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
|
|
21
27
|
import { HttpStatusCodeError, callTwitchApi } from "@twurple/api-call";
|
|
22
|
-
//#region extensions/twitch/src/
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
//#region extensions/twitch/src/runtime.ts
|
|
29
|
+
const { setRuntime: setTwitchRuntime, getRuntime: getTwitchRuntime } = createPluginRuntimeStore({
|
|
30
|
+
pluginId: "twitch",
|
|
31
|
+
errorMessage: "Twitch runtime not initialized"
|
|
32
|
+
});
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region extensions/twitch/src/oauth-owner.ts
|
|
35
|
+
const tasks = /* @__PURE__ */ new WeakMap();
|
|
36
|
+
function lineageOf(account, token) {
|
|
37
|
+
return createHash("sha256").update(JSON.stringify([
|
|
38
|
+
account.username.toLowerCase(),
|
|
39
|
+
account.clientId,
|
|
40
|
+
account.clientSecret,
|
|
41
|
+
token,
|
|
42
|
+
account.refreshToken,
|
|
43
|
+
account.expiresIn,
|
|
44
|
+
account.obtainmentTimestamp
|
|
45
|
+
])).digest("hex");
|
|
25
46
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
47
|
+
async function exchange(account, refreshToken, assertCurrent) {
|
|
48
|
+
let dispatched = false;
|
|
49
|
+
const { response, release } = await fetchWithSsrFGuard({
|
|
50
|
+
url: "https://id.twitch.tv/oauth2/token",
|
|
51
|
+
policy: { allowedHostnames: ["id.twitch.tv"] },
|
|
52
|
+
requireHttps: true,
|
|
53
|
+
timeoutMs: 3e4,
|
|
54
|
+
auditContext: "twitch.oauth.refresh",
|
|
55
|
+
beforeRequest: () => {
|
|
56
|
+
assertCurrent();
|
|
57
|
+
dispatched = true;
|
|
58
|
+
},
|
|
59
|
+
init: {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: {
|
|
62
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
63
|
+
Accept: "application/json"
|
|
64
|
+
},
|
|
65
|
+
body: new URLSearchParams({
|
|
66
|
+
client_id: account.clientId,
|
|
67
|
+
client_secret: account.clientSecret,
|
|
68
|
+
grant_type: "refresh_token",
|
|
69
|
+
refresh_token: refreshToken
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
}).catch((cause) => {
|
|
73
|
+
throw createOAuthRefreshError("Twitch OAuth refresh transport failed", dispatched ? {
|
|
74
|
+
version: 1,
|
|
75
|
+
phase: "token-response",
|
|
76
|
+
outcome: "unknown"
|
|
77
|
+
} : {
|
|
78
|
+
version: 1,
|
|
79
|
+
phase: "before-dispatch",
|
|
80
|
+
outcome: "not-attempted",
|
|
81
|
+
recovery: {
|
|
82
|
+
kind: "later",
|
|
83
|
+
evidence: "dispatch-not-started"
|
|
84
|
+
}
|
|
85
|
+
}, { cause });
|
|
86
|
+
});
|
|
87
|
+
try {
|
|
88
|
+
let payload;
|
|
89
|
+
try {
|
|
90
|
+
payload = await readProviderJsonObjectResponse(response, "Twitch OAuth refresh", { maxBytes: 262144 });
|
|
91
|
+
} catch {
|
|
92
|
+
throw createOAuthRefreshError("Twitch OAuth refresh returned an unreadable response", {
|
|
93
|
+
version: 1,
|
|
94
|
+
phase: "after-token-response",
|
|
95
|
+
outcome: "unknown",
|
|
96
|
+
status: response.status
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (!response.ok || readOAuthRefreshErrorReason(payload)) throw createOAuthRefreshResponseError("Twitch OAuth refresh", response.status, payload);
|
|
100
|
+
if (typeof payload.access_token !== "string" || !payload.access_token.trim() || typeof payload.refresh_token !== "string" || !payload.refresh_token.trim() || typeof payload.expires_in !== "number" || !Number.isFinite(payload.expires_in) || payload.expires_in < 0 || !Array.isArray(payload.scope) || !payload.scope.every((scope) => typeof scope === "string") || typeof payload.token_type !== "string" || payload.token_type.toLowerCase() !== "bearer") throw createOAuthRefreshError("Twitch OAuth refresh returned invalid tokens", {
|
|
101
|
+
version: 1,
|
|
102
|
+
phase: "after-token-response",
|
|
103
|
+
outcome: "unknown",
|
|
104
|
+
status: response.status
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
accessToken: payload.access_token,
|
|
108
|
+
refreshToken: payload.refresh_token,
|
|
109
|
+
expiresIn: payload.expires_in,
|
|
110
|
+
scope: payload.scope,
|
|
111
|
+
obtainmentTimestamp: Date.now()
|
|
112
|
+
};
|
|
113
|
+
} finally {
|
|
114
|
+
await release();
|
|
36
115
|
}
|
|
37
|
-
}
|
|
116
|
+
}
|
|
117
|
+
/** One durable channel-account owner, including the initial and IRC-requested refresh. */
|
|
118
|
+
async function createManagedTwitchAuthProvider(account, token, accountId) {
|
|
119
|
+
const clientId = account.clientId;
|
|
120
|
+
if (!clientId) throw new Error("Twitch OAuth requires a client ID");
|
|
121
|
+
const runtime = getTwitchRuntime();
|
|
122
|
+
const id = normalizeAccountId(accountId);
|
|
123
|
+
const lineage = lineageOf(account, token);
|
|
124
|
+
const assertCurrent = () => {
|
|
125
|
+
if (getTwitchRuntime() !== runtime) throw new Error("Twitch OAuth runtime changed");
|
|
126
|
+
const cfg = runtime.config.current({ clone: true });
|
|
127
|
+
const current = getAccountConfig(cfg, id);
|
|
128
|
+
if (cfg.channels?.twitch?.enabled === false || current?.enabled === false) throw new Error("Twitch account is disabled; enable it before using its OAuth grant");
|
|
129
|
+
const currentToken = normalizeToken(resolveTwitchToken(cfg, id).token);
|
|
130
|
+
if (!current || lineageOf(current, currentToken) !== lineage) throw new Error("Twitch OAuth account changed; retry with its current configuration");
|
|
131
|
+
};
|
|
132
|
+
assertCurrent();
|
|
133
|
+
const namespace = "oauth-" + id;
|
|
134
|
+
const key = runtime.state.resolveStateDir() + ":" + id + ":" + lineage;
|
|
135
|
+
const resolve = async (force = false) => {
|
|
136
|
+
assertCurrent();
|
|
137
|
+
let active = tasks.get(runtime);
|
|
138
|
+
if (!active) {
|
|
139
|
+
active = /* @__PURE__ */ new Map();
|
|
140
|
+
tasks.set(runtime, active);
|
|
141
|
+
}
|
|
142
|
+
const pending = active.get(key);
|
|
143
|
+
if (pending) return await pending;
|
|
144
|
+
const task = (async () => {
|
|
145
|
+
const store = runtime.state.openKeyedStoreV2({
|
|
146
|
+
namespace,
|
|
147
|
+
maxEntries: 1,
|
|
148
|
+
overflowPolicy: "reject-new"
|
|
149
|
+
}, { assertCurrent });
|
|
150
|
+
let observed = await store.observe("current");
|
|
151
|
+
if (observed.value?.lineage !== lineage) {
|
|
152
|
+
const initialized = await store.compareAndApply("current", observed.comparison, {
|
|
153
|
+
operation: "update",
|
|
154
|
+
action: "set",
|
|
155
|
+
value: {
|
|
156
|
+
lineage,
|
|
157
|
+
token: {
|
|
158
|
+
accessToken: token,
|
|
159
|
+
refreshToken: account.refreshToken ?? null,
|
|
160
|
+
expiresIn: account.expiresIn ?? null,
|
|
161
|
+
obtainmentTimestamp: account.obtainmentTimestamp ?? Date.now(),
|
|
162
|
+
scope: []
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
observed = initialized.status === "conflict" ? initialized.current : await store.observe("current");
|
|
167
|
+
}
|
|
168
|
+
const validateCompleted = async (claim) => {
|
|
169
|
+
assertCurrent();
|
|
170
|
+
const info = await getTokenInfo(claim.completed.accessToken, clientId);
|
|
171
|
+
assertCurrent();
|
|
172
|
+
const current = await store.observe("current");
|
|
173
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before validation");
|
|
174
|
+
if (!info.userId || info.userName?.toLowerCase() !== account.username.toLowerCase() || claim.expectedUserId && info.userId !== claim.expectedUserId) {
|
|
175
|
+
await store.compareAndApply("current", current.comparison, {
|
|
176
|
+
operation: "update",
|
|
177
|
+
action: "set",
|
|
178
|
+
value: {
|
|
179
|
+
lineage,
|
|
180
|
+
claim: claim.claim
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
throw new Error("Twitch OAuth refresh returned a different account; reauthorize the configured grant");
|
|
184
|
+
}
|
|
185
|
+
const replacement = {
|
|
186
|
+
...claim.completed,
|
|
187
|
+
userId: info.userId
|
|
188
|
+
};
|
|
189
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
190
|
+
operation: "update",
|
|
191
|
+
action: "set",
|
|
192
|
+
value: {
|
|
193
|
+
lineage,
|
|
194
|
+
token: replacement
|
|
195
|
+
}
|
|
196
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
197
|
+
assertCurrent();
|
|
198
|
+
return replacement;
|
|
199
|
+
};
|
|
200
|
+
if (observed.value?.lineage === lineage && "claim" in observed.value && observed.value.completed) return await validateCompleted({
|
|
201
|
+
...observed.value,
|
|
202
|
+
completed: observed.value.completed
|
|
203
|
+
});
|
|
204
|
+
assertCurrent();
|
|
205
|
+
if (!observed.value || observed.value.lineage !== lineage || !("token" in observed.value)) throw new Error("Twitch OAuth refresh is pending or its outcome is uncertain; reauthorize the configured grant");
|
|
206
|
+
const original = observed.value.token;
|
|
207
|
+
if (!force && !accessTokenIsExpired(original)) return original;
|
|
208
|
+
if (!original.refreshToken) throw new Error("Twitch OAuth refresh requires a refresh token");
|
|
209
|
+
const claim = {
|
|
210
|
+
lineage,
|
|
211
|
+
claim: randomUUID()
|
|
212
|
+
};
|
|
213
|
+
if ((await store.compareAndApply("current", observed.comparison, {
|
|
214
|
+
operation: "update",
|
|
215
|
+
action: "set",
|
|
216
|
+
value: claim
|
|
217
|
+
})).status !== "applied") throw new Error("Twitch OAuth grant changed before refresh; retry with its current owner");
|
|
218
|
+
const settle = async (replacement) => {
|
|
219
|
+
const current = await store.observe("current");
|
|
220
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
221
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
222
|
+
operation: "update",
|
|
223
|
+
action: "set",
|
|
224
|
+
value: {
|
|
225
|
+
lineage,
|
|
226
|
+
token: replacement
|
|
227
|
+
}
|
|
228
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before settlement");
|
|
229
|
+
assertCurrent();
|
|
230
|
+
};
|
|
231
|
+
assertCurrent();
|
|
232
|
+
let refreshed;
|
|
233
|
+
try {
|
|
234
|
+
refreshed = await exchange(account, original.refreshToken, assertCurrent);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (isRecoverableOAuthRefreshFailure(error)) await settle(original);
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
const completed = {
|
|
240
|
+
...claim,
|
|
241
|
+
completed: refreshed,
|
|
242
|
+
...original.userId ? { expectedUserId: original.userId } : {}
|
|
243
|
+
};
|
|
244
|
+
const current = await store.observe("current");
|
|
245
|
+
if (!isDeepStrictEqual(current.value, claim)) throw new Error("Twitch OAuth refresh owner changed before completion");
|
|
246
|
+
if ((await store.compareAndApply("current", current.comparison, {
|
|
247
|
+
operation: "update",
|
|
248
|
+
action: "set",
|
|
249
|
+
value: completed
|
|
250
|
+
})).status !== "applied") throw new Error("Twitch OAuth refresh owner changed before completion");
|
|
251
|
+
return await validateCompleted(completed);
|
|
252
|
+
})();
|
|
253
|
+
active.set(key, task);
|
|
254
|
+
try {
|
|
255
|
+
return await task;
|
|
256
|
+
} finally {
|
|
257
|
+
if (active.get(key) === task) active.delete(key);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
let grant = await resolve();
|
|
261
|
+
let staticProvider = new StaticAuthProvider(clientId, grant);
|
|
262
|
+
const prepare = async (force = false) => {
|
|
263
|
+
const current = await resolve(force);
|
|
264
|
+
if (current.accessToken !== grant.accessToken) staticProvider = new StaticAuthProvider(clientId, current);
|
|
265
|
+
grant = current;
|
|
266
|
+
assertCurrent();
|
|
267
|
+
return staticProvider;
|
|
268
|
+
};
|
|
269
|
+
return {
|
|
270
|
+
clientId,
|
|
271
|
+
hasClientSecret: true,
|
|
272
|
+
getCurrentScopesForUser: () => staticProvider.getCurrentScopesForUser(),
|
|
273
|
+
async getAccessTokenForUser(user, ...scopeSets) {
|
|
274
|
+
const result = await (await prepare()).getAccessTokenForUser(user, ...scopeSets);
|
|
275
|
+
assertCurrent();
|
|
276
|
+
return result;
|
|
277
|
+
},
|
|
278
|
+
async getAccessTokenForIntent(intent, ...scopeSets) {
|
|
279
|
+
if (intent !== "chat") return null;
|
|
280
|
+
const result = await (await prepare()).getAccessTokenForIntent(intent, ...scopeSets);
|
|
281
|
+
assertCurrent();
|
|
282
|
+
return result;
|
|
283
|
+
},
|
|
284
|
+
async getAnyAccessToken() {
|
|
285
|
+
const result = await (await prepare()).getAnyAccessToken();
|
|
286
|
+
assertCurrent();
|
|
287
|
+
return result;
|
|
288
|
+
},
|
|
289
|
+
async refreshAccessTokenForIntent(intent) {
|
|
290
|
+
if (intent !== "chat") throw new Error("Unknown Twitch OAuth intent");
|
|
291
|
+
const result = await (await prepare(true)).getAccessTokenForIntent(intent);
|
|
292
|
+
assertCurrent();
|
|
293
|
+
return result;
|
|
294
|
+
},
|
|
295
|
+
async refreshAccessTokenForUser(user) {
|
|
296
|
+
const result = await (await prepare(true)).getAccessTokenForUser(user);
|
|
297
|
+
assertCurrent();
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
38
302
|
//#endregion
|
|
39
303
|
//#region extensions/twitch/src/twitch-client.ts
|
|
40
|
-
const TWITCH_CHAT_AUTH_INTENTS = ["chat"];
|
|
41
304
|
var TwitchClientManager = class {
|
|
42
305
|
constructor(logger, statusSink) {
|
|
43
306
|
this.logger = logger;
|
|
44
307
|
this.statusSink = statusSink;
|
|
45
|
-
this.clients = /* @__PURE__ */ new Map();
|
|
46
|
-
this.pendingClients = /* @__PURE__ */ new Map();
|
|
47
|
-
this.connectionPromises = /* @__PURE__ */ new Map();
|
|
48
|
-
this.messageHandlers = /* @__PURE__ */ new Map();
|
|
49
308
|
}
|
|
50
309
|
setStatusSink(statusSink) {
|
|
51
310
|
if (statusSink) this.statusSink = statusSink;
|
|
@@ -60,64 +319,28 @@ var TwitchClientManager = class {
|
|
|
60
319
|
lastError
|
|
61
320
|
});
|
|
62
321
|
}
|
|
63
|
-
async createAuthProvider(account, normalizedToken, clientId) {
|
|
64
|
-
if (account.clientSecret) {
|
|
65
|
-
const authProvider = new RefreshingAuthProvider({
|
|
66
|
-
clientId,
|
|
67
|
-
clientSecret: account.clientSecret
|
|
68
|
-
});
|
|
69
|
-
try {
|
|
70
|
-
const userId = await authProvider.addUserForToken({
|
|
71
|
-
accessToken: normalizedToken,
|
|
72
|
-
refreshToken: account.refreshToken ?? null,
|
|
73
|
-
expiresIn: account.expiresIn ?? null,
|
|
74
|
-
obtainmentTimestamp: account.obtainmentTimestamp ?? Date.now()
|
|
75
|
-
}, TWITCH_CHAT_AUTH_INTENTS);
|
|
76
|
-
this.logger.info(`Added user ${userId} to RefreshingAuthProvider for ${account.username}`);
|
|
77
|
-
} catch (err) {
|
|
78
|
-
throw new Error(`Failed to add user to RefreshingAuthProvider: ${formatErrorMessage(err)}`, { cause: err });
|
|
79
|
-
}
|
|
80
|
-
authProvider.onRefresh((userId, token) => {
|
|
81
|
-
this.logger.info(`Access token refreshed for user ${userId} (expires in ${token.expiresIn ? `${token.expiresIn}s` : "unknown"})`);
|
|
82
|
-
});
|
|
83
|
-
authProvider.onRefreshFailure((userId, error) => {
|
|
84
|
-
this.logger.error(`Failed to refresh access token for user ${userId}: ${error.message}`);
|
|
85
|
-
});
|
|
86
|
-
const refreshStatus = account.refreshToken ? "automatic token refresh enabled" : "token refresh disabled (no refresh token)";
|
|
87
|
-
this.logger.info(`Using RefreshingAuthProvider for ${account.username} (${refreshStatus})`);
|
|
88
|
-
return authProvider;
|
|
89
|
-
}
|
|
90
|
-
this.logger.info(`Using StaticAuthProvider for ${account.username} (no clientSecret provided)`);
|
|
91
|
-
return new StaticAuthProvider(clientId, normalizedToken);
|
|
92
|
-
}
|
|
93
322
|
async getClient(account, cfg, accountId) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (pending) return pending;
|
|
99
|
-
const connection = this.createConnectedClient(key, account, () => this.connectionPromises.get(key) === connection, cfg, accountId);
|
|
100
|
-
this.connectionPromises.set(key, connection);
|
|
323
|
+
if (this.client) return this.client;
|
|
324
|
+
if (this.connectionPromise) return this.connectionPromise;
|
|
325
|
+
const connection = this.createConnectedClient(account, () => this.connectionPromise === connection, cfg, accountId);
|
|
326
|
+
this.connectionPromise = connection;
|
|
101
327
|
try {
|
|
102
328
|
return await connection;
|
|
103
329
|
} finally {
|
|
104
|
-
if (this.
|
|
330
|
+
if (this.connectionPromise === connection) this.connectionPromise = void 0;
|
|
105
331
|
}
|
|
106
332
|
}
|
|
107
|
-
async createConnectedClient(
|
|
108
|
-
const tokenResolution = resolveTwitchToken(cfg,
|
|
333
|
+
async createConnectedClient(account, ownsConnection, cfg, accountId) {
|
|
334
|
+
const tokenResolution = resolveTwitchToken(cfg, accountId);
|
|
109
335
|
if (!tokenResolution.token) {
|
|
110
336
|
const resolvedAccountId = accountId ?? DEFAULT_ACCOUNT_ID;
|
|
111
337
|
const tokenConfigPath = cfg?.channels?.twitch?.accounts ? `channels.twitch.accounts.${resolvedAccountId}.accessToken` : "channels.twitch.accessToken";
|
|
112
338
|
throw new Error(`Missing Twitch token for account ${resolvedAccountId} (set ${tokenConfigPath} or OPENCLAW_TWITCH_ACCESS_TOKEN for default)`);
|
|
113
339
|
}
|
|
114
|
-
|
|
115
|
-
if (!account.clientId) {
|
|
116
|
-
this.logger.error(`Missing Twitch client ID for account ${account.username}`);
|
|
117
|
-
throw new Error("Missing Twitch client ID");
|
|
118
|
-
}
|
|
340
|
+
if (!account.clientId) throw new Error(`Missing Twitch client ID for account ${account.username}`);
|
|
119
341
|
const normalizedToken = normalizeToken(tokenResolution.token);
|
|
120
|
-
const
|
|
342
|
+
const clientId = account.clientId;
|
|
343
|
+
const authProvider = await (account.clientSecret && account.refreshToken ? createManagedTwitchAuthProvider(account, normalizedToken, accountId) : new StaticAuthProvider(clientId, normalizedToken));
|
|
121
344
|
if (!ownsConnection()) throw new Error(`Twitch connection cancelled for ${account.username}`);
|
|
122
345
|
const client = new ChatClient({
|
|
123
346
|
authProvider,
|
|
@@ -144,87 +367,70 @@ var TwitchClientManager = class {
|
|
|
144
367
|
} }
|
|
145
368
|
}
|
|
146
369
|
});
|
|
147
|
-
this.
|
|
370
|
+
this.pendingClient = client;
|
|
148
371
|
try {
|
|
149
|
-
|
|
150
|
-
|
|
372
|
+
const connectTimeoutMs = 15e3;
|
|
373
|
+
await new Promise((resolve, reject) => {
|
|
374
|
+
let settled = false;
|
|
375
|
+
let authRetryPending = false;
|
|
376
|
+
const listeners = [];
|
|
377
|
+
const finish = (error) => {
|
|
378
|
+
if (settled) return;
|
|
379
|
+
settled = true;
|
|
380
|
+
clearTimeout(timeout);
|
|
381
|
+
for (const listener of listeners) listener.unbind();
|
|
382
|
+
if (error) {
|
|
383
|
+
try {
|
|
384
|
+
client.quit();
|
|
385
|
+
} catch {}
|
|
386
|
+
reject(error);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
resolve();
|
|
390
|
+
};
|
|
391
|
+
listeners.push(client.onAuthenticationSuccess(() => {
|
|
392
|
+
this.publishReady();
|
|
393
|
+
finish();
|
|
394
|
+
}), client.onAuthenticationFailure((text) => {
|
|
395
|
+
authRetryPending = true;
|
|
396
|
+
this.publishRecovering(text);
|
|
397
|
+
this.logger.warn(`Twitch authentication failed for ${account.username}; waiting for retry, disconnect, or timeout: ${text}`);
|
|
398
|
+
}), client.onDisconnect((manual, reason) => {
|
|
399
|
+
if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
|
|
400
|
+
if (authRetryPending && !manual) return;
|
|
401
|
+
finish(reason ?? /* @__PURE__ */ new Error(manual ? `Twitch connection cancelled for ${account.username}` : `Twitch disconnected before ready for ${account.username}`));
|
|
402
|
+
}));
|
|
403
|
+
const timeout = setTimeout(() => finish(/* @__PURE__ */ new Error(`Timed out connecting to Twitch as ${account.username}`)), connectTimeoutMs);
|
|
404
|
+
timeout.unref?.();
|
|
405
|
+
try {
|
|
406
|
+
client.connect();
|
|
407
|
+
} catch (error) {
|
|
408
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
if (this.pendingClient !== client) {
|
|
151
412
|
client.quit();
|
|
152
413
|
throw new Error(`Twitch connection cancelled for ${account.username}`);
|
|
153
414
|
}
|
|
154
415
|
} finally {
|
|
155
|
-
if (this.
|
|
416
|
+
if (this.pendingClient === client) this.pendingClient = void 0;
|
|
156
417
|
}
|
|
157
|
-
this.setupClientHandlers(client, account);
|
|
158
|
-
this.clients.set(key, client);
|
|
159
|
-
this.logger.info(`Connected to Twitch as ${account.username}`);
|
|
160
|
-
return client;
|
|
161
|
-
}
|
|
162
|
-
async connectClient(client, account) {
|
|
163
|
-
const connectTimeoutMs = 15e3;
|
|
164
|
-
await new Promise((resolve, reject) => {
|
|
165
|
-
let settled = false;
|
|
166
|
-
let authRetryPending = false;
|
|
167
|
-
const listeners = [];
|
|
168
|
-
const finish = (error) => {
|
|
169
|
-
if (settled) return;
|
|
170
|
-
settled = true;
|
|
171
|
-
clearTimeout(timeout);
|
|
172
|
-
for (const listener of listeners) listener.unbind();
|
|
173
|
-
if (error) {
|
|
174
|
-
try {
|
|
175
|
-
client.quit();
|
|
176
|
-
} catch {}
|
|
177
|
-
reject(error);
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
resolve();
|
|
181
|
-
};
|
|
182
|
-
listeners.push(client.onAuthenticationSuccess(() => {
|
|
183
|
-
this.publishReady();
|
|
184
|
-
finish();
|
|
185
|
-
}), client.onAuthenticationFailure((text) => {
|
|
186
|
-
authRetryPending = true;
|
|
187
|
-
this.publishRecovering(text);
|
|
188
|
-
this.logger.warn(`Twitch authentication failed for ${account.username}; waiting for retry, disconnect, or timeout: ${text}`);
|
|
189
|
-
}), client.onDisconnect((manual, reason) => {
|
|
190
|
-
if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
|
|
191
|
-
if (authRetryPending && !manual) {
|
|
192
|
-
this.logger.debug?.(`Twitch disconnected during auth retry for ${account.username}: ${formatErrorMessage(reason)}`);
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
finish(reason ?? /* @__PURE__ */ new Error(manual ? `Twitch connection cancelled for ${account.username}` : `Twitch disconnected before ready for ${account.username}`));
|
|
196
|
-
}));
|
|
197
|
-
const timeout = setTimeout(() => finish(/* @__PURE__ */ new Error(`Timed out connecting to Twitch as ${account.username}`)), connectTimeoutMs);
|
|
198
|
-
timeout.unref?.();
|
|
199
|
-
try {
|
|
200
|
-
client.connect();
|
|
201
|
-
} catch (error) {
|
|
202
|
-
finish(error instanceof Error ? error : new Error(String(error)));
|
|
203
|
-
}
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
setupClientHandlers(client, account) {
|
|
207
|
-
const key = this.getAccountKey(account);
|
|
208
418
|
client.onMessage((channelName, _user, messageText, msg) => {
|
|
209
|
-
const handler = this.
|
|
210
|
-
if (handler) {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
isSub: msg.userInfo.isSubscriber,
|
|
225
|
-
chatType: "group"
|
|
226
|
-
});
|
|
227
|
-
}
|
|
419
|
+
const handler = this.messageHandler?.handler;
|
|
420
|
+
if (handler) handler({
|
|
421
|
+
username: msg.userInfo.userName,
|
|
422
|
+
displayName: msg.userInfo.displayName,
|
|
423
|
+
userId: msg.userInfo.userId,
|
|
424
|
+
message: messageText,
|
|
425
|
+
channel: channelName,
|
|
426
|
+
id: msg.id,
|
|
427
|
+
timestamp: Date.now(),
|
|
428
|
+
isMod: msg.userInfo.isMod,
|
|
429
|
+
isOwner: msg.userInfo.isBroadcaster,
|
|
430
|
+
isVip: msg.userInfo.isVip,
|
|
431
|
+
isSub: msg.userInfo.isSubscriber,
|
|
432
|
+
chatType: "group"
|
|
433
|
+
});
|
|
228
434
|
});
|
|
229
435
|
client.onAuthenticationSuccess(() => this.publishReady());
|
|
230
436
|
client.onAuthenticationFailure((text) => {
|
|
@@ -233,40 +439,24 @@ var TwitchClientManager = class {
|
|
|
233
439
|
client.onDisconnect((manual, reason) => {
|
|
234
440
|
if (!manual) this.publishRecovering(reason ? formatErrorMessage(reason) : "Twitch connection lost");
|
|
235
441
|
});
|
|
236
|
-
this.
|
|
442
|
+
this.client = client;
|
|
443
|
+
this.logger.info(`Connected to Twitch as ${account.username}`);
|
|
444
|
+
return client;
|
|
237
445
|
}
|
|
238
|
-
onMessage(
|
|
239
|
-
const key = this.getAccountKey(account);
|
|
446
|
+
onMessage(handler) {
|
|
240
447
|
const registration = { handler };
|
|
241
|
-
this.
|
|
448
|
+
this.messageHandler = registration;
|
|
242
449
|
return () => {
|
|
243
|
-
if (this.
|
|
450
|
+
if (this.messageHandler === registration) this.messageHandler = void 0;
|
|
244
451
|
};
|
|
245
452
|
}
|
|
246
|
-
async disconnect(account) {
|
|
247
|
-
const key = this.getAccountKey(account);
|
|
248
|
-
const client = this.clients.get(key);
|
|
249
|
-
const pendingClient = this.pendingClients.get(key);
|
|
250
|
-
const pendingConnection = this.connectionPromises.delete(key);
|
|
251
|
-
if (pendingClient) {
|
|
252
|
-
pendingClient.quit();
|
|
253
|
-
this.pendingClients.delete(key);
|
|
254
|
-
}
|
|
255
|
-
if (client) {
|
|
256
|
-
client.quit();
|
|
257
|
-
this.clients.delete(key);
|
|
258
|
-
this.logger.info(`Disconnected ${key}`);
|
|
259
|
-
}
|
|
260
|
-
if (pendingConnection || pendingClient || client) this.messageHandlers.delete(key);
|
|
261
|
-
}
|
|
262
453
|
async disconnectAll() {
|
|
263
|
-
this.
|
|
264
|
-
this.
|
|
265
|
-
this.
|
|
266
|
-
this.
|
|
267
|
-
this.
|
|
268
|
-
this.
|
|
269
|
-
this.logger.info(" Disconnected all clients");
|
|
454
|
+
this.pendingClient?.quit();
|
|
455
|
+
this.client?.quit();
|
|
456
|
+
this.pendingClient = void 0;
|
|
457
|
+
this.connectionPromise = void 0;
|
|
458
|
+
this.client = void 0;
|
|
459
|
+
this.messageHandler = void 0;
|
|
270
460
|
}
|
|
271
461
|
async sendMessage(account, channel, message, cfg, accountId) {
|
|
272
462
|
const effect = captureEffectAuthority();
|
|
@@ -294,17 +484,12 @@ var TwitchClientManager = class {
|
|
|
294
484
|
};
|
|
295
485
|
} catch (error) {
|
|
296
486
|
if (preparingUse || isChannelPartialDeliveryError(error)) throw error;
|
|
297
|
-
const errorMessage = formatErrorMessage(error);
|
|
298
|
-
this.logger.error(`Failed to send message: ${errorMessage}`);
|
|
299
487
|
return {
|
|
300
488
|
ok: false,
|
|
301
|
-
error:
|
|
489
|
+
error: formatErrorMessage(error)
|
|
302
490
|
};
|
|
303
491
|
}
|
|
304
492
|
}
|
|
305
|
-
getAccountKey(account) {
|
|
306
|
-
return `${account.username}:${account.channel}`;
|
|
307
|
-
}
|
|
308
493
|
};
|
|
309
494
|
//#endregion
|
|
310
495
|
//#region extensions/twitch/src/client-manager-registry.ts
|
|
@@ -312,29 +497,21 @@ const registry = /* @__PURE__ */ new Map();
|
|
|
312
497
|
function getOrCreateClientManager(accountId, logger, statusSink) {
|
|
313
498
|
const existing = registry.get(accountId);
|
|
314
499
|
if (existing) {
|
|
315
|
-
existing.
|
|
316
|
-
return existing
|
|
500
|
+
existing.setStatusSink(statusSink);
|
|
501
|
+
return existing;
|
|
317
502
|
}
|
|
318
503
|
const manager = new TwitchClientManager(logger, statusSink);
|
|
319
|
-
registry.set(accountId,
|
|
320
|
-
manager,
|
|
321
|
-
logger
|
|
322
|
-
});
|
|
323
|
-
logger.info(`Registered client manager for account: ${accountId}`);
|
|
504
|
+
registry.set(accountId, manager);
|
|
324
505
|
return manager;
|
|
325
506
|
}
|
|
326
507
|
function getClientManager(accountId) {
|
|
327
|
-
return registry.get(accountId)
|
|
508
|
+
return registry.get(accountId);
|
|
328
509
|
}
|
|
329
510
|
async function removeClientManager(accountId) {
|
|
330
|
-
const
|
|
331
|
-
if (!
|
|
511
|
+
const manager = registry.get(accountId);
|
|
512
|
+
if (!manager) return;
|
|
332
513
|
registry.delete(accountId);
|
|
333
|
-
|
|
334
|
-
await entry.manager.disconnectAll();
|
|
335
|
-
} finally {
|
|
336
|
-
entry.logger.info(`Unregistered client manager for account: ${accountId}`);
|
|
337
|
-
}
|
|
514
|
+
await manager.disconnectAll();
|
|
338
515
|
}
|
|
339
516
|
//#endregion
|
|
340
517
|
//#region extensions/twitch/src/config-schema.ts
|
|
@@ -496,7 +673,6 @@ const twitchOutbound = {
|
|
|
496
673
|
},
|
|
497
674
|
sendMedia: async (params) => {
|
|
498
675
|
const { text, mediaUrl } = params;
|
|
499
|
-
if (params.signal?.aborted) throw new Error("Outbound delivery aborted");
|
|
500
676
|
const message = mediaUrl ? `${text || ""} ${mediaUrl}`.trim() : text;
|
|
501
677
|
return twitchOutbound.sendText({
|
|
502
678
|
...params,
|
|
@@ -509,79 +685,21 @@ const twitchMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
|
509
685
|
outbound: twitchOutbound
|
|
510
686
|
});
|
|
511
687
|
//#endregion
|
|
512
|
-
//#region extensions/twitch/src/probe.ts
|
|
513
|
-
async function probeTwitch(account, timeoutMs) {
|
|
514
|
-
let client;
|
|
515
|
-
try {
|
|
516
|
-
return await runChannelProbe(void 0, async () => {
|
|
517
|
-
if (!account.accessToken || !account.username) return {
|
|
518
|
-
ok: false,
|
|
519
|
-
error: "missing credentials (accessToken, username)",
|
|
520
|
-
username: account.username
|
|
521
|
-
};
|
|
522
|
-
const rawToken = normalizeToken(account.accessToken.trim());
|
|
523
|
-
const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
|
|
524
|
-
const probeClient = new ChatClient({ authProvider });
|
|
525
|
-
client = probeClient;
|
|
526
|
-
const connectionPromise = new Promise((resolve, reject) => {
|
|
527
|
-
let settled = false;
|
|
528
|
-
const cleanup = () => {
|
|
529
|
-
if (settled) return;
|
|
530
|
-
settled = true;
|
|
531
|
-
connectListener.unbind();
|
|
532
|
-
disconnectListener.unbind();
|
|
533
|
-
authFailListener.unbind();
|
|
534
|
-
};
|
|
535
|
-
const connectListener = probeClient.onConnect(() => {
|
|
536
|
-
cleanup();
|
|
537
|
-
resolve();
|
|
538
|
-
});
|
|
539
|
-
const disconnectListener = probeClient.onDisconnect((_manually, reason) => {
|
|
540
|
-
cleanup();
|
|
541
|
-
reject(reason || /* @__PURE__ */ new Error("Disconnected"));
|
|
542
|
-
});
|
|
543
|
-
const authFailListener = probeClient.onAuthenticationFailure(() => {
|
|
544
|
-
cleanup();
|
|
545
|
-
reject(/* @__PURE__ */ new Error("Authentication failed"));
|
|
546
|
-
});
|
|
547
|
-
});
|
|
548
|
-
await raceWithTimeout(() => {
|
|
549
|
-
probeClient.connect();
|
|
550
|
-
return connectionPromise;
|
|
551
|
-
}, timeoutMs, () => {
|
|
552
|
-
throw new Error(`timeout after ${timeoutMs}ms`);
|
|
553
|
-
});
|
|
554
|
-
client.quit();
|
|
555
|
-
client = void 0;
|
|
556
|
-
return {
|
|
557
|
-
ok: true,
|
|
558
|
-
connected: true,
|
|
559
|
-
username: account.username,
|
|
560
|
-
channel: account.channel
|
|
561
|
-
};
|
|
562
|
-
}, (error) => ({
|
|
563
|
-
ok: false,
|
|
564
|
-
error: formatErrorMessage(error),
|
|
565
|
-
username: account.username,
|
|
566
|
-
channel: account.channel
|
|
567
|
-
}));
|
|
568
|
-
} finally {
|
|
569
|
-
if (client) try {
|
|
570
|
-
client.quit();
|
|
571
|
-
} catch {}
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
//#endregion
|
|
575
688
|
//#region extensions/twitch/src/resolver.ts
|
|
576
689
|
const TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS = 1e4;
|
|
577
|
-
function
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
690
|
+
async function resolveTwitchTargets(inputs, account, _kind, log) {
|
|
691
|
+
if (!account.clientId || !account.accessToken) {
|
|
692
|
+
log?.error("Missing Twitch client ID or accessToken");
|
|
693
|
+
return inputs.map((input) => ({
|
|
694
|
+
input,
|
|
695
|
+
resolved: false,
|
|
696
|
+
note: "missing Twitch credentials"
|
|
697
|
+
}));
|
|
698
|
+
}
|
|
699
|
+
const normalizedToken = normalizeToken(account.accessToken);
|
|
700
|
+
const clientId = account.clientId;
|
|
583
701
|
let tokenValidated = false;
|
|
584
|
-
|
|
702
|
+
async function resolveHelixUser(query) {
|
|
585
703
|
const controller = new AbortController();
|
|
586
704
|
const fetchOptions = { signal: controller.signal };
|
|
587
705
|
const request = (async () => {
|
|
@@ -591,7 +709,7 @@ function createHelixUserResolver(clientId, accessToken) {
|
|
|
591
709
|
tokenInfo = await callTwitchApi({
|
|
592
710
|
type: "auth",
|
|
593
711
|
url: "validate"
|
|
594
|
-
}, clientId,
|
|
712
|
+
}, clientId, normalizedToken, void 0, fetchOptions);
|
|
595
713
|
} catch (error) {
|
|
596
714
|
if (error instanceof HttpStatusCodeError && error.statusCode === 401) throw new Error("Invalid token supplied", { cause: error });
|
|
597
715
|
throw error;
|
|
@@ -603,29 +721,18 @@ function createHelixUserResolver(clientId, accessToken) {
|
|
|
603
721
|
type: "helix",
|
|
604
722
|
url: "users",
|
|
605
723
|
query
|
|
606
|
-
}, clientId,
|
|
724
|
+
}, clientId, normalizedToken, void 0, fetchOptions)).data[0] ?? null;
|
|
607
725
|
})();
|
|
608
726
|
try {
|
|
609
727
|
return await withTimeout(request, TWITCH_HELIX_USER_LOOKUP_TIMEOUT_MS, "Twitch Helix user lookup");
|
|
610
728
|
} finally {
|
|
611
729
|
controller.abort();
|
|
612
730
|
}
|
|
613
|
-
};
|
|
614
|
-
}
|
|
615
|
-
async function resolveTwitchTargets(inputs, account, _kind, log) {
|
|
616
|
-
if (!account.clientId || !account.accessToken) {
|
|
617
|
-
log?.error("Missing Twitch client ID or accessToken");
|
|
618
|
-
return inputs.map((input) => ({
|
|
619
|
-
input,
|
|
620
|
-
resolved: false,
|
|
621
|
-
note: "missing Twitch credentials"
|
|
622
|
-
}));
|
|
623
731
|
}
|
|
624
|
-
const normalizedToken = normalizeToken(account.accessToken);
|
|
625
|
-
const resolveHelixUser = createHelixUserResolver(account.clientId, normalizedToken);
|
|
626
732
|
const results = [];
|
|
627
733
|
for (const input of inputs) {
|
|
628
|
-
const
|
|
734
|
+
const trimmed = input.trim();
|
|
735
|
+
const normalized = normalizeLowercaseStringOrEmpty(trimmed.startsWith("@") ? trimmed.slice(1) : trimmed);
|
|
629
736
|
if (!normalized) {
|
|
630
737
|
results.push({
|
|
631
738
|
input,
|
|
@@ -667,61 +774,10 @@ async function resolveTwitchTargets(inputs, account, _kind, log) {
|
|
|
667
774
|
return results;
|
|
668
775
|
}
|
|
669
776
|
//#endregion
|
|
670
|
-
//#region extensions/twitch/src/status.ts
|
|
671
|
-
function collectTwitchStatusIssues(accounts) {
|
|
672
|
-
const issues = [];
|
|
673
|
-
for (const entry of accounts) {
|
|
674
|
-
const accountId = entry.accountId;
|
|
675
|
-
if (!accountId) continue;
|
|
676
|
-
if (!entry.configured) {
|
|
677
|
-
issues.push({
|
|
678
|
-
channel: "twitch",
|
|
679
|
-
accountId,
|
|
680
|
-
kind: "config",
|
|
681
|
-
message: "Twitch account is not properly configured",
|
|
682
|
-
fix: "Add required fields: username, accessToken, and clientId to your account configuration"
|
|
683
|
-
});
|
|
684
|
-
continue;
|
|
685
|
-
}
|
|
686
|
-
if (entry.enabled === false) {
|
|
687
|
-
issues.push({
|
|
688
|
-
channel: "twitch",
|
|
689
|
-
accountId,
|
|
690
|
-
kind: "config",
|
|
691
|
-
message: "Twitch account is disabled",
|
|
692
|
-
fix: "Set enabled: true in your account configuration to enable this account"
|
|
693
|
-
});
|
|
694
|
-
continue;
|
|
695
|
-
}
|
|
696
|
-
if (entry.lastError) issues.push({
|
|
697
|
-
channel: "twitch",
|
|
698
|
-
accountId,
|
|
699
|
-
kind: "runtime",
|
|
700
|
-
message: `Last error: ${entry.lastError}`,
|
|
701
|
-
fix: "Check your token validity and network connection. Check that the bot has the required OAuth scopes."
|
|
702
|
-
});
|
|
703
|
-
if (!entry.running && !entry.lastStartAt && !entry.lastInboundAt && !entry.lastOutboundAt) issues.push({
|
|
704
|
-
channel: "twitch",
|
|
705
|
-
accountId,
|
|
706
|
-
kind: "runtime",
|
|
707
|
-
message: "Account has never connected successfully",
|
|
708
|
-
fix: "Start the Twitch gateway to begin receiving messages. Check logs for connection errors."
|
|
709
|
-
});
|
|
710
|
-
if (entry.running && entry.lastStartAt) {
|
|
711
|
-
const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
|
|
712
|
-
if (daysSinceStart > 7) issues.push({
|
|
713
|
-
channel: "twitch",
|
|
714
|
-
accountId,
|
|
715
|
-
kind: "runtime",
|
|
716
|
-
message: `Connection has been running for ${Math.floor(daysSinceStart)} days`,
|
|
717
|
-
fix: "Consider restarting the connection periodically to refresh the connection. Twitch tokens may expire after long periods."
|
|
718
|
-
});
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
return issues;
|
|
722
|
-
}
|
|
723
|
-
//#endregion
|
|
724
777
|
//#region extensions/twitch/src/plugin.ts
|
|
778
|
+
function readSendValue(value) {
|
|
779
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value).trim() : void 0;
|
|
780
|
+
}
|
|
725
781
|
const twitchPlugin = createChatChannelPlugin({
|
|
726
782
|
pairing: {
|
|
727
783
|
idLabel: "twitchUserId",
|
|
@@ -786,7 +842,18 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
786
842
|
configured: false
|
|
787
843
|
}
|
|
788
844
|
},
|
|
789
|
-
actions:
|
|
845
|
+
actions: {
|
|
846
|
+
describeMessageTool: () => ({ actions: ["send"] }),
|
|
847
|
+
supportsAction: ({ action }) => action === "send",
|
|
848
|
+
extractToolSend: ({ args }) => {
|
|
849
|
+
const to = readSendValue(args.to);
|
|
850
|
+
const message = readSendValue(args.message);
|
|
851
|
+
return to && message ? {
|
|
852
|
+
to,
|
|
853
|
+
message
|
|
854
|
+
} : null;
|
|
855
|
+
}
|
|
856
|
+
},
|
|
790
857
|
resolver: { resolveTargets: async ({ cfg, accountId, inputs, kind, runtime }) => {
|
|
791
858
|
const account = getAccountConfig(cfg, accountId ?? resolveDefaultTwitchAccountId(cfg));
|
|
792
859
|
if (!account) return inputs.map((input) => ({
|
|
@@ -804,8 +871,96 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
804
871
|
status: createComputedAccountStatusAdapter({
|
|
805
872
|
defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$1),
|
|
806
873
|
buildChannelSummary: ({ snapshot }) => buildPassiveProbedChannelStatusSummary(snapshot),
|
|
807
|
-
probeAccount: async ({ account, timeoutMs }) =>
|
|
808
|
-
|
|
874
|
+
probeAccount: async ({ account, timeoutMs }) => {
|
|
875
|
+
let client;
|
|
876
|
+
try {
|
|
877
|
+
return await runChannelProbe(void 0, async () => {
|
|
878
|
+
if (!account.accessToken || !account.username) return {
|
|
879
|
+
ok: false,
|
|
880
|
+
error: "missing credentials (accessToken, username)",
|
|
881
|
+
username: account.username
|
|
882
|
+
};
|
|
883
|
+
const rawToken = normalizeToken(account.accessToken.trim());
|
|
884
|
+
const authProvider = new StaticAuthProvider(account.clientId ?? "", rawToken);
|
|
885
|
+
const probeClient = new ChatClient({ authProvider });
|
|
886
|
+
client = probeClient;
|
|
887
|
+
const connectionPromise = new Promise((resolve, reject) => {
|
|
888
|
+
let settled = false;
|
|
889
|
+
const cleanup = () => {
|
|
890
|
+
if (settled) return;
|
|
891
|
+
settled = true;
|
|
892
|
+
authSuccessListener.unbind();
|
|
893
|
+
disconnectListener.unbind();
|
|
894
|
+
authFailListener.unbind();
|
|
895
|
+
};
|
|
896
|
+
const authSuccessListener = probeClient.onAuthenticationSuccess(() => {
|
|
897
|
+
cleanup();
|
|
898
|
+
resolve();
|
|
899
|
+
});
|
|
900
|
+
const disconnectListener = probeClient.onDisconnect((_manually, reason) => {
|
|
901
|
+
cleanup();
|
|
902
|
+
reject(reason || /* @__PURE__ */ new Error("Disconnected"));
|
|
903
|
+
});
|
|
904
|
+
const authFailListener = probeClient.onAuthenticationFailure(() => {
|
|
905
|
+
cleanup();
|
|
906
|
+
reject(/* @__PURE__ */ new Error("Authentication failed"));
|
|
907
|
+
});
|
|
908
|
+
});
|
|
909
|
+
await raceWithTimeout(() => {
|
|
910
|
+
probeClient.connect();
|
|
911
|
+
return connectionPromise;
|
|
912
|
+
}, timeoutMs, () => {
|
|
913
|
+
throw new Error(`timeout after ${timeoutMs}ms`);
|
|
914
|
+
});
|
|
915
|
+
client.quit();
|
|
916
|
+
client = void 0;
|
|
917
|
+
return {
|
|
918
|
+
ok: true,
|
|
919
|
+
connected: true,
|
|
920
|
+
username: account.username,
|
|
921
|
+
channel: account.channel
|
|
922
|
+
};
|
|
923
|
+
}, (error) => ({
|
|
924
|
+
ok: false,
|
|
925
|
+
error: formatErrorMessage(error),
|
|
926
|
+
username: account.username,
|
|
927
|
+
channel: account.channel
|
|
928
|
+
}));
|
|
929
|
+
} finally {
|
|
930
|
+
if (client) try {
|
|
931
|
+
client.quit();
|
|
932
|
+
} catch {}
|
|
933
|
+
}
|
|
934
|
+
},
|
|
935
|
+
collectStatusIssues: (accounts) => {
|
|
936
|
+
const issues = [];
|
|
937
|
+
for (const entry of accounts) {
|
|
938
|
+
const accountId = entry.accountId;
|
|
939
|
+
if (!accountId) continue;
|
|
940
|
+
const addIssue = (kind, message, fix) => issues.push({
|
|
941
|
+
channel: "twitch",
|
|
942
|
+
accountId,
|
|
943
|
+
kind,
|
|
944
|
+
message,
|
|
945
|
+
fix
|
|
946
|
+
});
|
|
947
|
+
if (!entry.configured) {
|
|
948
|
+
addIssue("config", "Twitch account is not properly configured", "Add required fields: username, accessToken, and clientId to your account configuration");
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
if (entry.enabled === false) {
|
|
952
|
+
addIssue("config", "Twitch account is disabled", "Set enabled: true in your account configuration to enable this account");
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
if (entry.lastError) addIssue("runtime", `Last error: ${entry.lastError}`, "Check your token validity and network connection. Check that the bot has the required OAuth scopes.");
|
|
956
|
+
if (!entry.running && !entry.lastStartAt && !entry.lastInboundAt && !entry.lastOutboundAt) addIssue("runtime", "Account has never connected successfully", "Start the Twitch gateway to begin receiving messages. Check logs for connection errors.");
|
|
957
|
+
if (entry.running && entry.lastStartAt) {
|
|
958
|
+
const daysSinceStart = (Date.now() - entry.lastStartAt) / 864e5;
|
|
959
|
+
if (daysSinceStart > 7) addIssue("runtime", `Connection has been running for ${Math.floor(daysSinceStart)} days`, "Consider restarting the connection periodically to refresh the connection. Twitch tokens may expire after long periods.");
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return issues;
|
|
963
|
+
},
|
|
809
964
|
resolveAccountSnapshot: ({ account, cfg }) => {
|
|
810
965
|
const { configured } = resolveTwitchAccountContext(cfg, account.accountId);
|
|
811
966
|
return {
|
|
@@ -836,7 +991,7 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
836
991
|
await runPassiveAccountLifecycle({
|
|
837
992
|
abortSignal: ctx.abortSignal,
|
|
838
993
|
start: async () => {
|
|
839
|
-
const { monitorTwitchProvider } = await import("./monitor-
|
|
994
|
+
const { monitorTwitchProvider } = await import("./monitor-BStOwZKj.mjs");
|
|
840
995
|
return monitorTwitchProvider({
|
|
841
996
|
account,
|
|
842
997
|
accountId,
|
|
@@ -875,4 +1030,4 @@ const twitchPlugin = createChatChannelPlugin({
|
|
|
875
1030
|
}
|
|
876
1031
|
});
|
|
877
1032
|
//#endregion
|
|
878
|
-
export { sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };
|
|
1033
|
+
export { setTwitchRuntime as a, getTwitchRuntime as i, sendMessageTwitchInternal as n, getOrCreateClientManager as r, twitchPlugin as t };
|