@gopherhole/cli 0.5.0 → 0.6.1

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 (3) hide show
  1. package/dist/index.js +849 -1
  2. package/package.json +1 -1
  3. package/src/index.ts +673 -1
package/src/index.ts CHANGED
@@ -20,7 +20,7 @@ const brand = {
20
20
  };
21
21
 
22
22
  // Version
23
- const VERSION = '0.4.1';
23
+ const VERSION = '0.6.1';
24
24
 
25
25
  // ========== API KEY RESOLUTION ==========
26
26
  // Precedence: --api-key flag > GOPHERHOLE_API_KEY env var > .env file in cwd
@@ -2807,6 +2807,70 @@ ${chalk.bold('Examples:')}
2807
2807
  }
2808
2808
  });
2809
2809
 
2810
+ // ========== REQUEST ACCESS (agent-to-agent via API key) ==========
2811
+
2812
+ program
2813
+ .command('request-access <agentId>')
2814
+ .description(`Request access to another agent (agent-to-agent, uses API key)
2815
+
2816
+ If the target has auto-approve enabled, access is granted immediately.
2817
+ Otherwise it's queued for manual approval by the target tenant.
2818
+
2819
+ ${chalk.bold('Examples:')}
2820
+ $ gopherhole request-access agent-abc123
2821
+ $ gopherhole request-access agent-abc123 --reason "Need data feed"
2822
+ $ gopherhole request-access agent-abc123 --scopes "messages:send,memory:read"
2823
+ `)
2824
+ .option('--api-key <key>', 'API key (overrides env / .env)')
2825
+ .option('--scopes <scopes>', 'Comma-separated scopes to request (default: messages:send)')
2826
+ .option('--reason <text>', 'Reason for the request (shown to target tenant)')
2827
+ .action(async (agentId, options) => {
2828
+ const apiKey = await resolveApiKey(options.apiKey);
2829
+ if (!apiKey) {
2830
+ console.error(chalk.red('No API key found.'));
2831
+ console.error(chalk.gray('Set GOPHERHOLE_API_KEY, pass --api-key, or run gopherhole init'));
2832
+ process.exit(1);
2833
+ }
2834
+
2835
+ const scopes = options.scopes
2836
+ ? options.scopes.split(',').map((s: string) => s.trim())
2837
+ : ['messages:send'];
2838
+
2839
+ const spinner = ora(`Requesting access to ${agentId}...`).start();
2840
+ try {
2841
+ const res = await fetch(`${API_URL}/access/request`, {
2842
+ method: 'POST',
2843
+ headers: {
2844
+ 'Content-Type': 'application/json',
2845
+ Authorization: `Bearer ${apiKey}`,
2846
+ },
2847
+ body: JSON.stringify({
2848
+ targetAgentId: agentId,
2849
+ scopes,
2850
+ reason: options.reason,
2851
+ }),
2852
+ });
2853
+
2854
+ if (!res.ok) {
2855
+ const err = await res.json().catch(() => ({}));
2856
+ throw new Error((err as any).error || `HTTP ${res.status}`);
2857
+ }
2858
+
2859
+ const data = await res.json() as { grant: { id: string; status: string } };
2860
+
2861
+ if (data.grant.status === 'approved') {
2862
+ spinner.succeed(`Access granted immediately (auto-approved). You can now message ${chalk.cyan(agentId)}.`);
2863
+ } else {
2864
+ spinner.succeed(`Access request submitted (pending approval).`);
2865
+ }
2866
+ console.log(` Grant ID: ${chalk.cyan(data.grant.id)}`);
2867
+ console.log(` Status: ${data.grant.status}`);
2868
+ } catch (err) {
2869
+ spinner.fail(chalk.red((err as Error).message));
2870
+ process.exit(1);
2871
+ }
2872
+ });
2873
+
2810
2874
  // ========== MEMORY COMMANDS (agent-to-agent via memory agent) ==========
2811
2875
 
2812
2876
  const MEMORY_AGENT = process.env.GOPHERHOLE_MEMORY_AGENT || 'agent-memory-official';
@@ -3159,5 +3223,613 @@ wsMembers
3159
3223
  }
3160
3224
  });
3161
3225
 
3226
+ // ========== KEYS COMMAND ==========
3227
+
3228
+ const keys = program
3229
+ .command('keys')
3230
+ .description(`Manage API keys
3231
+
3232
+ ${chalk.bold('Examples:')}
3233
+ $ gopherhole keys list
3234
+ $ gopherhole keys create --name "prod" --agent agent-abc123
3235
+ $ gopherhole keys delete key-abc123
3236
+ `);
3237
+
3238
+ keys
3239
+ .command('list')
3240
+ .description('List all API keys on the tenant')
3241
+ .option('--json', 'Output as JSON')
3242
+ .action(async (options) => {
3243
+ const sessionId = config.get('sessionId') as string;
3244
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3245
+
3246
+ const spinner = ora('Fetching API keys...').start();
3247
+ try {
3248
+ const res = await fetch(`${API_URL}/api-keys`, { headers: { 'X-Session-ID': sessionId } });
3249
+ if (!res.ok) throw new Error('Failed to fetch API keys');
3250
+ const data = await res.json() as { keys: any[] };
3251
+ const keysList = Array.isArray(data) ? data : data.keys || [];
3252
+ spinner.stop();
3253
+
3254
+ if (options.json) { console.log(JSON.stringify(keysList, null, 2)); return; }
3255
+ if (keysList.length === 0) { console.log(chalk.yellow('\nNo API keys found.\n')); return; }
3256
+
3257
+ console.log(chalk.bold('\nAPI Keys:\n'));
3258
+ for (const k of keysList) {
3259
+ console.log(` ${chalk.cyan(k.id)} — ${k.name || 'unnamed'}`);
3260
+ console.log(` Agent: ${k.agentId || k.agent_id || 'none'} | Prefix: ${chalk.gray(k.prefix || '???')} | Scopes: ${k.scopes?.join(', ') || 'default'}`);
3261
+ console.log('');
3262
+ }
3263
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3264
+ });
3265
+
3266
+ keys
3267
+ .command('create')
3268
+ .description('Create a new API key')
3269
+ .requiredOption('--name <name>', 'Human-readable label for this key')
3270
+ .requiredOption('--agent <agentId>', 'The agent this key authenticates as')
3271
+ .option('--scopes <scopes>', 'Comma-separated scopes (e.g., "messages:send,memory:read")')
3272
+ .action(async (options) => {
3273
+ const sessionId = config.get('sessionId') as string;
3274
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3275
+
3276
+ const spinner = ora('Creating API key...').start();
3277
+ try {
3278
+ const body: any = { name: options.name, agentId: options.agent };
3279
+ if (options.scopes) body.scopes = options.scopes.split(',').map((s: string) => s.trim());
3280
+ const res = await fetch(`${API_URL}/api-keys`, {
3281
+ method: 'POST',
3282
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3283
+ body: JSON.stringify(body),
3284
+ });
3285
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to create key'); }
3286
+ const data = await res.json() as any;
3287
+ spinner.succeed('API key created!');
3288
+ console.log('');
3289
+ console.log(` ID: ${chalk.cyan(data.id)}`);
3290
+ console.log(` Key: ${brand.green(data.key || data.secret)}`);
3291
+ console.log('');
3292
+ console.log(chalk.yellow(' Store this key securely — it will not be shown again.'));
3293
+ console.log('');
3294
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3295
+ });
3296
+
3297
+ keys
3298
+ .command('delete <keyId>')
3299
+ .description('Revoke and delete an API key')
3300
+ .option('-y, --yes', 'Skip confirmation')
3301
+ .action(async (keyId, options) => {
3302
+ const sessionId = config.get('sessionId') as string;
3303
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3304
+
3305
+ if (!options.yes) {
3306
+ const { confirm } = await inquirer.prompt([{
3307
+ type: 'confirm', name: 'confirm', message: `Permanently revoke key ${keyId}?`, default: false,
3308
+ }]);
3309
+ if (!confirm) { console.log(chalk.gray('Cancelled.')); return; }
3310
+ }
3311
+
3312
+ const spinner = ora('Revoking key...').start();
3313
+ try {
3314
+ const res = await fetch(`${API_URL}/api-keys/${keyId}`, {
3315
+ method: 'DELETE',
3316
+ headers: { 'X-Session-ID': sessionId },
3317
+ });
3318
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to delete key'); }
3319
+ spinner.succeed(`Key ${chalk.cyan(keyId)} revoked and deleted.`);
3320
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3321
+ });
3322
+
3323
+ // ========== TEAM COMMAND ==========
3324
+
3325
+ const team = program
3326
+ .command('team')
3327
+ .description(`Manage team members
3328
+
3329
+ ${chalk.bold('Examples:')}
3330
+ $ gopherhole team list
3331
+ $ gopherhole team invite user@example.com --role admin
3332
+ $ gopherhole team remove member-abc123
3333
+ `);
3334
+
3335
+ team
3336
+ .command('list')
3337
+ .description('List team members')
3338
+ .option('--json', 'Output as JSON')
3339
+ .action(async (options) => {
3340
+ const sessionId = config.get('sessionId') as string;
3341
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3342
+
3343
+ const spinner = ora('Fetching team...').start();
3344
+ try {
3345
+ const res = await fetch(`${API_URL}/team/members`, { headers: { 'X-Session-ID': sessionId } });
3346
+ if (!res.ok) throw new Error('Failed to fetch team');
3347
+ const data = await res.json() as any;
3348
+ const members = Array.isArray(data) ? data : data.members || [];
3349
+ spinner.stop();
3350
+
3351
+ if (options.json) { console.log(JSON.stringify(members, null, 2)); return; }
3352
+ if (members.length === 0) { console.log(chalk.yellow('\nNo team members.\n')); return; }
3353
+
3354
+ console.log(chalk.bold('\nTeam Members:\n'));
3355
+ for (const m of members) {
3356
+ const role = m.role === 'admin' ? chalk.red(m.role) : chalk.gray(m.role);
3357
+ console.log(` ${chalk.bold(m.name || m.email)} (${chalk.cyan(m.id)})`);
3358
+ console.log(` Role: ${role}${m.joinedAt ? ` | Joined: ${m.joinedAt}` : ''}`);
3359
+ console.log('');
3360
+ }
3361
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3362
+ });
3363
+
3364
+ team
3365
+ .command('invite <email>')
3366
+ .description('Invite someone to your tenant')
3367
+ .option('--role <role>', 'Role: admin, member, viewer (default: member)')
3368
+ .action(async (email, options) => {
3369
+ const sessionId = config.get('sessionId') as string;
3370
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3371
+
3372
+ const spinner = ora(`Sending invite to ${email}...`).start();
3373
+ try {
3374
+ const body: any = { email };
3375
+ if (options.role) body.role = options.role;
3376
+ const res = await fetch(`${API_URL}/team/invites`, {
3377
+ method: 'POST',
3378
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3379
+ body: JSON.stringify(body),
3380
+ });
3381
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to send invite'); }
3382
+ spinner.succeed(`Invitation sent to ${chalk.cyan(email)} with role: ${options.role || 'member'}`);
3383
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3384
+ });
3385
+
3386
+ team
3387
+ .command('remove <memberId>')
3388
+ .description('Remove a team member')
3389
+ .option('-y, --yes', 'Skip confirmation')
3390
+ .action(async (memberId, options) => {
3391
+ const sessionId = config.get('sessionId') as string;
3392
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3393
+
3394
+ if (!options.yes) {
3395
+ const { confirm } = await inquirer.prompt([{
3396
+ type: 'confirm', name: 'confirm', message: `Remove team member ${memberId}?`, default: false,
3397
+ }]);
3398
+ if (!confirm) { console.log(chalk.gray('Cancelled.')); return; }
3399
+ }
3400
+
3401
+ const spinner = ora('Removing member...').start();
3402
+ try {
3403
+ const res = await fetch(`${API_URL}/team/members/${memberId}`, {
3404
+ method: 'DELETE',
3405
+ headers: { 'X-Session-ID': sessionId },
3406
+ });
3407
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to remove member'); }
3408
+ spinner.succeed(`Team member ${chalk.cyan(memberId)} removed.`);
3409
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3410
+ });
3411
+
3412
+ // ========== USAGE COMMAND ==========
3413
+
3414
+ const usage = program
3415
+ .command('usage')
3416
+ .description(`View usage statistics
3417
+
3418
+ ${chalk.bold('Examples:')}
3419
+ $ gopherhole usage summary
3420
+ $ gopherhole usage summary --period week
3421
+ $ gopherhole usage agents
3422
+ `);
3423
+
3424
+ usage
3425
+ .command('summary')
3426
+ .description('Get high-level usage overview')
3427
+ .option('--period <period>', 'Time window: day, week, month (default: month)')
3428
+ .option('--json', 'Output as JSON')
3429
+ .action(async (options) => {
3430
+ const sessionId = config.get('sessionId') as string;
3431
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3432
+
3433
+ const spinner = ora('Fetching usage...').start();
3434
+ try {
3435
+ const params = new URLSearchParams();
3436
+ if (options.period) params.set('period', options.period);
3437
+ const qs = params.toString() ? `?${params}` : '';
3438
+ const res = await fetch(`${API_URL}/usage/summary${qs}`, { headers: { 'X-Session-ID': sessionId } });
3439
+ if (!res.ok) throw new Error('Failed to fetch usage');
3440
+ const data = await res.json();
3441
+ spinner.stop();
3442
+
3443
+ if (options.json) { console.log(JSON.stringify(data, null, 2)); return; }
3444
+
3445
+ console.log(chalk.bold(`\nUsage Summary (${options.period || 'month'}):\n`));
3446
+ const d = data as any;
3447
+ if (d.messagesSent !== undefined) console.log(` Messages Sent: ${brand.green(d.messagesSent)}`);
3448
+ if (d.messagesReceived !== undefined) console.log(` Messages Received: ${brand.green(d.messagesReceived)}`);
3449
+ if (d.tasksCreated !== undefined) console.log(` Tasks Created: ${brand.green(d.tasksCreated)}`);
3450
+ if (d.connections !== undefined) console.log(` Connections: ${brand.green(d.connections)}`);
3451
+ if (d.creditsUsed !== undefined) console.log(` Credits Used: ${brand.green(d.creditsUsed)}`);
3452
+ console.log('');
3453
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3454
+ });
3455
+
3456
+ usage
3457
+ .command('agents')
3458
+ .description('Per-agent usage breakdown')
3459
+ .option('--period <period>', 'Time window: day, week, month (default: month)')
3460
+ .option('--limit <n>', 'Max agents to show (default: 20)')
3461
+ .option('--json', 'Output as JSON')
3462
+ .action(async (options) => {
3463
+ const sessionId = config.get('sessionId') as string;
3464
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3465
+
3466
+ const spinner = ora('Fetching per-agent usage...').start();
3467
+ try {
3468
+ const params = new URLSearchParams();
3469
+ if (options.period) params.set('period', options.period);
3470
+ if (options.limit) params.set('limit', options.limit);
3471
+ const qs = params.toString() ? `?${params}` : '';
3472
+ const res = await fetch(`${API_URL}/usage/agents${qs}`, { headers: { 'X-Session-ID': sessionId } });
3473
+ if (!res.ok) throw new Error('Failed to fetch agent usage');
3474
+ const data = await res.json() as any;
3475
+ spinner.stop();
3476
+
3477
+ if (options.json) { console.log(JSON.stringify(data, null, 2)); return; }
3478
+
3479
+ const agents = Array.isArray(data) ? data : data.agents || [];
3480
+ if (agents.length === 0) { console.log(chalk.yellow('\nNo usage data.\n')); return; }
3481
+
3482
+ console.log(chalk.bold(`\nPer-Agent Usage (${options.period || 'month'}):\n`));
3483
+ for (const a of agents) {
3484
+ console.log(` ${chalk.bold(a.name || a.agentId)} (${chalk.cyan(a.agentId || a.id)})`);
3485
+ if (a.messages !== undefined) console.log(` Messages: ${a.messages}`);
3486
+ if (a.tasks !== undefined) console.log(` Tasks: ${a.tasks}`);
3487
+ if (a.credits !== undefined) console.log(` Credits: ${a.credits}`);
3488
+ console.log('');
3489
+ }
3490
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3491
+ });
3492
+
3493
+ // ========== WEBHOOKS COMMAND ==========
3494
+
3495
+ const webhooks = program
3496
+ .command('webhooks')
3497
+ .description(`Manage webhooks
3498
+
3499
+ ${chalk.bold('Examples:')}
3500
+ $ gopherhole webhooks list
3501
+ $ gopherhole webhooks create --url https://example.com/hook --events message.received,task.completed
3502
+ $ gopherhole webhooks delete wh-abc123
3503
+ $ gopherhole webhooks test wh-abc123
3504
+ `);
3505
+
3506
+ webhooks
3507
+ .command('list')
3508
+ .description('List configured webhooks')
3509
+ .option('--json', 'Output as JSON')
3510
+ .action(async (options) => {
3511
+ const sessionId = config.get('sessionId') as string;
3512
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3513
+
3514
+ const spinner = ora('Fetching webhooks...').start();
3515
+ try {
3516
+ const res = await fetch(`${API_URL}/webhooks`, { headers: { 'X-Session-ID': sessionId } });
3517
+ if (!res.ok) throw new Error('Failed to fetch webhooks');
3518
+ const data = await res.json() as any;
3519
+ const hooks = Array.isArray(data) ? data : data.webhooks || [];
3520
+ spinner.stop();
3521
+
3522
+ if (options.json) { console.log(JSON.stringify(hooks, null, 2)); return; }
3523
+ if (hooks.length === 0) { console.log(chalk.yellow('\nNo webhooks configured.\n')); return; }
3524
+
3525
+ console.log(chalk.bold('\nWebhooks:\n'));
3526
+ for (const h of hooks) {
3527
+ console.log(` ${chalk.cyan(h.id)} — ${h.url}`);
3528
+ console.log(` Events: ${h.events?.join(', ') || 'all'}${h.description ? ` | ${chalk.gray(h.description)}` : ''}`);
3529
+ console.log('');
3530
+ }
3531
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3532
+ });
3533
+
3534
+ webhooks
3535
+ .command('create')
3536
+ .description('Create a new webhook')
3537
+ .requiredOption('--url <url>', 'HTTPS URL to deliver events to')
3538
+ .requiredOption('--events <events>', 'Comma-separated event types (e.g., "message.received,task.completed")')
3539
+ .option('--description <text>', 'Label for this webhook')
3540
+ .option('--secret <secret>', 'Signing secret for HMAC-SHA256 verification')
3541
+ .action(async (options) => {
3542
+ const sessionId = config.get('sessionId') as string;
3543
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3544
+
3545
+ const spinner = ora('Creating webhook...').start();
3546
+ try {
3547
+ const body: any = {
3548
+ url: options.url,
3549
+ events: options.events.split(',').map((e: string) => e.trim()),
3550
+ };
3551
+ if (options.description) body.description = options.description;
3552
+ if (options.secret) body.secret = options.secret;
3553
+ const res = await fetch(`${API_URL}/webhooks`, {
3554
+ method: 'POST',
3555
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3556
+ body: JSON.stringify(body),
3557
+ });
3558
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to create webhook'); }
3559
+ const data = await res.json() as any;
3560
+ spinner.succeed('Webhook created!');
3561
+ console.log(`\n ID: ${chalk.cyan(data.id)}`);
3562
+ console.log(` URL: ${data.url || options.url}`);
3563
+ console.log(` Events: ${body.events.join(', ')}\n`);
3564
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3565
+ });
3566
+
3567
+ webhooks
3568
+ .command('delete <webhookId>')
3569
+ .description('Delete a webhook')
3570
+ .option('-y, --yes', 'Skip confirmation')
3571
+ .action(async (webhookId, options) => {
3572
+ const sessionId = config.get('sessionId') as string;
3573
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3574
+
3575
+ if (!options.yes) {
3576
+ const { confirm } = await inquirer.prompt([{
3577
+ type: 'confirm', name: 'confirm', message: `Delete webhook ${webhookId}?`, default: false,
3578
+ }]);
3579
+ if (!confirm) { console.log(chalk.gray('Cancelled.')); return; }
3580
+ }
3581
+
3582
+ const spinner = ora('Deleting webhook...').start();
3583
+ try {
3584
+ const res = await fetch(`${API_URL}/webhooks/${webhookId}`, {
3585
+ method: 'DELETE',
3586
+ headers: { 'X-Session-ID': sessionId },
3587
+ });
3588
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to delete webhook'); }
3589
+ spinner.succeed(`Webhook ${chalk.cyan(webhookId)} deleted.`);
3590
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3591
+ });
3592
+
3593
+ webhooks
3594
+ .command('test <webhookId>')
3595
+ .description('Send a test event to a webhook')
3596
+ .action(async (webhookId) => {
3597
+ const sessionId = config.get('sessionId') as string;
3598
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3599
+
3600
+ const spinner = ora('Sending test event...').start();
3601
+ try {
3602
+ const res = await fetch(`${API_URL}/webhooks/${webhookId}/test`, {
3603
+ method: 'POST',
3604
+ headers: { 'X-Session-ID': sessionId },
3605
+ });
3606
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to test webhook'); }
3607
+ const data = await res.json() as any;
3608
+ spinner.succeed(`Test event sent. Response: ${data.status || data.statusCode || 'delivered'}`);
3609
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3610
+ });
3611
+
3612
+ // ========== TENANT COMMAND ==========
3613
+
3614
+ const tenant = program
3615
+ .command('tenant')
3616
+ .description(`View and manage tenant settings
3617
+
3618
+ ${chalk.bold('Examples:')}
3619
+ $ gopherhole tenant settings
3620
+ $ gopherhole tenant update --name "Acme Corp" --slug acme
3621
+ `);
3622
+
3623
+ tenant
3624
+ .command('settings')
3625
+ .description('View current tenant settings')
3626
+ .option('--json', 'Output as JSON')
3627
+ .action(async (options) => {
3628
+ const sessionId = config.get('sessionId') as string;
3629
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3630
+
3631
+ const spinner = ora('Fetching tenant settings...').start();
3632
+ try {
3633
+ const res = await fetch(`${API_URL}/auth/tenant/settings`, { headers: { 'X-Session-ID': sessionId } });
3634
+ if (!res.ok) throw new Error('Failed to fetch tenant settings');
3635
+ const data = await res.json() as any;
3636
+ spinner.stop();
3637
+
3638
+ if (options.json) { console.log(JSON.stringify(data, null, 2)); return; }
3639
+
3640
+ console.log(chalk.bold('\nTenant Settings:\n'));
3641
+ if (data.name) console.log(` Name: ${brand.green(data.name)}`);
3642
+ if (data.slug) console.log(` Slug: ${chalk.cyan(data.slug)}`);
3643
+ if (data.plan) console.log(` Plan: ${data.plan}`);
3644
+ if (data.email) console.log(` Email: ${data.email}`);
3645
+ if (data.id) console.log(` ID: ${chalk.gray(data.id)}`);
3646
+ console.log('');
3647
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3648
+ });
3649
+
3650
+ tenant
3651
+ .command('update')
3652
+ .description('Update tenant name or slug')
3653
+ .option('--name <name>', 'New display name')
3654
+ .option('--slug <slug>', 'New URL-safe slug')
3655
+ .action(async (options) => {
3656
+ const sessionId = config.get('sessionId') as string;
3657
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3658
+
3659
+ const body: any = {};
3660
+ if (options.name) body.name = options.name;
3661
+ if (options.slug) body.slug = options.slug;
3662
+ if (Object.keys(body).length === 0) {
3663
+ console.log(chalk.yellow('No changes specified. Use --name or --slug.'));
3664
+ return;
3665
+ }
3666
+
3667
+ const spinner = ora('Updating tenant...').start();
3668
+ try {
3669
+ const res = await fetch(`${API_URL}/auth/tenant`, {
3670
+ method: 'PATCH',
3671
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3672
+ body: JSON.stringify(body),
3673
+ });
3674
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to update tenant'); }
3675
+ spinner.succeed('Tenant updated.');
3676
+ if (body.name) console.log(` Name: ${brand.green(body.name)}`);
3677
+ if (body.slug) console.log(` Slug: ${chalk.cyan(body.slug)}`);
3678
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3679
+ });
3680
+
3681
+ // ========== PROFILE COMMAND ==========
3682
+
3683
+ program
3684
+ .command('profile')
3685
+ .description(`Update your user profile
3686
+
3687
+ ${chalk.bold('Examples:')}
3688
+ $ gopherhole profile --name "Jane Smith"
3689
+ $ gopherhole profile --avatar https://example.com/photo.jpg
3690
+ `)
3691
+ .option('--name <name>', 'Display name')
3692
+ .option('--avatar <url>', 'Avatar image URL')
3693
+ .action(async (options) => {
3694
+ const sessionId = config.get('sessionId') as string;
3695
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3696
+
3697
+ const body: any = {};
3698
+ if (options.name) body.name = options.name;
3699
+ if (options.avatar) body.avatarUrl = options.avatar;
3700
+ if (Object.keys(body).length === 0) {
3701
+ console.log(chalk.yellow('No changes specified. Use --name or --avatar.'));
3702
+ return;
3703
+ }
3704
+
3705
+ const spinner = ora('Updating profile...').start();
3706
+ try {
3707
+ const res = await fetch(`${API_URL}/auth/me`, {
3708
+ method: 'PATCH',
3709
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3710
+ body: JSON.stringify(body),
3711
+ });
3712
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to update profile'); }
3713
+ spinner.succeed('Profile updated.');
3714
+ if (body.name) console.log(` Name: ${brand.green(body.name)}`);
3715
+ if (body.avatarUrl) console.log(` Avatar: updated`);
3716
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3717
+ });
3718
+
3719
+ // ========== SECRETS COMMAND (workspace secrets) ==========
3720
+
3721
+ const secrets = program
3722
+ .command('secrets')
3723
+ .description(`Manage workspace secrets
3724
+
3725
+ ${chalk.bold('Examples:')}
3726
+ $ gopherhole secrets list ws-abc123
3727
+ $ gopherhole secrets set ws-abc123 OPENAI_API_KEY sk-abc...
3728
+ $ gopherhole secrets delete ws-abc123 OPENAI_API_KEY
3729
+ `);
3730
+
3731
+ secrets
3732
+ .command('list <workspaceId>')
3733
+ .description('List secret keys in a workspace (values are never shown)')
3734
+ .option('--json', 'Output as JSON')
3735
+ .action(async (workspaceId, options) => {
3736
+ const sessionId = config.get('sessionId') as string;
3737
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3738
+
3739
+ const spinner = ora('Fetching secrets...').start();
3740
+ try {
3741
+ const res = await fetch(`${API_URL}/workspaces/${workspaceId}/secrets`, { headers: { 'X-Session-ID': sessionId } });
3742
+ if (!res.ok) throw new Error('Failed to fetch secrets');
3743
+ const data = await res.json() as any;
3744
+ const secretsList = Array.isArray(data) ? data : data.secrets || [];
3745
+ spinner.stop();
3746
+
3747
+ if (options.json) { console.log(JSON.stringify(secretsList, null, 2)); return; }
3748
+ if (secretsList.length === 0) { console.log(chalk.yellow('\nNo secrets in this workspace.\n')); return; }
3749
+
3750
+ console.log(chalk.bold('\nWorkspace Secrets:\n'));
3751
+ for (const s of secretsList) {
3752
+ console.log(` ${chalk.cyan(s.key || s.name)}`);
3753
+ }
3754
+ console.log('');
3755
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3756
+ });
3757
+
3758
+ secrets
3759
+ .command('set <workspaceId> <key> <value>')
3760
+ .description('Create or update a workspace secret')
3761
+ .action(async (workspaceId, key, value) => {
3762
+ const sessionId = config.get('sessionId') as string;
3763
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3764
+
3765
+ const spinner = ora(`Setting secret ${key}...`).start();
3766
+ try {
3767
+ const res = await fetch(`${API_URL}/workspaces/${workspaceId}/secrets`, {
3768
+ method: 'POST',
3769
+ headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
3770
+ body: JSON.stringify({ key, value }),
3771
+ });
3772
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to set secret'); }
3773
+ spinner.succeed(`Secret ${chalk.cyan(key)} stored.`);
3774
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3775
+ });
3776
+
3777
+ secrets
3778
+ .command('delete <workspaceId> <key>')
3779
+ .description('Delete a workspace secret')
3780
+ .option('-y, --yes', 'Skip confirmation')
3781
+ .action(async (workspaceId, key, options) => {
3782
+ const sessionId = config.get('sessionId') as string;
3783
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3784
+
3785
+ if (!options.yes) {
3786
+ const { confirm } = await inquirer.prompt([{
3787
+ type: 'confirm', name: 'confirm', message: `Delete secret ${key}?`, default: false,
3788
+ }]);
3789
+ if (!confirm) { console.log(chalk.gray('Cancelled.')); return; }
3790
+ }
3791
+
3792
+ const spinner = ora(`Deleting secret ${key}...`).start();
3793
+ try {
3794
+ const res = await fetch(`${API_URL}/workspaces/${workspaceId}/secrets/${key}`, {
3795
+ method: 'DELETE',
3796
+ headers: { 'X-Session-ID': sessionId },
3797
+ });
3798
+ if (!res.ok) { const err = await res.json(); throw new Error((err as any).error || 'Failed to delete secret'); }
3799
+ spinner.succeed(`Secret ${chalk.cyan(key)} deleted.`);
3800
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3801
+ });
3802
+
3803
+ // ========== CREDITS COMMAND ==========
3804
+
3805
+ program
3806
+ .command('credits')
3807
+ .description(`View credit balance
3808
+
3809
+ ${chalk.bold('Examples:')}
3810
+ $ gopherhole credits
3811
+ `)
3812
+ .option('--json', 'Output as JSON')
3813
+ .action(async (options) => {
3814
+ const sessionId = config.get('sessionId') as string;
3815
+ if (!sessionId) { console.log(chalk.yellow('Not logged in. Run: gopherhole login')); process.exit(1); }
3816
+
3817
+ const spinner = ora('Fetching balance...').start();
3818
+ try {
3819
+ const res = await fetch(`${API_URL}/credits/balance`, { headers: { 'X-Session-ID': sessionId } });
3820
+ if (!res.ok) throw new Error('Failed to fetch credits');
3821
+ const data = await res.json() as any;
3822
+ spinner.stop();
3823
+
3824
+ if (options.json) { console.log(JSON.stringify(data, null, 2)); return; }
3825
+
3826
+ console.log(chalk.bold('\nCredit Balance:\n'));
3827
+ if (data.remaining !== undefined) console.log(` Remaining: ${brand.green(data.remaining)}`);
3828
+ if (data.total !== undefined) console.log(` Total: ${data.total}`);
3829
+ if (data.used !== undefined) console.log(` Used: ${data.used}`);
3830
+ console.log('');
3831
+ } catch (err) { spinner.fail(chalk.red((err as Error).message)); process.exit(1); }
3832
+ });
3833
+
3162
3834
  // Parse and run
3163
3835
  program.parse();