matimo-examples 0.1.0-alpha.7

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.
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ============================================================================
4
+ * SLACK TOOLS - DECORATOR PATTERN EXAMPLE
5
+ * ============================================================================
6
+ *
7
+ * PATTERN: Decorator Pattern with @tool
8
+ * ─────────────────────────────────────────────────────────────────────────
9
+ * Uses TypeScript @tool decorators to wrap Slack tool calls in a class.
10
+ *
11
+ * Use this pattern when:
12
+ * ✅ Building class-based applications
13
+ * ✅ Encapsulating tool logic in services
14
+ * ✅ Adding custom methods that combine multiple tools
15
+ * ✅ Need reusable tool wrappers
16
+ * ✅ Object-oriented design preferred
17
+ *
18
+ * SETUP:
19
+ * ─────────────────────────────────────────────────────────────────────────
20
+ * 1. Create .env file:
21
+ * SLACK_BOT_TOKEN=xoxb-xxxxxxxxxxxxx
22
+ *
23
+ * 2. Same scopes as factory pattern
24
+ *
25
+ * USAGE:
26
+ * ─────────────────────────────────────────────────────────────────────────
27
+ * export SLACK_BOT_TOKEN=your_token_here
28
+ * npm run slack:decorator
29
+ *
30
+ * ============================================================================
31
+ */
32
+
33
+ import 'dotenv/config';
34
+ import path from 'path';
35
+ import { fileURLToPath } from 'url';
36
+ import { MatimoInstance, tool, setGlobalMatimoInstance } from 'matimo';
37
+
38
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
39
+
40
+ /**
41
+ * Decorator Pattern Agent - Uses @tool decorators for Slack operations
42
+ */
43
+ class SlackDecoratorPatternAgent {
44
+ constructor(private matimo: MatimoInstance) {}
45
+
46
+ /**
47
+ * Slack send-message tool - manually execute with only required parameters
48
+ */
49
+ async sendMessage(channel: string, text: string): Promise<unknown> {
50
+ // Manually execute to avoid sending undefined parameters
51
+ const result = await this.matimo.execute('slack-send-message', {
52
+ channel,
53
+ text,
54
+ });
55
+ return result;
56
+ }
57
+
58
+ /**
59
+ * Slack list-channels tool - automatically executes via @tool decorator
60
+ */
61
+ @tool('slack-list-channels')
62
+ async listChannels(types?: string, limit?: number): Promise<unknown> {
63
+ // Decorator automatically calls: matimo.execute('slack-list-channels', { types, limit })
64
+ return undefined;
65
+ }
66
+
67
+ /**
68
+ * Slack get-channel-history tool - automatically executes via @tool decorator
69
+ */
70
+ @tool('slack_get_channel_history')
71
+ async getChannelHistory(channel: string, limit?: number): Promise<unknown> {
72
+ // Decorator automatically calls: matimo.execute('slack_get_channel_history', { channel, limit })
73
+ return undefined;
74
+ }
75
+
76
+ /**
77
+ * Slack add-reaction tool - automatically executes via @tool decorator
78
+ */
79
+ @tool('slack_add_reaction')
80
+ async addReaction(channel: string, timestamp: string, name: string): Promise<unknown> {
81
+ // Decorator automatically calls: matimo.execute('slack_add_reaction', { channel, timestamp, name })
82
+ return undefined;
83
+ }
84
+
85
+ /**
86
+ * Slack create-channel tool - automatically executes via @tool decorator
87
+ */
88
+ @tool('slack_create_channel')
89
+ async createChannel(name: string, is_private?: boolean): Promise<unknown> {
90
+ // Decorator automatically calls: matimo.execute('slack_create_channel', { name, is_private })
91
+ return undefined;
92
+ }
93
+
94
+ /**
95
+ * Slack set-channel-topic tool - automatically executes via @tool decorator
96
+ */
97
+ @tool('slack_set_channel_topic')
98
+ async setChannelTopic(channel: string, topic: string): Promise<unknown> {
99
+ // Decorator automatically calls: matimo.execute('slack_set_channel_topic', { channel, topic })
100
+ return undefined;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Run decorator pattern examples
106
+ */
107
+ async function runDecoratorPatternExamples() {
108
+ const botToken = process.env.SLACK_BOT_TOKEN || 'xoxb-default-fake-token';
109
+
110
+ console.info('╔════════════════════════════════════════════════════════╗');
111
+ console.info('║ Slack Tools - Decorator Pattern ║');
112
+ console.info('║ (Uses @tool decorators for automatic execution) ║');
113
+ console.info('╚════════════════════════════════════════════════════════╝\n');
114
+
115
+ if (botToken === 'xoxb-default-fake-token') {
116
+ console.info('🔐 Warning: SLACK_BOT_TOKEN not set in environment');
117
+ console.info(' Set it: export SLACK_BOT_TOKEN="xoxb-xxxx"');
118
+ console.info(' Get one from: https://api.slack.com/apps\n');
119
+ }
120
+
121
+ console.info(`🤖 Slack Bot Token: ${botToken.substring(0, 10)}...\n`);
122
+
123
+ try {
124
+ // Initialize Matimo with auto-discovery
125
+ console.info('🚀 Initializing Matimo...');
126
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
127
+ setGlobalMatimoInstance(matimo);
128
+
129
+ const matimoTools = matimo.listTools();
130
+ const slackTools = matimoTools.filter((t) => t.name.startsWith('slack'));
131
+ console.info(`📦 Loaded ${matimoTools.length} total tools, ${slackTools.length} Slack tools\n`);
132
+
133
+ // Create agent
134
+ const agent = new SlackDecoratorPatternAgent(matimo);
135
+
136
+ console.info('🧪 Testing Slack Tools with Decorator Pattern');
137
+ console.info('═'.repeat(60) + '\n');
138
+
139
+ // Example 1: List channels
140
+ console.info('📋 Example 1: List Available Channels');
141
+ console.info('─'.repeat(60));
142
+ try {
143
+ const listResult = await agent.listChannels('public_channel,private_channel', 100);
144
+
145
+ const listData = (listResult as any).data || listResult;
146
+
147
+ if (listData.ok === true && listData.channels && Array.isArray(listData.channels)) {
148
+ const channels = listData.channels;
149
+ console.info(`✅ Found ${channels.length} channels:`);
150
+ channels.slice(0, 5).forEach((ch: any, idx: number) => {
151
+ console.info(` ${idx + 1}. #${ch.name} (ID: ${ch.id})`);
152
+ });
153
+ if (channels.length > 5) {
154
+ console.info(` ... and ${channels.length - 5} more`);
155
+ }
156
+
157
+ // Use first available channel for next examples
158
+ const firstChannel = channels[0];
159
+ console.info(`\n🎯 Using first channel: #${firstChannel.name} (${firstChannel.id})\n`);
160
+
161
+ // Example 2: Send message
162
+ console.info('💬 Example 2: Send Message to Channel');
163
+ console.info('─'.repeat(60));
164
+ try {
165
+ const sendResult = await agent.sendMessage(
166
+ firstChannel.id,
167
+ `👋 Hello from Matimo! Decorator pattern test at ${new Date().toISOString()}`
168
+ );
169
+
170
+ const sendData = (sendResult as any).data || sendResult;
171
+ if (sendData.ok === true) {
172
+ console.info('✅ Message sent successfully!');
173
+ if (sendData.ts) console.info(` Timestamp: ${sendData.ts}`);
174
+ if (sendData.channel) console.info(` Channel: ${sendData.channel}`);
175
+ } else {
176
+ console.info(`❌ Failed: ${sendData.error || 'Unknown error'}`);
177
+ }
178
+ } catch (error) {
179
+ console.info(`❌ Error: ${error instanceof Error ? error.message : String(error)}`);
180
+ }
181
+
182
+ // Example 3: Get channel history
183
+ console.info('\n📜 Example 3: Get Channel History');
184
+ console.info('─'.repeat(60));
185
+ try {
186
+ const historyResult = await agent.getChannelHistory(firstChannel.id, 5);
187
+
188
+ const historyData = (historyResult as any).data || historyResult;
189
+ if (
190
+ historyData.ok === true &&
191
+ historyData.messages &&
192
+ Array.isArray(historyData.messages)
193
+ ) {
194
+ console.info(
195
+ `✅ Retrieved ${historyData.messages.length} messages from #${firstChannel.name}`
196
+ );
197
+ historyData.messages.slice(0, 3).forEach((msg: any, idx: number) => {
198
+ console.info(` ${idx + 1}. "${msg.text?.substring(0, 50)}..." (${msg.ts})`);
199
+ });
200
+ } else {
201
+ console.info(`❌ Failed: ${historyData.error || 'No messages found'}`);
202
+ }
203
+ } catch (error) {
204
+ console.info(`❌ Error: ${error instanceof Error ? error.message : String(error)}`);
205
+ }
206
+
207
+ // Example 4: Set channel topic
208
+ console.info('\n🏷️ Example 4: Set Channel Topic');
209
+ console.info('─'.repeat(60));
210
+ try {
211
+ const topicResult = await agent.setChannelTopic(
212
+ firstChannel.id,
213
+ '🎯 Matimo Testing Channel - Decorator Pattern Example'
214
+ );
215
+
216
+ const topicData = (topicResult as any).data || topicResult;
217
+ if (topicData.ok === true) {
218
+ console.info('✅ Channel topic updated successfully!');
219
+ } else {
220
+ console.info(`❌ Failed: ${topicData.error || 'Unknown error'}`);
221
+ }
222
+ } catch (error) {
223
+ console.info(`❌ Error: ${error instanceof Error ? error.message : String(error)}`);
224
+ }
225
+ } else {
226
+ console.info(`❌ Failed to list channels: ${listData.error || 'Unknown error'}`);
227
+ }
228
+ } catch (error) {
229
+ console.info(`❌ Error: ${error instanceof Error ? error.message : String(error)}`);
230
+ }
231
+
232
+ console.info('\n' + '═'.repeat(60));
233
+ console.info('✨ Decorator Pattern Example Complete!');
234
+ console.info('═'.repeat(60) + '\n');
235
+ } catch (error) {
236
+ console.error('❌ Fatal error:', error instanceof Error ? error.message : String(error));
237
+ process.exit(1);
238
+ }
239
+ }
240
+
241
+ // Run the example
242
+ runDecoratorPatternExamples().catch((error) => {
243
+ console.error('❌ Unhandled error:', error);
244
+ process.exit(1);
245
+ });
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ============================================================================
4
+ * SLACK TOOLS - FACTORY PATTERN EXAMPLE
5
+ * ============================================================================
6
+ *
7
+ * PATTERN: SDK Factory Pattern
8
+ * ─────────────────────────────────────────────────────────────────────────
9
+ * Direct tool execution via MatimoInstance - the simplest way to use tools.
10
+ *
11
+ * Use this pattern when:
12
+ * ✅ Building simple scripts or CLI tools
13
+ * ✅ Direct API calls without abstraction
14
+ * ✅ Quick prototyping
15
+ * ✅ One-off tool execution
16
+ *
17
+ * SETUP:
18
+ * ─────────────────────────────────────────────────────────────────────────
19
+ * 1. Create .env file in project root:
20
+ * SLACK_BOT_TOKEN=xoxb-xxxxxxxxxxxx
21
+ *
22
+ * 2. Get a Slack bot token:
23
+ * - Go to: https://api.slack.com/apps
24
+ * - Create a new app or select existing
25
+ * - OAuth & Permissions → Install app to workspace
26
+ * - Copy "Bot User OAuth Token"
27
+ * - Required scopes: chat:write, channels:read, conversations:history
28
+ *
29
+ * USAGE:
30
+ * ─────────────────────────────────────────────────────────────────────────
31
+ * export SLACK_BOT_TOKEN=xoxb-xxxx
32
+ * npm run slack:factory -- --channel:C123456
33
+ *
34
+ * AVAILABLE TOOLS:
35
+ * ─────────────────────────────────────────────────────────────────────────
36
+ * 1. slack-send-message
37
+ * Parameters: channel (required), text (required), [blocks]
38
+ * Returns: Message timestamp and channel ID
39
+ * Example: Send a message to #general channel
40
+ *
41
+ * 2. slack-list-channels
42
+ * Parameters: [types], [limit], [cursor]
43
+ * Returns: List of channels, DMs, and groups
44
+ * Types: public_channel, private_channel, mpim, im
45
+ *
46
+ * 3. slack_create_channel
47
+ * Parameters: name (required), [is_private]
48
+ * Returns: Channel object with ID and name
49
+ * Example: Create a new public or private channel
50
+ *
51
+ * 4. slack_join_channel
52
+ * Parameters: channel (required)
53
+ * Returns: { ok: true/false }
54
+ * Example: Bot joins a public channel
55
+ *
56
+ * 5. slack_set_channel_topic
57
+ * Parameters: channel (required), topic (required)
58
+ * Returns: { ok: true/false, topic }
59
+ * Example: Set channel description/topic
60
+ *
61
+ * 6. slack_get_channel_history
62
+ * Parameters: channel (required), [limit], [oldest], [latest], [cursor]
63
+ * Returns: Messages array with pagination
64
+ * Example: Get recent messages from channel
65
+ *
66
+ * And more...
67
+ *
68
+ * ============================================================================
69
+ */
70
+
71
+ import 'dotenv/config';
72
+ import path from 'path';
73
+ import { fileURLToPath } from 'url';
74
+ import { MatimoInstance } from 'matimo';
75
+
76
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
77
+
78
+ /**
79
+ * Run factory pattern examples
80
+ */
81
+ async function runFactoryPatternExamples() {
82
+ // Parse CLI arguments
83
+ const args = process.argv.slice(2);
84
+ let channelId = process.env.SLACK_CHANNEL_ID || 'C0000000000';
85
+
86
+ for (const arg of args) {
87
+ if (arg.startsWith('--channel:')) {
88
+ channelId = arg.split(':')[1];
89
+ } else if (arg.startsWith('--channel=')) {
90
+ channelId = arg.split('=')[1];
91
+ }
92
+ }
93
+
94
+ console.info('\n╔════════════════════════════════════════════════════════╗');
95
+ console.info('║ Slack Tools - Factory Pattern ║');
96
+ console.info('║ (Direct execution - simplest approach) ║');
97
+ console.info('╚════════════════════════════════════════════════════════╝\n');
98
+
99
+ const botToken = process.env.SLACK_BOT_TOKEN;
100
+ if (!botToken) {
101
+ console.error('❌ Error: SLACK_BOT_TOKEN not set in .env');
102
+ console.info(' Set it: export SLACK_BOT_TOKEN="xoxb-xxxx"');
103
+ console.info(' Get one from: https://api.slack.com/apps');
104
+ process.exit(1);
105
+ }
106
+
107
+ console.info(`🤖 Bot Token: ${botToken.slice(0, 10)}...`);
108
+ console.info(`📍 Target Channel: ${channelId}\n`);
109
+
110
+ // Initialize Matimo with auto-discovery to find all @matimo/* packages
111
+ console.info('🚀 Initializing Matimo...');
112
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
113
+
114
+ const allTools = matimo.listTools();
115
+ console.info(`✅ Loaded ${allTools.length} tools\n`);
116
+
117
+ // Get Slack tools
118
+ const slackTools = allTools.filter((t) => t.name.startsWith('slack'));
119
+ console.info(`🔧 Found ${slackTools.length} Slack tools\n`);
120
+
121
+ // List available channels and use first one if default doesn't exist
122
+ console.info('📋 Finding an available channel...');
123
+ const listResult = await matimo.execute('slack-list-channels', {
124
+ limit: 10,
125
+ types: 'public_channel,private_channel',
126
+ });
127
+ const listData = (listResult as any).data || listResult;
128
+ let activeChannel = channelId;
129
+
130
+ if (listData.ok === true && listData.channels && listData.channels.length > 0) {
131
+ // Use first available channel if default is not found
132
+ const defaultChannelExists = listData.channels.some((ch: any) => ch.id === channelId);
133
+ if (!defaultChannelExists) {
134
+ activeChannel = listData.channels[0].id;
135
+ console.info(
136
+ ` Using first available channel: #${listData.channels[0].name} (${activeChannel})`
137
+ );
138
+ } else {
139
+ console.info(
140
+ ` Using specified channel: #${listData.channels.find((ch: any) => ch.id === channelId)?.name} (${channelId})`
141
+ );
142
+ }
143
+ } else {
144
+ console.info(` ⚠️ Could not list channels, using default: ${channelId}`);
145
+ }
146
+ console.info();
147
+
148
+ console.info('════════════════════════════════════════════════════════════\n');
149
+ console.info('Running Examples:');
150
+ console.info('════════════════════════════════════════════════════════════\n');
151
+
152
+ try {
153
+ // Example 1: Send a message
154
+ console.info('1️⃣ Sending message to channel...');
155
+ const sendResult = await matimo.execute('slack-send-message', {
156
+ channel: activeChannel,
157
+ text: `🤖 Factory Pattern test message at ${new Date().toISOString()}`,
158
+ });
159
+ // Slack API returns {ok: true/false, ...} or wrapped in data
160
+ const sendData = (sendResult as any).data || sendResult;
161
+ if (sendData.ok === true) {
162
+ console.info(' ✅ Message sent successfully');
163
+ console.info(` Channel: ${sendData.channel}`);
164
+ console.info(` Timestamp: ${sendData.ts}\n`);
165
+ } else {
166
+ console.info(` ❌ Failed: ${sendData.error || 'Unknown error'}`);
167
+ console.info(` Response: ${JSON.stringify(sendData)}\n`);
168
+ }
169
+
170
+ // Example 2: List channels
171
+ console.info('2️⃣ Listing channels...');
172
+ const listResult = await matimo.execute('slack-list-channels', {
173
+ limit: 5,
174
+ types: 'public_channel,private_channel',
175
+ });
176
+ const listData = (listResult as any).data || listResult;
177
+ if (listData.ok === true && listData.channels) {
178
+ const channels = listData.channels || [];
179
+ console.info(` ✅ Found ${channels.length} channels`);
180
+ channels.slice(0, 3).forEach((ch: any) => {
181
+ console.info(` • #${ch.name} (${ch.id})`);
182
+ });
183
+ console.info();
184
+ } else {
185
+ console.info(` ❌ Failed: ${listData.error || 'Unknown error'}`);
186
+ console.info(` Response: ${JSON.stringify(listData)}\n`);
187
+ }
188
+
189
+ // Example 3: Set channel topic
190
+ console.info('3️⃣ Setting channel topic...');
191
+ const topicResult = await matimo.execute('slack_set_channel_topic', {
192
+ channel: activeChannel,
193
+ topic: '🎯 Matimo Testing Channel - Factory Pattern Example',
194
+ });
195
+ const topicData = (topicResult as any).data || topicResult;
196
+ if (topicData.ok === true) {
197
+ console.info(' ✅ Topic set successfully\n');
198
+ } else {
199
+ console.info(` ❌ Failed: ${topicData.error || 'Unknown error'}`);
200
+ console.info(` Response: ${JSON.stringify(topicData)}\n`);
201
+ }
202
+
203
+ // Example 4: Get channel history
204
+ console.info('4️⃣ Retrieving channel history...');
205
+ const historyResult = await matimo.execute('slack_get_channel_history', {
206
+ channel: activeChannel,
207
+ limit: 5,
208
+ });
209
+ const historyData = (historyResult as any).data || historyResult;
210
+ if (historyData.ok === true && historyData.messages) {
211
+ console.info(` ✅ Retrieved ${historyData.messages.length} recent messages\n`);
212
+ } else {
213
+ console.info(` ❌ Failed: ${historyData.error || 'Unknown error'}`);
214
+ console.info(` Response: ${JSON.stringify(historyData)}\n`);
215
+ }
216
+ } catch (error) {
217
+ console.error('❌ Error:', error);
218
+ process.exit(1);
219
+ }
220
+
221
+ console.info('════════════════════════════════════════════════════════════');
222
+ console.info('✨ Factory Pattern Example Complete!');
223
+ console.info('════════════════════════════════════════════════════════════\n');
224
+ }
225
+
226
+ runFactoryPatternExamples().catch(console.error);