@kodelyth/twitch 2026.5.42 → 2026.6.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.
Files changed (45) hide show
  1. package/klaw.plugin.json +219 -2
  2. package/package.json +19 -2
  3. package/api.ts +0 -21
  4. package/channel-plugin-api.ts +0 -1
  5. package/index.test.ts +0 -13
  6. package/index.ts +0 -16
  7. package/runtime-api.ts +0 -22
  8. package/setup-entry.ts +0 -9
  9. package/setup-plugin-api.ts +0 -3
  10. package/src/access-control.test.ts +0 -373
  11. package/src/access-control.ts +0 -195
  12. package/src/actions.test.ts +0 -75
  13. package/src/actions.ts +0 -175
  14. package/src/client-manager-registry.ts +0 -87
  15. package/src/config-schema.test.ts +0 -46
  16. package/src/config-schema.ts +0 -88
  17. package/src/config.test.ts +0 -233
  18. package/src/config.ts +0 -177
  19. package/src/monitor.ts +0 -311
  20. package/src/outbound.test.ts +0 -572
  21. package/src/outbound.ts +0 -242
  22. package/src/plugin.lifecycle.test.ts +0 -86
  23. package/src/plugin.live.test.ts +0 -120
  24. package/src/plugin.test.ts +0 -77
  25. package/src/plugin.ts +0 -220
  26. package/src/probe.test.ts +0 -196
  27. package/src/probe.ts +0 -130
  28. package/src/resolver.ts +0 -139
  29. package/src/runtime.ts +0 -9
  30. package/src/send.test.ts +0 -342
  31. package/src/send.ts +0 -191
  32. package/src/setup-surface.test.ts +0 -529
  33. package/src/setup-surface.ts +0 -526
  34. package/src/status.test.ts +0 -298
  35. package/src/status.ts +0 -179
  36. package/src/test-fixtures.ts +0 -30
  37. package/src/token.test.ts +0 -198
  38. package/src/token.ts +0 -93
  39. package/src/twitch-client.test.ts +0 -574
  40. package/src/twitch-client.ts +0 -276
  41. package/src/types.ts +0 -104
  42. package/src/utils/markdown.ts +0 -98
  43. package/src/utils/twitch.ts +0 -81
  44. package/test/setup.ts +0 -7
  45. package/tsconfig.json +0 -16
package/src/actions.ts DELETED
@@ -1,175 +0,0 @@
1
- /**
2
- * Twitch message actions adapter.
3
- *
4
- * Handles tool-based actions for Twitch, such as sending messages.
5
- */
6
-
7
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
8
- import { resolveTwitchAccountContext } from "./config.js";
9
- import { twitchOutbound } from "./outbound.js";
10
- import type { ChannelMessageActionAdapter, ChannelMessageActionContext } from "./types.js";
11
-
12
- /**
13
- * Create a tool result with error content.
14
- */
15
- function errorResponse(error: string) {
16
- return {
17
- content: [
18
- {
19
- type: "text" as const,
20
- text: JSON.stringify({ ok: false, error }),
21
- },
22
- ],
23
- details: { ok: false },
24
- };
25
- }
26
-
27
- /**
28
- * Read a string parameter from action arguments.
29
- *
30
- * @param args - Action arguments
31
- * @param key - Parameter key
32
- * @param options - Options for reading the parameter
33
- * @returns The parameter value or undefined if not found
34
- */
35
- function readStringParam(
36
- args: Record<string, unknown>,
37
- key: string,
38
- options: { required?: boolean; trim?: boolean } = {},
39
- ): string | undefined {
40
- const value = args[key];
41
- if (value === undefined || value === null) {
42
- if (options.required) {
43
- throw new Error(`Missing required parameter: ${key}`);
44
- }
45
- return undefined;
46
- }
47
-
48
- // Convert value to string safely
49
- if (typeof value === "string") {
50
- return options.trim !== false ? value.trim() : value;
51
- }
52
-
53
- if (typeof value === "number" || typeof value === "boolean") {
54
- const str = String(value);
55
- return options.trim !== false ? str.trim() : str;
56
- }
57
-
58
- throw new Error(`Parameter ${key} must be a string, number, or boolean`);
59
- }
60
-
61
- /** Supported Twitch actions */
62
- const TWITCH_ACTIONS = new Set(["send" as const]);
63
- type TwitchAction = typeof TWITCH_ACTIONS extends Set<infer U> ? U : never;
64
-
65
- /**
66
- * Twitch message actions adapter.
67
- */
68
- export const twitchMessageActions: ChannelMessageActionAdapter = {
69
- /**
70
- * List available actions for this channel.
71
- */
72
- describeMessageTool: () => ({ actions: [...TWITCH_ACTIONS] }),
73
-
74
- /**
75
- * Check if an action is supported.
76
- */
77
- supportsAction: ({ action }) => TWITCH_ACTIONS.has(action as TwitchAction),
78
-
79
- /**
80
- * Extract tool send parameters from action arguments.
81
- *
82
- * Parses and validates the "to" and "message" parameters for sending.
83
- *
84
- * @param params - Arguments from the tool call
85
- * @returns Parsed send parameters or null if invalid
86
- *
87
- * @example
88
- * const result = twitchMessageActions.extractToolSend!({
89
- * args: { to: "#mychannel", message: "Hello!" }
90
- * });
91
- * // Returns: { to: "#mychannel", message: "Hello!" }
92
- */
93
- extractToolSend: ({ args }) => {
94
- try {
95
- const to = readStringParam(args, "to", { required: true });
96
- const message = readStringParam(args, "message", { required: true });
97
-
98
- if (!to || !message) {
99
- return null;
100
- }
101
-
102
- return { to, message };
103
- } catch {
104
- return null;
105
- }
106
- },
107
-
108
- /**
109
- * Handle an action execution.
110
- *
111
- * Processes the "send" action to send messages to Twitch.
112
- *
113
- * @param ctx - Action context including action type, parameters, and config
114
- * @returns Tool result with content or null if action not supported
115
- *
116
- * @example
117
- * const result = await twitchMessageActions.handleAction!({
118
- * action: "send",
119
- * params: { message: "Hello Twitch!", to: "#mychannel" },
120
- * cfg: klawConfig,
121
- * accountId: "default",
122
- * });
123
- */
124
- handleAction: async (ctx: ChannelMessageActionContext) => {
125
- if (ctx.action !== "send") {
126
- return {
127
- content: [{ type: "text" as const, text: "Unsupported action" }],
128
- details: { ok: false, error: "Unsupported action" },
129
- };
130
- }
131
-
132
- const message = readStringParam(ctx.params, "message", { required: true });
133
- const to = readStringParam(ctx.params, "to", { required: false });
134
- const accountId = ctx.accountId ?? resolveTwitchAccountContext(ctx.cfg).accountId;
135
-
136
- const { account, availableAccountIds } = resolveTwitchAccountContext(ctx.cfg, accountId);
137
- if (!account) {
138
- return errorResponse(
139
- `Account not found: ${accountId}. Available accounts: ${availableAccountIds.join(", ") || "none"}`,
140
- );
141
- }
142
-
143
- // Use the channel from account config (or override with `to` parameter)
144
- const targetChannel = to || account.channel;
145
- if (!targetChannel) {
146
- return errorResponse("No channel specified and no default channel in account config");
147
- }
148
-
149
- if (!twitchOutbound.sendText) {
150
- return errorResponse("sendText not implemented");
151
- }
152
-
153
- try {
154
- const result = await twitchOutbound.sendText({
155
- cfg: ctx.cfg,
156
- to: targetChannel,
157
- text: message ?? "",
158
- accountId,
159
- });
160
-
161
- return {
162
- content: [
163
- {
164
- type: "text" as const,
165
- text: JSON.stringify(result),
166
- },
167
- ],
168
- details: { ok: true },
169
- };
170
- } catch (error) {
171
- const errorMsg = formatErrorMessage(error);
172
- return errorResponse(errorMsg);
173
- }
174
- },
175
- };
@@ -1,87 +0,0 @@
1
- /**
2
- * Client manager registry for Twitch plugin.
3
- *
4
- * Manages the lifecycle of TwitchClientManager instances across the plugin,
5
- * ensuring proper cleanup when accounts are stopped or reconfigured.
6
- */
7
-
8
- import { TwitchClientManager } from "./twitch-client.js";
9
- import type { ChannelLogSink } from "./types.js";
10
-
11
- /**
12
- * Registry entry tracking a client manager and its associated account.
13
- */
14
- type RegistryEntry = {
15
- /** The client manager instance */
16
- manager: TwitchClientManager;
17
- /** The account ID this manager is for */
18
- accountId: string;
19
- /** Logger for this entry */
20
- logger: ChannelLogSink;
21
- /** When this entry was created */
22
- createdAt: number;
23
- };
24
-
25
- /**
26
- * Global registry of client managers.
27
- * Keyed by account ID.
28
- */
29
- const registry = new Map<string, RegistryEntry>();
30
-
31
- /**
32
- * Get or create a client manager for an account.
33
- *
34
- * @param accountId - The account ID
35
- * @param logger - Logger instance
36
- * @returns The client manager
37
- */
38
- export function getOrCreateClientManager(
39
- accountId: string,
40
- logger: ChannelLogSink,
41
- ): TwitchClientManager {
42
- const existing = registry.get(accountId);
43
- if (existing) {
44
- return existing.manager;
45
- }
46
-
47
- const manager = new TwitchClientManager(logger);
48
- registry.set(accountId, {
49
- manager,
50
- accountId,
51
- logger,
52
- createdAt: Date.now(),
53
- });
54
-
55
- logger.info(`Registered client manager for account: ${accountId}`);
56
- return manager;
57
- }
58
-
59
- /**
60
- * Get an existing client manager for an account.
61
- *
62
- * @param accountId - The account ID
63
- * @returns The client manager, or undefined if not registered
64
- */
65
- export function getClientManager(accountId: string): TwitchClientManager | undefined {
66
- return registry.get(accountId)?.manager;
67
- }
68
-
69
- /**
70
- * Disconnect and remove a client manager from the registry.
71
- *
72
- * @param accountId - The account ID
73
- * @returns Promise that resolves when cleanup is complete
74
- */
75
- export async function removeClientManager(accountId: string): Promise<void> {
76
- const entry = registry.get(accountId);
77
- if (!entry) {
78
- return;
79
- }
80
-
81
- // Disconnect the client manager
82
- await entry.manager.disconnectAll();
83
-
84
- // Remove from registry
85
- registry.delete(accountId);
86
- entry.logger.info(`Unregistered client manager for account: ${accountId}`);
87
- }
@@ -1,46 +0,0 @@
1
- import AjvPkg from "ajv";
2
- import { buildChannelConfigSchema } from "klaw/plugin-sdk/channel-config-schema";
3
- import { describe, expect, it } from "vitest";
4
- import { TwitchConfigSchema } from "./config-schema.js";
5
-
6
- function validateTwitchConfig(value: unknown): boolean {
7
- const Ajv = AjvPkg as unknown as new (opts?: object) => import("ajv").default;
8
- const schema = buildChannelConfigSchema(TwitchConfigSchema).schema;
9
- const validate = new Ajv({ allErrors: true, strict: false }).compile(schema);
10
- const ok = validate(value);
11
- if (!ok) {
12
- throw new Error(`expected valid Twitch config: ${JSON.stringify(validate.errors)}`);
13
- }
14
- return true;
15
- }
16
-
17
- describe("TwitchConfigSchema JSON schema", () => {
18
- it("accepts single-account channel config with base fields", () => {
19
- expect(
20
- validateTwitchConfig({
21
- enabled: false,
22
- username: "klaw",
23
- accessToken: "oauth:test",
24
- clientId: "test-client-id",
25
- channel: "klaw-test",
26
- }),
27
- ).toBe(true);
28
- });
29
-
30
- it("accepts multi-account channel config with defaultAccount", () => {
31
- expect(
32
- validateTwitchConfig({
33
- enabled: true,
34
- defaultAccount: "stream",
35
- accounts: {
36
- stream: {
37
- username: "klaw",
38
- accessToken: "oauth:test",
39
- clientId: "test-client-id",
40
- channel: "klaw-test",
41
- },
42
- },
43
- }),
44
- ).toBe(true);
45
- });
46
- });
@@ -1,88 +0,0 @@
1
- import { MarkdownConfigSchema } from "klaw/plugin-sdk/channel-config-primitives";
2
- import { z } from "zod";
3
-
4
- /**
5
- * Twitch user roles that can be allowed to interact with the bot
6
- */
7
- const TwitchRoleSchema = z.enum(["moderator", "owner", "vip", "subscriber", "all"]);
8
-
9
- const TwitchAccountShape = {
10
- /** Twitch username */
11
- username: z.string(),
12
- /** Twitch OAuth access token (requires chat:read and chat:write scopes) */
13
- accessToken: z.string(),
14
- /** Twitch client ID (from Twitch Developer Portal or twitchtokengenerator.com) */
15
- clientId: z.string().optional(),
16
- /** Channel name to join */
17
- channel: z.string().min(1),
18
- /** Enable this account */
19
- enabled: z.boolean().optional(),
20
- /** Allowlist of Twitch user IDs who can interact with the bot (use IDs for safety, not usernames) */
21
- allowFrom: z.array(z.string()).optional(),
22
- /** Roles allowed to interact with the bot (e.g., ["moderator", "vip", "subscriber"]) */
23
- allowedRoles: z.array(TwitchRoleSchema).optional(),
24
- /** Require @mention to trigger bot responses */
25
- requireMention: z.boolean().optional(),
26
- /** Outbound response prefix override for this channel/account. */
27
- responsePrefix: z.string().optional(),
28
- /** Twitch client secret (required for token refresh via RefreshingAuthProvider) */
29
- clientSecret: z.string().optional(),
30
- /** Refresh token (required for automatic token refresh) */
31
- refreshToken: z.string().optional(),
32
- /** Token expiry time in seconds (optional, for token refresh tracking) */
33
- expiresIn: z.number().nullable().optional(),
34
- /** Timestamp when token was obtained (optional, for token refresh tracking) */
35
- obtainmentTimestamp: z.number().optional(),
36
- };
37
-
38
- /**
39
- * Twitch account configuration schema
40
- */
41
- const TwitchAccountSchema = z.object(TwitchAccountShape);
42
-
43
- /**
44
- * Base configuration properties shared by both single and multi-account modes
45
- */
46
- const TwitchConfigBaseShape = {
47
- name: z.string().optional(),
48
- enabled: z.boolean().optional(),
49
- markdown: MarkdownConfigSchema.optional(),
50
- defaultAccount: z.string().optional(),
51
- };
52
-
53
- /**
54
- * Simplified single-account configuration schema
55
- *
56
- * Use this for single-account setups. Properties are at the top level,
57
- * creating an implicit "default" account.
58
- */
59
- const SimplifiedSchema = z.object({
60
- ...TwitchConfigBaseShape,
61
- ...TwitchAccountShape,
62
- });
63
-
64
- /**
65
- * Multi-account configuration schema
66
- *
67
- * Use this for multi-account setups. Each key is an account ID (e.g., "default", "secondary").
68
- */
69
- const MultiAccountSchema = z
70
- .object({
71
- ...TwitchConfigBaseShape,
72
- /** Per-account configuration (for multi-account setups) */
73
- accounts: z.record(z.string(), TwitchAccountSchema),
74
- })
75
- .refine((val) => Object.keys(val.accounts || {}).length > 0, {
76
- message: "accounts must contain at least one entry",
77
- });
78
-
79
- /**
80
- * Twitch plugin configuration schema
81
- *
82
- * Supports two mutually exclusive patterns:
83
- * 1. Simplified single-account: username, accessToken, clientId, channel at top level
84
- * 2. Multi-account: accounts object with named account configs
85
- *
86
- * The union ensures clear discrimination between the two modes.
87
- */
88
- export const TwitchConfigSchema = z.union([SimplifiedSchema, MultiAccountSchema]);
@@ -1,233 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- getAccountConfig,
4
- listAccountIds,
5
- resolveDefaultTwitchAccountId,
6
- resolveTwitchAccountContext,
7
- } from "./config.js";
8
-
9
- describe("getAccountConfig", () => {
10
- const mockMultiAccountConfig = {
11
- channels: {
12
- twitch: {
13
- accounts: {
14
- default: {
15
- username: "testbot",
16
- accessToken: "oauth:test123",
17
- },
18
- secondary: {
19
- username: "secondbot",
20
- accessToken: "oauth:secondary",
21
- },
22
- },
23
- },
24
- },
25
- };
26
-
27
- const mockSimplifiedConfig = {
28
- channels: {
29
- twitch: {
30
- username: "testbot",
31
- accessToken: "oauth:test123",
32
- },
33
- },
34
- };
35
-
36
- it("returns account config for valid account ID (multi-account)", () => {
37
- const result = getAccountConfig(mockMultiAccountConfig, "default");
38
-
39
- expect(result?.username).toBe("testbot");
40
- });
41
-
42
- it("returns account config for default account (simplified config)", () => {
43
- const result = getAccountConfig(mockSimplifiedConfig, "default");
44
-
45
- expect(result?.username).toBe("testbot");
46
- });
47
-
48
- it("returns non-default account from multi-account config", () => {
49
- const result = getAccountConfig(mockMultiAccountConfig, "secondary");
50
-
51
- expect(result?.username).toBe("secondbot");
52
- });
53
-
54
- it("normalizes account ids without reading inherited account properties", () => {
55
- const accounts = Object.create({
56
- inherited: {
57
- username: "inherited-bot",
58
- accessToken: "oauth:inherited",
59
- },
60
- }) as Record<string, unknown>;
61
- accounts.Secondary = {
62
- username: "secondbot",
63
- accessToken: "oauth:secondary",
64
- };
65
-
66
- const cfg = {
67
- channels: {
68
- twitch: {
69
- accounts,
70
- },
71
- },
72
- };
73
-
74
- expect(getAccountConfig(cfg, "SECONDARY\r\n")).toEqual({
75
- username: "secondbot",
76
- accessToken: "oauth:secondary",
77
- });
78
- expect(getAccountConfig(cfg, "inherited")).toBeNull();
79
- });
80
-
81
- it("returns null for non-existent account ID", () => {
82
- const result = getAccountConfig(mockMultiAccountConfig, "nonexistent");
83
-
84
- expect(result).toBeNull();
85
- });
86
-
87
- it("returns null when core config is null", () => {
88
- const result = getAccountConfig(null, "default");
89
-
90
- expect(result).toBeNull();
91
- });
92
-
93
- it("returns null when core config is undefined", () => {
94
- const result = getAccountConfig(undefined, "default");
95
-
96
- expect(result).toBeNull();
97
- });
98
-
99
- it("returns null when channels are not defined", () => {
100
- const result = getAccountConfig({}, "default");
101
-
102
- expect(result).toBeNull();
103
- });
104
-
105
- it("returns null when twitch is not defined", () => {
106
- const result = getAccountConfig({ channels: {} }, "default");
107
-
108
- expect(result).toBeNull();
109
- });
110
-
111
- it("returns null when accounts are not defined", () => {
112
- const result = getAccountConfig({ channels: { twitch: {} } }, "default");
113
-
114
- expect(result).toBeNull();
115
- });
116
- });
117
-
118
- describe("listAccountIds", () => {
119
- it("includes the implicit default account from simplified config", () => {
120
- expect(
121
- listAccountIds({
122
- channels: {
123
- twitch: {
124
- username: "testbot",
125
- accessToken: "oauth:test123",
126
- },
127
- },
128
- } as Parameters<typeof listAccountIds>[0]),
129
- ).toEqual(["default"]);
130
- });
131
-
132
- it("combines explicit accounts with the implicit default account once", () => {
133
- expect(
134
- listAccountIds({
135
- channels: {
136
- twitch: {
137
- username: "testbot",
138
- accounts: {
139
- default: { username: "testbot" },
140
- secondary: { username: "secondbot" },
141
- },
142
- },
143
- },
144
- } as Parameters<typeof listAccountIds>[0]),
145
- ).toEqual(["default", "secondary"]);
146
- });
147
-
148
- it("normalizes configured account ids", () => {
149
- expect(
150
- listAccountIds({
151
- channels: {
152
- twitch: {
153
- accounts: {
154
- Secondary: { username: "secondbot" },
155
- "Alerts\r\n\u001b[31m": { username: "alerts" },
156
- },
157
- },
158
- },
159
- } as Parameters<typeof listAccountIds>[0]),
160
- ).toEqual(["alerts-31m", "secondary"]);
161
- });
162
- });
163
-
164
- describe("resolveDefaultTwitchAccountId", () => {
165
- it("prefers channels.twitch.defaultAccount when configured", () => {
166
- expect(
167
- resolveDefaultTwitchAccountId({
168
- channels: {
169
- twitch: {
170
- defaultAccount: "secondary",
171
- accounts: {
172
- default: { username: "default" },
173
- secondary: { username: "secondary" },
174
- },
175
- },
176
- },
177
- } as Parameters<typeof resolveDefaultTwitchAccountId>[0]),
178
- ).toBe("secondary");
179
- });
180
- });
181
-
182
- describe("resolveTwitchAccountContext", () => {
183
- it("uses configured defaultAccount when accountId is omitted", () => {
184
- const context = resolveTwitchAccountContext({
185
- channels: {
186
- twitch: {
187
- defaultAccount: "secondary",
188
- accounts: {
189
- default: {
190
- username: "default-bot",
191
- accessToken: "oauth:default-token",
192
- },
193
- secondary: {
194
- username: "second-bot",
195
- accessToken: "oauth:second-token",
196
- },
197
- },
198
- },
199
- },
200
- } as Parameters<typeof resolveTwitchAccountContext>[0]);
201
-
202
- expect(context.accountId).toBe("secondary");
203
- expect(context.account?.username).toBe("second-bot");
204
- });
205
-
206
- it("keeps account and token lookup aligned after account id normalization", () => {
207
- const context = resolveTwitchAccountContext(
208
- {
209
- channels: {
210
- twitch: {
211
- accounts: {
212
- Secondary: {
213
- username: "second-bot",
214
- accessToken: "oauth:second-token",
215
- clientId: "second-client",
216
- channel: "#second",
217
- },
218
- },
219
- },
220
- },
221
- } as Parameters<typeof resolveTwitchAccountContext>[0],
222
- "secondary",
223
- );
224
-
225
- expect(context.accountId).toBe("secondary");
226
- expect(context.account?.username).toBe("second-bot");
227
- expect(context.tokenResolution).toEqual({
228
- token: "oauth:second-token",
229
- source: "config",
230
- });
231
- expect(context.configured).toBe(true);
232
- });
233
- });