berget 0.1.0 → 1.1.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.
Files changed (49) hide show
  1. package/README.md +92 -0
  2. package/dist/index.js +7 -439
  3. package/dist/src/client.js +193 -102
  4. package/dist/src/commands/api-keys.js +271 -0
  5. package/dist/src/commands/auth.js +65 -0
  6. package/dist/src/commands/autocomplete.js +24 -0
  7. package/dist/src/commands/billing.js +53 -0
  8. package/dist/src/commands/chat.js +276 -0
  9. package/dist/src/commands/clusters.js +69 -0
  10. package/dist/src/commands/index.js +25 -0
  11. package/dist/src/commands/models.js +69 -0
  12. package/dist/src/commands/users.js +43 -0
  13. package/dist/src/constants/command-structure.js +164 -0
  14. package/dist/src/services/api-key-service.js +34 -5
  15. package/dist/src/services/auth-service.js +83 -43
  16. package/dist/src/services/chat-service.js +177 -0
  17. package/dist/src/services/cluster-service.js +37 -2
  18. package/dist/src/services/collaborator-service.js +21 -4
  19. package/dist/src/services/flux-service.js +21 -4
  20. package/dist/src/services/helm-service.js +20 -3
  21. package/dist/src/services/kubectl-service.js +26 -5
  22. package/dist/src/utils/config-checker.js +50 -0
  23. package/dist/src/utils/default-api-key.js +111 -0
  24. package/dist/src/utils/token-manager.js +165 -0
  25. package/index.ts +5 -529
  26. package/package.json +6 -1
  27. package/src/client.ts +262 -80
  28. package/src/commands/api-keys.ts +364 -0
  29. package/src/commands/auth.ts +58 -0
  30. package/src/commands/autocomplete.ts +19 -0
  31. package/src/commands/billing.ts +41 -0
  32. package/src/commands/chat.ts +345 -0
  33. package/src/commands/clusters.ts +65 -0
  34. package/src/commands/index.ts +23 -0
  35. package/src/commands/models.ts +63 -0
  36. package/src/commands/users.ts +37 -0
  37. package/src/constants/command-structure.ts +184 -0
  38. package/src/services/api-key-service.ts +36 -5
  39. package/src/services/auth-service.ts +101 -44
  40. package/src/services/chat-service.ts +177 -0
  41. package/src/services/cluster-service.ts +37 -2
  42. package/src/services/collaborator-service.ts +23 -4
  43. package/src/services/flux-service.ts +23 -4
  44. package/src/services/helm-service.ts +22 -3
  45. package/src/services/kubectl-service.ts +28 -5
  46. package/src/types/api.d.ts +58 -192
  47. package/src/utils/config-checker.ts +23 -0
  48. package/src/utils/default-api-key.ts +94 -0
  49. package/src/utils/token-manager.ts +150 -0
package/index.ts CHANGED
@@ -1,11 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { program } from 'commander'
4
- import * as fs from 'fs'
5
- import * as path from 'path'
6
- import { createAuthenticatedClient } from './src/client'
7
- import { handleError } from './src/utils/error-handler'
8
- import chalk from 'chalk'
4
+ import { registerCommands } from './src/commands'
5
+ import { checkBergetConfig } from './src/utils/config-checker'
9
6
 
10
7
  // Set version and description
11
8
  program
@@ -22,531 +19,10 @@ program
22
19
  )
23
20
  .version(process.env.npm_package_version || '0.0.1', '-v, --version')
24
21
  .option('--local', 'Use local API endpoint (hidden)', false)
22
+ .option('--debug', 'Enable debug output', false)
25
23
 
26
- // Import services
27
- import { AuthService } from './src/services/auth-service'
28
- import { ApiKeyService, ApiKey } from './src/services/api-key-service'
29
- import { ClusterService, Cluster } from './src/services/cluster-service'
30
-
31
- // Auth commands
32
- program
33
- .command('login')
34
- .description('Log in to Berget')
35
- .action(async () => {
36
- const authService = AuthService.getInstance()
37
- await authService.login()
38
- })
39
-
40
- program
41
- .command('logout')
42
- .description('Log out from Berget')
43
- .action(() => {
44
- const { clearAuthToken } = require('./src/client')
45
- clearAuthToken()
46
- console.log(chalk.green('You have been logged out from Berget'))
47
- })
48
-
49
- program
50
- .command('whoami')
51
- .description('Show information about the logged in user')
52
- .action(async () => {
53
- try {
54
- const authService = AuthService.getInstance()
55
- const profile = await authService.getUserProfile()
56
-
57
- if (profile) {
58
- console.log(
59
- chalk.bold(`Logged in as: ${profile.name || profile.login}`)
60
- )
61
- console.log(`Email: ${chalk.cyan(profile.email || 'Not available')}`)
62
- console.log(`Role: ${chalk.cyan(profile.role || 'Not available')}`)
63
-
64
- if (profile.company) {
65
- console.log(`Company: ${chalk.cyan(profile.company.name)}`)
66
- }
67
- } else {
68
- console.log(
69
- chalk.yellow('You are not logged in. Use `berget login` to log in.')
70
- )
71
- }
72
- } catch (error) {
73
- handleError('You are not logged in or an error occurred', error)
74
- }
75
- })
76
-
77
- // API Key commands
78
- const apiKey = program.command('api-key').description('Manage API keys')
79
-
80
- apiKey
81
- .command('list')
82
- .description('List all API keys')
83
- .action(async () => {
84
- try {
85
- const apiKeyService = ApiKeyService.getInstance()
86
- const keys = await apiKeyService.listApiKeys()
87
-
88
- if (keys.length === 0) {
89
- console.log(
90
- chalk.yellow(
91
- 'No API keys found. Create one with `berget api-key create --name <name>`'
92
- )
93
- )
94
- return
95
- }
96
-
97
- console.log(chalk.bold('Your API keys:'))
98
- console.log('')
99
-
100
- // Create a table-like format with headers
101
- console.log(
102
- chalk.dim('ID'.padEnd(10)) +
103
- chalk.dim('NAME'.padEnd(25)) +
104
- chalk.dim('PREFIX'.padEnd(12)) +
105
- chalk.dim('STATUS'.padEnd(12)) +
106
- chalk.dim('CREATED'.padEnd(12)) +
107
- chalk.dim('LAST USED')
108
- )
109
-
110
- console.log(chalk.dim('─'.repeat(85)))
111
-
112
- keys.forEach((key: ApiKey) => {
113
- const lastUsed = key.lastUsed ? key.lastUsed.substring(0, 10) : 'Never'
114
- const status = key.active
115
- ? chalk.green('● Active')
116
- : chalk.red('● Inactive')
117
-
118
- console.log(
119
- String(key.id).padEnd(10) +
120
- key.name.padEnd(25) +
121
- key.prefix.padEnd(12) +
122
- status.padEnd(12) +
123
- key.created.substring(0, 10).padEnd(12) +
124
- lastUsed
125
- )
126
- })
127
-
128
- console.log('')
129
- console.log(
130
- chalk.dim(
131
- 'Use `berget api-key create --name <name>` to create a new API key'
132
- )
133
- )
134
- console.log(
135
- chalk.dim('Use `berget api-key delete <id>` to delete an API key')
136
- )
137
- console.log(
138
- chalk.dim('Use `berget api-key rotate <id>` to rotate an API key')
139
- )
140
- } catch (error) {
141
- handleError('Failed to list API keys', error)
142
- }
143
- })
144
-
145
- apiKey
146
- .command('create')
147
- .description('Create a new API key')
148
- .option('--name <name>', 'Name of the API key')
149
- .option('--description <description>', 'Description of the API key')
150
- .action(async (options) => {
151
- try {
152
- if (!options.name) {
153
- console.error(chalk.red('Error: --name is required'))
154
- console.log('')
155
- console.log(
156
- 'Usage: berget api-key create --name <name> [--description <description>]'
157
- )
158
- return
159
- }
160
-
161
- console.log(chalk.blue('Creating API key...'))
162
-
163
- const apiKeyService = ApiKeyService.getInstance()
164
- const result = await apiKeyService.createApiKey({
165
- name: options.name,
166
- description: options.description,
167
- })
168
-
169
- console.log('')
170
- console.log(chalk.green('✓ API key created'))
171
- console.log('')
172
- console.log(chalk.bold('API key details:'))
173
- console.log('')
174
- console.log(`${chalk.dim('ID:')} ${result.id}`)
175
- console.log(`${chalk.dim('Name:')} ${result.name}`)
176
- if (result.description) {
177
- console.log(`${chalk.dim('Description:')} ${result.description}`)
178
- }
179
- console.log(
180
- `${chalk.dim('Created:')} ${new Date(
181
- result.created
182
- ).toLocaleString()}`
183
- )
184
- console.log('')
185
- console.log(chalk.bold('API key:'))
186
- console.log(chalk.cyan(result.key))
187
- console.log('')
188
- console.log(
189
- chalk.yellow('⚠️ IMPORTANT: Save this API key in a secure location.')
190
- )
191
- console.log(chalk.yellow(' It will not be displayed again.'))
192
-
193
- console.log('')
194
- console.log(
195
- chalk.dim(
196
- 'Use this key in your applications to authenticate with the Berget API.'
197
- )
198
- )
199
- } catch (error) {
200
- handleError('Failed to create API key', error)
201
- }
202
- })
203
-
204
- apiKey
205
- .command('delete')
206
- .description('Delete an API key')
207
- .argument('<id>', 'ID of the API key to delete')
208
- .action(async (id) => {
209
- try {
210
- console.log(chalk.blue(`Deleting API key ${id}...`))
211
-
212
- const apiKeyService = ApiKeyService.getInstance()
213
- await apiKeyService.deleteApiKey(id)
214
-
215
- console.log(chalk.green(`✓ API key ${id} has been deleted`))
216
- console.log('')
217
- console.log(
218
- chalk.dim(
219
- 'Applications using this key will no longer be able to authenticate.'
220
- )
221
- )
222
- console.log(
223
- chalk.dim('Use `berget api-key list` to see your remaining API keys.')
224
- )
225
- } catch (error) {
226
- handleError('Failed to delete API key', error)
227
- }
228
- })
229
-
230
- apiKey
231
- .command('rotate')
232
- .description(
233
- 'Rotate an API key (creates a new one and invalidates the old one)'
234
- )
235
- .argument('<id>', 'ID of the API key to rotate')
236
- .action(async (id) => {
237
- try {
238
- console.log(chalk.blue(`Rotating API key ${id}...`))
239
- console.log(
240
- chalk.dim('This will invalidate the old key and generate a new one.')
241
- )
242
-
243
- const apiKeyService = ApiKeyService.getInstance()
244
- const result = await apiKeyService.rotateApiKey(id)
245
-
246
- console.log('')
247
- console.log(chalk.green('✓ API key rotated'))
248
- console.log('')
249
- console.log(chalk.bold('New API key details:'))
250
- console.log('')
251
- console.log(`${chalk.dim('ID:')} ${result.id}`)
252
- console.log(`${chalk.dim('Name:')} ${result.name}`)
253
- if (result.description) {
254
- console.log(`${chalk.dim('Description:')} ${result.description}`)
255
- }
256
- console.log(
257
- `${chalk.dim('Created:')} ${new Date(
258
- result.created
259
- ).toLocaleString()}`
260
- )
261
- console.log('')
262
- console.log(chalk.bold('New API key:'))
263
- console.log(chalk.cyan(result.key))
264
- console.log('')
265
- console.log(
266
- chalk.yellow(
267
- '⚠️ IMPORTANT: Update your applications with this new API key.'
268
- )
269
- )
270
- console.log(
271
- chalk.yellow(
272
- ' The old key has been invalidated and will no longer work.'
273
- )
274
- )
275
- console.log(chalk.yellow(' This new key will not be displayed again.'))
276
- } catch (error) {
277
- handleError('Failed to rotate API key', error)
278
- }
279
- })
280
-
281
- apiKey
282
- .command('usage')
283
- .description('Show usage statistics for an API key')
284
- .argument('<id>', 'ID of the API key')
285
- .option('--start <date>', 'Start date (YYYY-MM-DD)')
286
- .option('--end <date>', 'End date (YYYY-MM-DD)')
287
- .action(async (id, options) => {
288
- try {
289
- console.log(chalk.blue(`Fetching usage statistics for API key ${id}...`))
290
-
291
- const apiKeyService = ApiKeyService.getInstance()
292
- const usage = await apiKeyService.getApiKeyUsage(id)
293
-
294
- console.log('')
295
- console.log(
296
- chalk.bold(`Usage statistics for API key: ${usage.name} (${id})`)
297
- )
298
- console.log('')
299
-
300
- // Period information
301
- console.log(
302
- chalk.dim(`Period: ${usage.period.start} to ${usage.period.end}`)
303
- )
304
- console.log('')
305
-
306
- // Request statistics
307
- console.log(chalk.bold('Request statistics:'))
308
- console.log(
309
- `Total requests: ${chalk.cyan(usage.requests.total.toLocaleString())}`
310
- )
311
-
312
- // Daily breakdown if available
313
- if (usage.requests.daily && usage.requests.daily.length > 0) {
314
- console.log('')
315
- console.log(chalk.bold('Daily breakdown:'))
316
- console.log(chalk.dim('─'.repeat(30)))
317
- console.log(chalk.dim('DATE'.padEnd(12) + 'REQUESTS'))
318
-
319
- usage.requests.daily.forEach((day: { date: string; count: number }) => {
320
- console.log(`${day.date.padEnd(12)}${day.count.toLocaleString()}`)
321
- })
322
- }
323
-
324
- // Model usage if available
325
- if (usage.models && usage.models.length > 0) {
326
- console.log('')
327
- console.log(chalk.bold('Model usage:'))
328
- console.log(chalk.dim('─'.repeat(70)))
329
- console.log(
330
- chalk.dim('MODEL'.padEnd(20)) +
331
- chalk.dim('REQUESTS'.padEnd(10)) +
332
- chalk.dim('INPUT'.padEnd(12)) +
333
- chalk.dim('OUTPUT'.padEnd(12)) +
334
- chalk.dim('TOTAL TOKENS')
335
- )
336
-
337
- usage.models.forEach(
338
- (model: {
339
- name: string
340
- requests: number
341
- tokens: {
342
- input: number
343
- output: number
344
- total: number
345
- }
346
- }) => {
347
- console.log(
348
- model.name.padEnd(20) +
349
- model.requests.toString().padEnd(10) +
350
- model.tokens.input.toLocaleString().padEnd(12) +
351
- model.tokens.output.toLocaleString().padEnd(12) +
352
- model.tokens.total.toLocaleString()
353
- )
354
- }
355
- )
356
- }
357
-
358
- console.log('')
359
- console.log(
360
- chalk.dim(
361
- 'Use these statistics to understand your API usage and optimize your costs.'
362
- )
363
- )
364
- } catch (error) {
365
- handleError('Failed to get API key usage', error)
366
- }
367
- })
368
-
369
- // Cluster commands
370
- const cluster = program.command('cluster').description('Manage Berget clusters')
371
-
372
- // Removed cluster create command as it's not available in the API
373
-
374
- cluster
375
- .command('list')
376
- .description('List all Berget clusters')
377
- .action(async () => {
378
- try {
379
- const clusterService = ClusterService.getInstance()
380
- const clusters = await clusterService.listClusters()
381
-
382
- console.log('NAME STATUS NODES CREATED')
383
- clusters.forEach((cluster: Cluster) => {
384
- console.log(
385
- `${cluster.name.padEnd(22)} ${cluster.status.padEnd(9)} ${String(
386
- cluster.nodes
387
- ).padEnd(8)} ${cluster.created}`
388
- )
389
- })
390
- } catch (error) {
391
- handleError('Failed to list clusters', error)
392
- }
393
- })
394
-
395
- cluster
396
- .command('usage')
397
- .description('Get usage metrics for a specific cluster')
398
- .argument('<clusterId>', 'Cluster ID')
399
- .action(async (clusterId) => {
400
- try {
401
- const clusterService = ClusterService.getInstance()
402
- const usage = await clusterService.getClusterUsage(clusterId)
403
-
404
- console.log('Cluster Usage:')
405
- console.log(JSON.stringify(usage, null, 2))
406
- } catch (error) {
407
- handleError('Failed to get cluster usage', error)
408
- }
409
- })
410
-
411
- // Autocomplete command
412
- program
413
- .command('autocomplete')
414
- .command('install')
415
- .description('Install shell autocompletion')
416
- .action(() => {
417
- console.log(chalk.green('✓ Berget autocomplete installed in your shell'))
418
- console.log(chalk.green('✓ Shell completion for kubectl also installed'))
419
- console.log('')
420
- console.log('Restart your shell or run:')
421
- console.log(' source ~/.bashrc')
422
- })
423
-
424
- // Removed flux commands as they're not available in the API
425
-
426
- // Removed collaborator commands as they're not available in the API
427
-
428
- // Removed helm commands as they're not available in the API
429
-
430
- // Removed kubernetes-like commands as they're not available in the API
431
-
432
- // Add token usage command
433
- program
434
- .command('token-usage')
435
- .description('Get token usage statistics')
436
- .option('--model <modelId>', 'Get usage for a specific model')
437
- .action(async (options) => {
438
- try {
439
- const client = createAuthenticatedClient()
440
- let response
441
-
442
- if (options.model) {
443
- const { data, error } = await client.GET('/v1/usage/tokens/{modelId}', {
444
- params: { path: { modelId: options.model } },
445
- })
446
- if (error) throw new Error(JSON.stringify(error))
447
- response = data
448
- } else {
449
- const { data, error } = await client.GET('/v1/usage/tokens')
450
- if (error) throw new Error(JSON.stringify(error))
451
- response = data
452
- }
453
-
454
- console.log('Token Usage:')
455
- console.log(JSON.stringify(response, null, 2))
456
- } catch (error) {
457
- handleError('Failed to get token usage', error)
458
- }
459
- })
460
-
461
- // Add models command
462
- program
463
- .command('models')
464
- .description('List available AI models')
465
- .option('--id <modelId>', 'Get details for a specific model')
466
- .action(async (options) => {
467
- try {
468
- const client = createAuthenticatedClient()
469
- let response
470
-
471
- if (options.id) {
472
- const { data, error } = await client.GET('/v1/models/{modelId}', {
473
- params: { path: { modelId: options.id } },
474
- })
475
- if (error) throw new Error(JSON.stringify(error))
476
- response = data
477
-
478
- console.log('Model Details:')
479
- console.log(JSON.stringify(response, null, 2))
480
- } else {
481
- const { data, error } = await client.GET('/v1/models')
482
- if (error) throw new Error(JSON.stringify(error))
483
- response = data
484
-
485
- console.log('Available Models:')
486
- console.log(
487
- 'ID OWNED BY CAPABILITIES'
488
- )
489
- response.data.forEach((model: any) => {
490
- const capabilities = []
491
- if (model.capabilities.vision) capabilities.push('vision')
492
- if (model.capabilities.function_calling)
493
- capabilities.push('function_calling')
494
- if (model.capabilities.json_mode) capabilities.push('json_mode')
495
-
496
- console.log(
497
- `${model.id.padEnd(24)} ${model.owned_by.padEnd(
498
- 25
499
- )} ${capabilities.join(', ')}`
500
- )
501
- })
502
- }
503
- } catch (error) {
504
- handleError('Failed to get models', error)
505
- }
506
- })
507
-
508
- // Add team command
509
- program
510
- .command('team')
511
- .description('Manage team members')
512
- .action(async () => {
513
- try {
514
- const client = createAuthenticatedClient()
515
- const { data, error } = await client.GET('/v1/users')
516
- if (error) throw new Error(JSON.stringify(error))
517
-
518
- console.log('Team Members:')
519
- console.log(
520
- 'NAME EMAIL ROLE'
521
- )
522
- data.forEach((user: any) => {
523
- console.log(
524
- `${user.name.padEnd(24)} ${user.email.padEnd(30)} ${user.role}`
525
- )
526
- })
527
- } catch (error) {
528
- handleError('Failed to list team members', error)
529
- }
530
- })
531
-
532
- // Auto-detect .bergetconfig and switch clusters
533
- const checkBergetConfig = () => {
534
- const configPath = path.join(process.cwd(), '.bergetconfig')
535
- if (fs.existsSync(configPath)) {
536
- try {
537
- const config = fs.readFileSync(configPath, 'utf8')
538
- const match = config.match(/cluster:\s*(.+)/)
539
- if (match && match[1]) {
540
- const clusterName = match[1].trim()
541
- console.log(`🔄 Berget: Switched to cluster "${clusterName}"`)
542
- console.log('✓ kubectl config updated')
543
- console.log('')
544
- }
545
- } catch (error) {
546
- // Silently ignore errors reading config
547
- }
548
- }
549
- }
24
+ // Register all commands
25
+ registerCommands(program)
550
26
 
551
27
  // Check for .bergetconfig if not running a command
552
28
  if (process.argv.length <= 2) {
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "berget",
3
- "version": "0.1.0",
3
+ "version": "1.1.0",
4
4
  "main": "dist/index.js",
5
5
  "bin": {
6
6
  "berget": "dist/index.js"
7
7
  },
8
8
  "private": false,
9
9
  "scripts": {
10
+ "start": "node --import tsx ./index.ts --local",
11
+ "login": "node --import tsx ./index.ts --local auth login",
12
+ "logout": "node --import tsx ./index.ts --local auth logout",
13
+ "whoami": "node --import tsx ./index.ts --local auth whoami",
10
14
  "build": "tsc",
11
15
  "prepublishOnly": "npm run build",
12
16
  "generate-types": "openapi-typescript https://api.berget.ai/openapi.json -o src/types/api.d.ts"
@@ -16,6 +20,7 @@
16
20
  "description": "This is a cli command for interacting with the AI infrastructure provider Berget",
17
21
  "devDependencies": {
18
22
  "@types/node": "^20.11.20",
23
+ "tsx": "^4.19.3",
19
24
  "typescript": "^5.3.3"
20
25
  },
21
26
  "dependencies": {