@plosson/agentio 0.3.1 → 0.4.0

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,285 @@
1
+ import { Command } from 'commander';
2
+ import { google } from 'googleapis';
3
+ import { createGoogleAuth } from '../auth/token-manager';
4
+ import { setCredentials } from '../auth/token-store';
5
+ import { setProfile } from '../config/config-manager';
6
+ import { createProfileCommands } from '../utils/profile-commands';
7
+ import { createClientGetter } from '../utils/client-factory';
8
+ import { performOAuthFlow } from '../auth/oauth';
9
+ import { GDriveClient } from '../services/gdrive/client';
10
+ import { printGDriveFileList, printGDriveFile, printGDriveDownloaded, printGDriveUploaded } from '../utils/output';
11
+ import { CliError, handleError } from '../utils/errors';
12
+ import { prompt } from '../utils/stdin';
13
+ import type { GDriveCredentials, GDriveAccessLevel } from '../types/gdrive';
14
+
15
+ const getGDriveClient = createClientGetter<GDriveCredentials, GDriveClient>({
16
+ service: 'gdrive',
17
+ createClient: (credentials) => new GDriveClient(credentials),
18
+ });
19
+
20
+ export function registerGDriveCommands(program: Command): void {
21
+ const gdrive = program
22
+ .command('gdrive')
23
+ .description('Google Drive operations');
24
+
25
+ gdrive
26
+ .command('list')
27
+ .description('List files')
28
+ .option('--profile <name>', 'Profile name')
29
+ .option('--limit <n>', 'Number of files', '20')
30
+ .option('--folder <id>', 'Folder ID to list (use "root" for root folder)')
31
+ .option('--query <query>', 'Drive API query filter')
32
+ .option('--order <field>', 'Order by field', 'modifiedTime desc')
33
+ .option('--trash', 'Include trashed files')
34
+ .addHelpText('after', `
35
+ Query Syntax Examples:
36
+
37
+ Name search:
38
+ --query "name contains 'report'" Files with "report" in name
39
+ --query "name = 'Budget 2024.xlsx'" Exact name match
40
+
41
+ File type:
42
+ --query "mimeType = 'application/pdf'"
43
+ --query "mimeType contains 'image/'"
44
+
45
+ Ownership:
46
+ --query "'me' in owners" Files you own
47
+ --query "not 'me' in owners" Shared with you
48
+
49
+ Date filters:
50
+ --query "modifiedTime > '2024-01-01'"
51
+ --query "createdTime > '2024-01-01'"
52
+
53
+ Properties:
54
+ --query "starred = true" Starred files
55
+ --query "shared = true" Shared files
56
+
57
+ Combined:
58
+ --query "name contains 'report' and modifiedTime > '2024-01-01'"
59
+ `)
60
+ .action(async (options) => {
61
+ try {
62
+ const { client } = await getGDriveClient(options.profile);
63
+ const files = await client.list({
64
+ limit: parseInt(options.limit, 10),
65
+ folderId: options.folder,
66
+ query: options.query,
67
+ orderBy: options.order,
68
+ includeTrash: options.trash,
69
+ });
70
+ printGDriveFileList(files);
71
+ } catch (error) {
72
+ handleError(error);
73
+ }
74
+ });
75
+
76
+ gdrive
77
+ .command('folders')
78
+ .description('List folders')
79
+ .option('--profile <name>', 'Profile name')
80
+ .option('--limit <n>', 'Number of folders', '20')
81
+ .option('--parent <id>', 'Parent folder ID (use "root" for root folder)')
82
+ .option('--query <query>', 'Additional query filter')
83
+ .action(async (options) => {
84
+ try {
85
+ const { client } = await getGDriveClient(options.profile);
86
+ const folders = await client.listFolders({
87
+ limit: parseInt(options.limit, 10),
88
+ parentId: options.parent,
89
+ query: options.query,
90
+ });
91
+ printGDriveFileList(folders, 'Folders');
92
+ } catch (error) {
93
+ handleError(error);
94
+ }
95
+ });
96
+
97
+ gdrive
98
+ .command('get <file-id-or-url>')
99
+ .description('Get file metadata')
100
+ .option('--profile <name>', 'Profile name')
101
+ .action(async (fileIdOrUrl: string, options) => {
102
+ try {
103
+ const { client } = await getGDriveClient(options.profile);
104
+ const file = await client.get(fileIdOrUrl);
105
+ printGDriveFile(file);
106
+ } catch (error) {
107
+ handleError(error);
108
+ }
109
+ });
110
+
111
+ gdrive
112
+ .command('search')
113
+ .description('Search for files')
114
+ .requiredOption('--query <text>', 'Search text (searches name and content)')
115
+ .option('--profile <name>', 'Profile name')
116
+ .option('--limit <n>', 'Number of results', '20')
117
+ .option('--type <mime>', 'Filter by MIME type')
118
+ .option('--folder <id>', 'Search within folder')
119
+ .action(async (options) => {
120
+ try {
121
+ const { client } = await getGDriveClient(options.profile);
122
+ const files = await client.search({
123
+ query: options.query,
124
+ mimeType: options.type,
125
+ limit: parseInt(options.limit, 10),
126
+ folderId: options.folder,
127
+ });
128
+ printGDriveFileList(files, 'Search Results');
129
+ } catch (error) {
130
+ handleError(error);
131
+ }
132
+ });
133
+
134
+ gdrive
135
+ .command('download <file-id-or-url>')
136
+ .description('Download a file (or export Google Workspace files)')
137
+ .option('--profile <name>', 'Profile name')
138
+ .requiredOption('--output <path>', 'Output file path')
139
+ .option('--export <format>', 'Export format for Google Workspace files (pdf, docx, xlsx, csv, pptx, txt, etc.)')
140
+ .addHelpText('after', `
141
+ Export Formats:
142
+
143
+ Google Docs: pdf, docx, odt, txt, html, rtf
144
+ Google Sheets: xlsx, csv, pdf, ods, tsv
145
+ Google Slides: pptx, pdf, odp, txt
146
+ Google Drawing: pdf, png, jpeg, svg
147
+
148
+ Examples:
149
+ agentio gdrive download <doc-id> --output report.pdf --export pdf
150
+ agentio gdrive download <sheet-id> --output data.csv --export csv
151
+ `)
152
+ .action(async (fileIdOrUrl: string, options) => {
153
+ try {
154
+ const { client } = await getGDriveClient(options.profile);
155
+ const result = await client.download({
156
+ fileIdOrUrl,
157
+ outputPath: options.output,
158
+ exportFormat: options.export,
159
+ });
160
+ printGDriveDownloaded(result);
161
+ } catch (error) {
162
+ handleError(error);
163
+ }
164
+ });
165
+
166
+ gdrive
167
+ .command('put <file-path>')
168
+ .description('Upload a file to Google Drive')
169
+ .option('--profile <name>', 'Profile name')
170
+ .option('--name <name>', 'Name for the file in Drive (defaults to local filename)')
171
+ .option('--folder <id>', 'Folder ID to upload to')
172
+ .option('--type <mime>', 'MIME type (auto-detected if not specified)')
173
+ .option('--convert', 'Convert to Google Workspace format (Doc, Sheet, or Slides)')
174
+ .addHelpText('after', `
175
+ Conversion:
176
+
177
+ With --convert, supported files are converted to Google Workspace format:
178
+ docx, doc, odt, txt, html, rtf → Google Doc
179
+ xlsx, xls, ods, csv, tsv → Google Sheet
180
+ pptx, ppt, odp → Google Slides
181
+
182
+ Examples:
183
+ agentio gdrive put report.docx --convert # Creates Google Doc
184
+ agentio gdrive put data.xlsx --convert # Creates Google Sheet
185
+ agentio gdrive put slides.pptx --convert # Creates Google Slides
186
+ `)
187
+ .action(async (filePath: string, options) => {
188
+ try {
189
+ const { client } = await getGDriveClient(options.profile);
190
+ const result = await client.upload({
191
+ filePath,
192
+ name: options.name,
193
+ folderId: options.folder,
194
+ mimeType: options.type,
195
+ convert: options.convert,
196
+ });
197
+ printGDriveUploaded(result);
198
+ } catch (error) {
199
+ handleError(error);
200
+ }
201
+ });
202
+
203
+ // Profile management
204
+ const profile = createProfileCommands<GDriveCredentials>(gdrive, {
205
+ service: 'gdrive',
206
+ displayName: 'Google Drive',
207
+ getExtraInfo: (credentials) => {
208
+ if (!credentials) return '';
209
+ const access = credentials.accessLevel === 'full' ? 'full' : 'read-only';
210
+ return ` - ${credentials.email} (${access})`;
211
+ },
212
+ });
213
+
214
+ profile
215
+ .command('add')
216
+ .description('Add a new Google Drive profile')
217
+ .option('--profile <name>', 'Profile name (auto-detected from email if not provided)')
218
+ .option('--readonly', 'Create a read-only profile (skip access level prompt)')
219
+ .option('--full', 'Create a full access profile (skip access level prompt)')
220
+ .action(async (options) => {
221
+ try {
222
+ console.error('Google Drive Setup\n');
223
+
224
+ let accessLevel: GDriveAccessLevel;
225
+
226
+ if (options.readonly) {
227
+ accessLevel = 'readonly';
228
+ } else if (options.full) {
229
+ accessLevel = 'full';
230
+ } else {
231
+ console.error('Access level options:');
232
+ console.error(' 1. Read-only - List, search, download files');
233
+ console.error(' 2. Full - Read-only + upload, create folders, modify files\n');
234
+
235
+ const choice = await prompt('? Select access level (1 or 2): ');
236
+ accessLevel = choice.trim() === '2' ? 'full' : 'readonly';
237
+ }
238
+
239
+ const oauthService = accessLevel === 'full' ? 'gdrive-full' : 'gdrive-readonly';
240
+ console.error(`\nStarting OAuth flow (${accessLevel} access)...\n`);
241
+
242
+ const tokens = await performOAuthFlow(oauthService);
243
+ const auth = createGoogleAuth(tokens);
244
+
245
+ let userEmail: string;
246
+ try {
247
+ const oauth2 = google.oauth2({ version: 'v2', auth });
248
+ const userInfo = await oauth2.userinfo.get();
249
+ userEmail = userInfo.data.email || '';
250
+ if (!userEmail) {
251
+ throw new Error('No email returned');
252
+ }
253
+ } catch (error) {
254
+ const errorMessage = error instanceof Error ? error.message : String(error);
255
+ throw new CliError(
256
+ 'AUTH_FAILED',
257
+ `Failed to fetch user email: ${errorMessage}`,
258
+ 'Ensure the account has an email address'
259
+ );
260
+ }
261
+
262
+ const profileName = options.profile || userEmail;
263
+
264
+ const credentials: GDriveCredentials = {
265
+ accessToken: tokens.access_token,
266
+ refreshToken: tokens.refresh_token,
267
+ expiryDate: tokens.expiry_date,
268
+ tokenType: tokens.token_type,
269
+ scope: tokens.scope,
270
+ email: userEmail,
271
+ accessLevel,
272
+ };
273
+
274
+ await setProfile('gdrive', profileName);
275
+ await setCredentials('gdrive', profileName, credentials);
276
+
277
+ console.log(`\nSuccess! Profile "${profileName}" configured.`);
278
+ console.log(` Email: ${userEmail}`);
279
+ console.log(` Access: ${accessLevel === 'full' ? 'Full (read & write)' : 'Read-only'}`);
280
+ console.log(` Test with: agentio gdrive list --profile ${profileName}`);
281
+ } catch (error) {
282
+ handleError(error);
283
+ }
284
+ });
285
+ }
@@ -1,39 +1,18 @@
1
1
  import { Command } from 'commander';
2
- import { setCredentials, getCredentials } from '../auth/token-store';
3
- import { setProfile, getProfile } from '../config/config-manager';
2
+ import { setCredentials } from '../auth/token-store';
3
+ import { setProfile } from '../config/config-manager';
4
4
  import { createProfileCommands } from '../utils/profile-commands';
5
+ import { createClientGetter } from '../utils/client-factory';
5
6
  import { GitHubClient } from '../services/github/client';
6
7
  import { performGitHubOAuthFlow } from '../auth/github-oauth';
7
8
  import { generateExportData } from './config';
8
9
  import { CliError, handleError } from '../utils/errors';
9
10
  import type { GitHubCredentials } from '../types/github';
10
11
 
11
- async function getGitHubClient(profileName: string): Promise<{ client: GitHubClient; profile: string }> {
12
- const profile = await getProfile('github', profileName);
13
-
14
- if (!profile) {
15
- throw new CliError(
16
- 'PROFILE_NOT_FOUND',
17
- `Profile "${profileName}" not found for github`,
18
- 'Run: agentio github profile add'
19
- );
20
- }
21
-
22
- const credentials = await getCredentials<GitHubCredentials>('github', profile);
23
-
24
- if (!credentials) {
25
- throw new CliError(
26
- 'AUTH_FAILED',
27
- `No credentials found for github profile "${profile}"`,
28
- `Run: agentio github profile add --profile ${profile}`
29
- );
30
- }
31
-
32
- return {
33
- client: new GitHubClient(credentials),
34
- profile,
35
- };
36
- }
12
+ const getGitHubClient = createClientGetter<GitHubCredentials, GitHubClient>({
13
+ service: 'github',
14
+ createClient: (credentials) => new GitHubClient(credentials),
15
+ });
37
16
 
38
17
  function parseRepo(repo: string): { owner: string; name: string } {
39
18
  const parts = repo.split('/');
@@ -56,7 +35,7 @@ export function registerGitHubCommands(program: Command): void {
56
35
  .command('install')
57
36
  .description('Install AGENTIO_KEY and AGENTIO_CONFIG as GitHub Actions secrets')
58
37
  .argument('<repo>', 'Repository in owner/repo format')
59
- .requiredOption('--profile <name>', 'Profile name')
38
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
60
39
  .action(async (repo: string, options) => {
61
40
  try {
62
41
  // Validate repo format
@@ -91,7 +70,7 @@ export function registerGitHubCommands(program: Command): void {
91
70
  .command('uninstall')
92
71
  .description('Remove AGENTIO_KEY and AGENTIO_CONFIG secrets from a repository')
93
72
  .argument('<repo>', 'Repository in owner/repo format')
94
- .requiredOption('--profile <name>', 'Profile name')
73
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
95
74
  .action(async (repo: string, options) => {
96
75
  try {
97
76
  // Validate repo format
@@ -68,7 +68,7 @@ function findChromePath(): string | null {
68
68
  return null;
69
69
  }
70
70
 
71
- async function getGmailClient(profileName: string): Promise<{ client: GmailClient; profile: string }> {
71
+ async function getGmailClient(profileName?: string): Promise<{ client: GmailClient; profile: string }> {
72
72
  const { tokens, profile } = await getValidTokens('gmail', profileName);
73
73
  const auth = createGoogleAuth(tokens);
74
74
  return { client: new GmailClient(auth), profile };
@@ -82,7 +82,7 @@ export function registerGmailCommands(program: Command): void {
82
82
  gmail
83
83
  .command('list')
84
84
  .description('List messages')
85
- .requiredOption('--profile <name>', 'Profile name')
85
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
86
86
  .option('--limit <n>', 'Number of messages', '10')
87
87
  .option('--query <query>', 'Gmail search query (see "gmail search --help" for syntax)')
88
88
  .option('--label <label>', 'Filter by label (repeatable)', (val, acc: string[]) => [...acc, val], [])
@@ -103,7 +103,7 @@ export function registerGmailCommands(program: Command): void {
103
103
  gmail
104
104
  .command('get <message-id>')
105
105
  .description('Get a message')
106
- .requiredOption('--profile <name>', 'Profile name')
106
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
107
107
  .option('--format <format>', 'Body format: text, html, or raw', 'text')
108
108
  .option('--body-only', 'Output only the message body')
109
109
  .action(async (messageId: string, options) => {
@@ -124,7 +124,7 @@ export function registerGmailCommands(program: Command): void {
124
124
  .command('search')
125
125
  .description('Search messages using Gmail query syntax')
126
126
  .requiredOption('--query <query>', 'Search query')
127
- .requiredOption('--profile <name>', 'Profile name')
127
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
128
128
  .option('--limit <n>', 'Max results', '10')
129
129
  .addHelpText('after', `
130
130
  Query Syntax Examples:
@@ -178,7 +178,7 @@ Query Syntax Examples:
178
178
  gmail
179
179
  .command('send')
180
180
  .description('Send an email')
181
- .requiredOption('--profile <name>', 'Profile name')
181
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
182
182
  .requiredOption('--to <email>', 'Recipient (repeatable)', (val, acc: string[]) => [...acc, val], [])
183
183
  .option('--cc <email>', 'CC recipient (repeatable)', (val, acc: string[]) => [...acc, val], [])
184
184
  .option('--bcc <email>', 'BCC recipient (repeatable)', (val, acc: string[]) => [...acc, val], [])
@@ -246,7 +246,7 @@ Query Syntax Examples:
246
246
  gmail
247
247
  .command('reply')
248
248
  .description('Reply to a thread')
249
- .requiredOption('--profile <name>', 'Profile name')
249
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
250
250
  .requiredOption('--thread-id <id>', 'Thread ID')
251
251
  .option('--body <body>', 'Reply body (or pipe via stdin)')
252
252
  .option('--html', 'Treat body as HTML')
@@ -277,7 +277,7 @@ Query Syntax Examples:
277
277
  gmail
278
278
  .command('archive <message-id...>')
279
279
  .description('Archive one or more messages')
280
- .requiredOption('--profile <name>', 'Profile name')
280
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
281
281
  .action(async (messageIds: string[], options) => {
282
282
  try {
283
283
  const { client } = await getGmailClient(options.profile);
@@ -293,7 +293,7 @@ Query Syntax Examples:
293
293
  gmail
294
294
  .command('mark <message-id...>')
295
295
  .description('Mark one or more messages as read or unread')
296
- .requiredOption('--profile <name>', 'Profile name')
296
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
297
297
  .option('--read', 'Mark as read')
298
298
  .option('--unread', 'Mark as unread')
299
299
  .action(async (messageIds: string[], options) => {
@@ -318,7 +318,7 @@ Query Syntax Examples:
318
318
  gmail
319
319
  .command('attachment <message-id>')
320
320
  .description('Download attachments from a message')
321
- .requiredOption('--profile <name>', 'Profile name')
321
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
322
322
  .option('--name <filename>', 'Download specific attachment by filename (downloads all if not specified)')
323
323
  .option('--output <dir>', 'Output directory', '.')
324
324
  .action(async (messageId: string, options) => {
@@ -361,7 +361,7 @@ Query Syntax Examples:
361
361
  gmail
362
362
  .command('export <message-id>')
363
363
  .description('Export a message as PDF')
364
- .requiredOption('--profile <name>', 'Profile name')
364
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
365
365
  .option('--output <path>', 'Output file path', 'message.pdf')
366
366
  .action(async (messageId: string, options) => {
367
367
  try {
@@ -1,6 +1,6 @@
1
1
  import { Command } from 'commander';
2
2
  import { setCredentials, getCredentials } from '../auth/token-store';
3
- import { setProfile, getProfile } from '../config/config-manager';
3
+ import { setProfile, resolveProfile } from '../config/config-manager';
4
4
  import { createProfileCommands } from '../utils/profile-commands';
5
5
  import { performJiraOAuthFlow, refreshJiraToken, type AtlassianSite } from '../auth/jira-oauth';
6
6
  import { JiraClient } from '../services/jira/client';
@@ -46,15 +46,17 @@ async function ensureValidToken(credentials: JiraCredentials, profile: string):
46
46
  return credentials;
47
47
  }
48
48
 
49
- async function getJiraClient(profileName: string): Promise<{ client: JiraClient; profile: string }> {
50
- const profile = await getProfile('jira', profileName);
49
+ async function getJiraClient(profileName?: string): Promise<{ client: JiraClient; profile: string }> {
50
+ const { profile, error } = await resolveProfile('jira', profileName);
51
51
 
52
52
  if (!profile) {
53
- throw new CliError(
54
- 'PROFILE_NOT_FOUND',
55
- `Profile "${profileName}" not found for jira`,
56
- 'Run: agentio jira profile add'
57
- );
53
+ if (error === 'none') {
54
+ throw new CliError('PROFILE_NOT_FOUND', 'No jira profile configured', 'Run: agentio jira profile add');
55
+ }
56
+ if (error === 'multiple') {
57
+ throw new CliError('PROFILE_NOT_FOUND', 'Multiple jira profiles exist', 'Specify --profile <name>');
58
+ }
59
+ throw new CliError('PROFILE_NOT_FOUND', `Profile "${profileName}" not found for jira`, 'Run: agentio jira profile add');
58
60
  }
59
61
 
60
62
  let credentials = await getCredentials<JiraCredentials>('jira', profile);
@@ -85,7 +87,7 @@ export function registerJiraCommands(program: Command): void {
85
87
  jira
86
88
  .command('projects')
87
89
  .description('List JIRA projects')
88
- .requiredOption('--profile <name>', 'Profile name')
90
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
89
91
  .option('--limit <number>', 'Maximum number of projects', '50')
90
92
  .action(async (options) => {
91
93
  try {
@@ -103,7 +105,7 @@ export function registerJiraCommands(program: Command): void {
103
105
  jira
104
106
  .command('search')
105
107
  .description('Search JIRA issues')
106
- .requiredOption('--profile <name>', 'Profile name')
108
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
107
109
  .option('--jql <query>', 'JQL query')
108
110
  .option('--project <key>', 'Project key')
109
111
  .option('--status <status>', 'Issue status')
@@ -130,7 +132,7 @@ export function registerJiraCommands(program: Command): void {
130
132
  .command('get')
131
133
  .description('Get JIRA issue details')
132
134
  .argument('<issue-key>', 'Issue key (e.g., PROJ-123)')
133
- .requiredOption('--profile <name>', 'Profile name')
135
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
134
136
  .action(async (issueKey: string, options) => {
135
137
  try {
136
138
  const { client } = await getJiraClient(options.profile);
@@ -147,7 +149,7 @@ export function registerJiraCommands(program: Command): void {
147
149
  .description('Add a comment to an issue')
148
150
  .argument('<issue-key>', 'Issue key (e.g., PROJ-123)')
149
151
  .argument('[body]', 'Comment body (or pipe via stdin)')
150
- .requiredOption('--profile <name>', 'Profile name')
152
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
151
153
  .action(async (issueKey: string, body: string | undefined, options) => {
152
154
  try {
153
155
  let text = body;
@@ -173,7 +175,7 @@ export function registerJiraCommands(program: Command): void {
173
175
  .command('transitions')
174
176
  .description('List available transitions for an issue')
175
177
  .argument('<issue-key>', 'Issue key (e.g., PROJ-123)')
176
- .requiredOption('--profile <name>', 'Profile name')
178
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
177
179
  .action(async (issueKey: string, options) => {
178
180
  try {
179
181
  const { client } = await getJiraClient(options.profile);
@@ -190,7 +192,7 @@ export function registerJiraCommands(program: Command): void {
190
192
  .description('Transition an issue to a new status')
191
193
  .argument('<issue-key>', 'Issue key (e.g., PROJ-123)')
192
194
  .argument('<transition-id>', 'Transition ID (use "transitions" command to see available)')
193
- .requiredOption('--profile <name>', 'Profile name')
195
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
194
196
  .action(async (issueKey: string, transitionId: string, options) => {
195
197
  try {
196
198
  const { client } = await getJiraClient(options.profile);
@@ -1,40 +1,19 @@
1
1
  import { Command } from 'commander';
2
2
  import { readFile } from 'fs/promises';
3
- import { setCredentials, getCredentials } from '../auth/token-store';
4
- import { setProfile, getProfile } from '../config/config-manager';
3
+ import { setCredentials } from '../auth/token-store';
4
+ import { setProfile } from '../config/config-manager';
5
5
  import { createProfileCommands } from '../utils/profile-commands';
6
+ import { createClientGetter } from '../utils/client-factory';
6
7
  import { SlackClient } from '../services/slack/client';
7
8
  import { CliError, handleError } from '../utils/errors';
8
9
  import { readStdin, prompt } from '../utils/stdin';
9
10
  import { printSlackSendResult } from '../utils/output';
10
11
  import type { SlackCredentials, SlackWebhookCredentials } from '../types/slack';
11
12
 
12
- async function getSlackClient(profileName: string): Promise<{ client: SlackClient; profile: string }> {
13
- const profile = await getProfile('slack', profileName);
14
-
15
- if (!profile) {
16
- throw new CliError(
17
- 'PROFILE_NOT_FOUND',
18
- `Profile "${profileName}" not found for slack`,
19
- 'Run: agentio slack profile add'
20
- );
21
- }
22
-
23
- const credentials = await getCredentials<SlackCredentials>('slack', profile);
24
-
25
- if (!credentials) {
26
- throw new CliError(
27
- 'AUTH_FAILED',
28
- `No credentials found for slack profile "${profile}"`,
29
- `Run: agentio slack profile add --profile ${profile}`
30
- );
31
- }
32
-
33
- return {
34
- client: new SlackClient(credentials),
35
- profile,
36
- };
37
- }
13
+ const getSlackClient = createClientGetter<SlackCredentials, SlackClient>({
14
+ service: 'slack',
15
+ createClient: (credentials) => new SlackClient(credentials),
16
+ });
38
17
 
39
18
  export function registerSlackCommands(program: Command): void {
40
19
  const slack = program
@@ -44,7 +23,7 @@ export function registerSlackCommands(program: Command): void {
44
23
  slack
45
24
  .command('send')
46
25
  .description('Send a message to Slack')
47
- .requiredOption('--profile <name>', 'Profile name')
26
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
48
27
  .option('--json [file]', 'Send Block Kit message from JSON file (or stdin if no file specified)')
49
28
  .argument('[message]', 'Message text (or pipe via stdin)')
50
29
  .action(async (message: string | undefined, options) => {
@@ -1,45 +1,25 @@
1
1
  import { Command } from 'commander';
2
- import { setCredentials, getCredentials } from '../auth/token-store';
3
- import { setProfile, getProfile } from '../config/config-manager';
2
+ import { setCredentials } from '../auth/token-store';
3
+ import { setProfile } from '../config/config-manager';
4
4
  import { createProfileCommands } from '../utils/profile-commands';
5
+ import { createClientGetter } from '../utils/client-factory';
5
6
  import { SqlClient } from '../services/sql/client';
6
7
  import { CliError, handleError } from '../utils/errors';
7
8
  import { readStdin, prompt } from '../utils/stdin';
8
9
  import type { SqlCredentials } from '../types/sql';
9
10
 
10
- async function getSqlClient(profileName: string): Promise<{ client: SqlClient; profile: string }> {
11
- const profile = await getProfile('sql', profileName);
12
-
13
- if (!profile) {
14
- throw new CliError(
15
- 'PROFILE_NOT_FOUND',
16
- `Profile "${profileName}" not found for sql`,
17
- 'Run: agentio sql profile add'
18
- );
19
- }
20
-
21
- const credentials = await getCredentials<SqlCredentials>('sql', profile);
22
-
23
- if (!credentials) {
24
- throw new CliError(
25
- 'AUTH_FAILED',
26
- `No credentials found for sql profile "${profile}"`,
27
- `Run: agentio sql profile add --profile ${profile}`
28
- );
29
- }
30
-
31
- return {
32
- client: new SqlClient(credentials),
33
- profile,
34
- };
35
- }
11
+ const getSqlClient = createClientGetter<SqlCredentials, SqlClient>({
12
+ service: 'sql',
13
+ createClient: (credentials) => new SqlClient(credentials),
14
+ });
36
15
 
37
16
  function extractDisplayName(url: string): string {
38
17
  try {
39
18
  const parsed = new URL(url);
19
+ const username = parsed.username ? decodeURIComponent(parsed.username) : '';
40
20
  const host = parsed.hostname || 'localhost';
41
21
  const db = parsed.pathname.replace(/^\//, '') || 'database';
42
- return `${host}/${db}`;
22
+ return username ? `${username}@${host}/${db}` : `${host}/${db}`;
43
23
  } catch {
44
24
  return url.substring(0, 30);
45
25
  }
@@ -53,7 +33,7 @@ export function registerSqlCommands(program: Command): void {
53
33
  sql
54
34
  .command('query')
55
35
  .description('Execute a SQL query')
56
- .requiredOption('--profile <name>', 'Profile name')
36
+ .option('--profile <name>', 'Profile name (optional if only one profile exists)')
57
37
  .option('--limit <n>', 'Maximum rows to return', '100')
58
38
  .argument('[query]', 'SQL query (or pipe via stdin)')
59
39
  .action(async (query: string | undefined, options) => {