berget 2.0.2 → 2.0.4

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.
@@ -11,39 +11,13 @@ import path from 'path'
11
11
  import { spawn } from 'child_process'
12
12
  import { updateEnvFile } from '../utils/env-manager'
13
13
  import { createAuthenticatedClient } from '../client'
14
-
15
- // Centralized model configuration
16
- const MODEL_CONFIG = {
17
- // Model names used in agent configurations (with provider prefix)
18
- AGENT_MODELS: {
19
- primary: 'berget/deepseek-r1',
20
- small: 'berget/gpt-oss',
21
- },
22
- // Model definitions in provider configuration (without prefix)
23
- PROVIDER_MODELS: {
24
- 'deepseek-r1': {
25
- name: 'GLM-4.6',
26
- limit: {
27
- output: 4000,
28
- context: 90000,
29
- },
30
- },
31
- 'gpt-oss': {
32
- name: 'GPT-OSS',
33
- limit: {
34
- output: 4000,
35
- context: 128000,
36
- },
37
- },
38
- 'llama-8b': {
39
- name: 'llama-3.1-8b',
40
- limit: {
41
- output: 4000,
42
- context: 128000,
43
- },
44
- },
45
- },
46
- }
14
+ import {
15
+ getConfigLoader,
16
+ getModelConfig,
17
+ getProviderModels,
18
+ type OpenCodeConfig,
19
+ type AgentConfig
20
+ } from '../utils/config-loader'
47
21
 
48
22
  /**
49
23
  * Check if current directory has git
@@ -65,6 +39,7 @@ async function mergeConfigurations(
65
39
  ): Promise<any> {
66
40
  try {
67
41
  const client = createAuthenticatedClient()
42
+ const modelConfig = getModelConfig()
68
43
 
69
44
  console.log(chalk.blue('🤖 Using AI to merge configurations...'))
70
45
 
@@ -87,7 +62,7 @@ Return ONLY the merged JSON configuration, no explanations.`
87
62
 
88
63
  const response = await client.POST('/v1/chat/completions', {
89
64
  body: {
90
- model: MODEL_CONFIG.AGENT_MODELS.primary,
65
+ model: modelConfig.primary,
91
66
  messages: [
92
67
  {
93
68
  role: 'user',
@@ -297,6 +272,21 @@ function getProjectName(): string {
297
272
  return path.basename(process.cwd())
298
273
  }
299
274
 
275
+ /**
276
+ * Load the latest agent configuration from opencode.json
277
+ */
278
+ async function loadLatestAgentConfig(): Promise<any> {
279
+ try {
280
+ const configPath = path.join(__dirname, '../../opencode.json')
281
+ const configContent = await readFile(configPath, 'utf8')
282
+ const config = JSON.parse(configContent)
283
+ return config.agent || {}
284
+ } catch (error) {
285
+ console.warn(chalk.yellow('⚠️ Could not load latest agent config, using fallback'))
286
+ return {}
287
+ }
288
+ }
289
+
300
290
  /**
301
291
  * Check if opencode is installed
302
292
  */
@@ -640,6 +630,10 @@ export function registerCodeCommands(program: Command): void {
640
630
  // Prepare .env file path for safe update
641
631
  const envPath = path.join(process.cwd(), '.env')
642
632
 
633
+ // Load latest agent configuration to ensure consistency
634
+ const latestAgentConfig = await loadLatestAgentConfig()
635
+ const modelConfig = getModelConfig()
636
+
643
637
  // Create opencode.json config with optimized agent-based format
644
638
  const config = {
645
639
  $schema: 'https://opencode.ai/config.json',
@@ -647,11 +641,11 @@ export function registerCodeCommands(program: Command): void {
647
641
  theme: 'berget-dark',
648
642
  share: 'manual',
649
643
  autoupdate: true,
650
- model: MODEL_CONFIG.AGENT_MODELS.primary,
651
- small_model: MODEL_CONFIG.AGENT_MODELS.small,
644
+ model: modelConfig.primary,
645
+ small_model: modelConfig.small,
652
646
  agent: {
653
647
  fullstack: {
654
- model: MODEL_CONFIG.AGENT_MODELS.primary,
648
+ model: modelConfig.primary,
655
649
  temperature: 0.3,
656
650
  top_p: 0.9,
657
651
  mode: 'primary',
@@ -662,7 +656,7 @@ export function registerCodeCommands(program: Command): void {
662
656
  'Voice: Scandinavian calm—precise, concise, confident; no fluff. You are Berget Code Fullstack agent. Act as a router and coordinator in a monorepo. Bottom-up schema: database → OpenAPI → generated types. Top-down types: API → UI → components. Use openapi-fetch and Zod at every boundary; compile-time errors are desired when contracts change. Routing rules: if task/paths match /apps/frontend or React (.tsx) → use frontend; if /apps/app or Expo/React Native → app; if /infra, /k8s, flux-system, kustomization.yaml, Helm values → devops; if /services, Koa routers, services/adapters/domain → backend. If ambiguous, remain fullstack and outline the end-to-end plan, then delegate subtasks to the right persona. Security: validate inputs; secrets via FluxCD SOPS/Sealed Secrets. Documentation is generated from code—never duplicated. CRITICAL: When all implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
663
657
  },
664
658
  frontend: {
665
- model: MODEL_CONFIG.AGENT_MODELS.primary,
659
+ model: modelConfig.primary,
666
660
  temperature: 0.4,
667
661
  top_p: 0.9,
668
662
  mode: 'primary',
@@ -674,7 +668,7 @@ export function registerCodeCommands(program: Command): void {
674
668
  'You are Berget Code Frontend agent. Voice: Scandinavian calm—precise, concise, confident. React 18 + TypeScript. Tailwind + Shadcn UI only via the design system (index.css, tailwind.config.ts). Use semantic tokens for color/spacing/typography/motion; never ad-hoc classes or inline colors. Components are pure and responsive; props-first data; minimal global state (Zustand/Jotai). Accessibility and keyboard navigation mandatory. Mock data only at init under /data via typed hooks (e.g., useProducts() reading /data/products.json). Design: minimal, balanced, quiet motion. CRITICAL: When all frontend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
675
669
  },
676
670
  backend: {
677
- model: MODEL_CONFIG.AGENT_MODELS.primary,
671
+ model: modelConfig.primary,
678
672
  temperature: 0.3,
679
673
  top_p: 0.9,
680
674
  mode: 'primary',
@@ -684,8 +678,9 @@ export function registerCodeCommands(program: Command): void {
684
678
  prompt:
685
679
  'You are Berget Code Backend agent. Voice: Scandinavian calm—precise, concise, confident. TypeScript + Koa. Prefer many small pure functions; avoid big try/catch blocks. Routes thin; logic in services/adapters/domain. Validate with Zod; auto-generate OpenAPI. Adapters isolate external systems; domain never depends on framework. Test with supertest; idempotent and stateless by default. Each microservice emits an OpenAPI contract; changes propagate upward to types. Code Quality & Refactoring Principles: Apply Single Responsibility Principle, fail fast with explicit errors, eliminate code duplication, remove nested complexity, use descriptive error codes, keep functions under 30 lines. Always leave code cleaner and more readable than you found it. CRITICAL: When all backend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
686
680
  },
687
- devops: {
688
- model: MODEL_CONFIG.AGENT_MODELS.primary,
681
+ // Use centralized devops configuration with Helm guidelines
682
+ devops: latestAgentConfig.devops || {
683
+ model: modelConfig.primary,
689
684
  temperature: 0.3,
690
685
  top_p: 0.8,
691
686
  mode: 'primary',
@@ -696,7 +691,7 @@ export function registerCodeCommands(program: Command): void {
696
691
  'You are Berget Code DevOps agent. Voice: Scandinavian calm—precise, concise, confident. Start simple: k8s/{deployment,service,ingress}. Add FluxCD sync to repo and image automation. Use Kustomize bases/overlays (staging, production). Add dependencies via Helm from upstream sources; prefer native operators when available (CloudNativePG, cert-manager, external-dns). SemVer with -rc tags keeps CI environments current. Observability with Prometheus/Grafana. No manual kubectl in production—Git is the source of truth.',
697
692
  },
698
693
  app: {
699
- model: MODEL_CONFIG.AGENT_MODELS.primary,
694
+ model: modelConfig.primary,
700
695
  temperature: 0.4,
701
696
  top_p: 0.9,
702
697
  mode: 'primary',
@@ -708,7 +703,7 @@ export function registerCodeCommands(program: Command): void {
708
703
  'You are Berget Code App agent. Voice: Scandinavian calm—precise, concise, confident. Expo + React Native + TypeScript. Structure by components/hooks/services/navigation. Components are pure; data via props; refactor shared logic into hooks/stores. Share tokens with frontend. Mock data in /data via typed hooks; later replace with live APIs. Offline via SQLite/MMKV; notifications via Expo. Request permissions only when needed. Subtle, meaningful motion; light/dark parity.',
709
704
  },
710
705
  security: {
711
- model: MODEL_CONFIG.AGENT_MODELS.primary,
706
+ model: modelConfig.primary,
712
707
  temperature: 0.2,
713
708
  top_p: 0.8,
714
709
  mode: 'subagent',
@@ -719,7 +714,7 @@ export function registerCodeCommands(program: Command): void {
719
714
  'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Security agent. Expert in application security, penetration testing, and OWASP standards. Core responsibilities: Conduct security assessments and penetration tests, Validate OWASP Top 10 compliance, Review code for security vulnerabilities, Implement security headers and Content Security Policy (CSP), Audit API security, Check for sensitive data exposure, Validate input sanitization and output encoding, Assess dependency security and supply chain risks. Tools and techniques: OWASP ZAP, Burp Suite, security linters, dependency scanners, manual code review. Always provide specific, actionable security recommendations with priority levels.',
720
715
  },
721
716
  quality: {
722
- model: MODEL_CONFIG.AGENT_MODELS.primary,
717
+ model: modelConfig.primary,
723
718
  temperature: 0.1,
724
719
  top_p: 0.9,
725
720
  mode: 'subagent',
@@ -781,7 +776,7 @@ export function registerCodeCommands(program: Command): void {
781
776
  baseURL: 'https://api.berget.ai/v1',
782
777
  apiKey: '{env:BERGET_API_KEY}',
783
778
  },
784
- models: MODEL_CONFIG.PROVIDER_MODELS,
779
+ models: getProviderModels(),
785
780
  },
786
781
  },
787
782
  }
@@ -908,6 +903,12 @@ Declarative GitOps infrastructure with FluxCD, Kustomize, Helm, and operators.
908
903
  - Operator-first approach
909
904
  - SemVer with release candidates
910
905
 
906
+ **Helm Values Configuration Process:**
907
+ 1. Documentation First Approach: Always fetch official documentation from Artifact Hub/GitHub for the specific chart version before writing values. Search Artifact Hub for exact chart version documentation, check the chart's GitHub repository for official docs and examples, verify the exact version being used in the deployment.
908
+ 2. Validation Requirements: Check for available validation schemas before committing YAML files. Use Helm's built-in validation tools (helm lint, helm template). Validate against JSON schema if available for the chart. Ensure YAML syntax correctness with linters.
909
+ 3. Standard Workflow: Identify chart name and exact version. Fetch official documentation from Artifact Hub/GitHub. Check for available schemas and validation tools. Write values according to official documentation. Validate against schema (if available). Test with helm template or helm lint. Commit validated YAML files.
910
+ 4. Quality Assurance: Never commit unvalidated Helm values. Use helm dependency update when adding new charts. Test rendering with helm template --dry-run before deployment. Document any custom values with comments referencing official docs.
911
+
911
912
  #### app
912
913
  Expo + React Native applications with props-first architecture and offline awareness.
913
914
 
@@ -1103,7 +1104,6 @@ All agents follow these principles:
1103
1104
 
1104
1105
  // Set environment variables for opencode
1105
1106
  const env = { ...process.env }
1106
- env.OPENCODE_API_KEY = config.apiKey
1107
1107
 
1108
1108
  // Prepare opencode command
1109
1109
  const opencodeArgs: string[] = []
@@ -1146,6 +1146,56 @@ All agents follow these principles:
1146
1146
  }
1147
1147
  })
1148
1148
 
1149
+ code
1150
+ .command(SUBCOMMANDS.CODE.SERVE)
1151
+ .description('Start OpenCode web server')
1152
+ .option('-p, --port <port>', 'Port to run the server on (default: 3000)')
1153
+ .option('-h, --host <host>', 'Host to bind the server to (default: localhost)')
1154
+ .option(
1155
+ '-y, --yes',
1156
+ 'Automatically answer yes to all prompts (for automation)',
1157
+ )
1158
+ .action(async (options) => {
1159
+ try {
1160
+ // Ensure opencode is installed
1161
+ if (!(await ensureOpencodeInstalled(options.yes))) {
1162
+ return
1163
+ }
1164
+
1165
+ console.log(chalk.cyan('🚀 Starting OpenCode web server...'))
1166
+
1167
+ // Prepare opencode serve command
1168
+ const serveArgs: string[] = ['serve']
1169
+
1170
+ if (options.port) {
1171
+ serveArgs.push('--port', options.port)
1172
+ }
1173
+
1174
+ if (options.host) {
1175
+ serveArgs.push('--host', options.host)
1176
+ }
1177
+
1178
+ // Spawn opencode serve process
1179
+ const opencode = spawn('opencode', serveArgs, {
1180
+ stdio: 'inherit',
1181
+ shell: true,
1182
+ })
1183
+
1184
+ opencode.on('close', (code) => {
1185
+ if (code !== 0) {
1186
+ console.log(chalk.red(`OpenCode server exited with code ${code}`))
1187
+ }
1188
+ })
1189
+
1190
+ opencode.on('error', (error) => {
1191
+ console.error(chalk.red('Failed to start OpenCode server:'))
1192
+ console.error(error.message)
1193
+ })
1194
+ } catch (error) {
1195
+ handleError('Failed to start OpenCode server', error)
1196
+ }
1197
+ })
1198
+
1149
1199
  code
1150
1200
  .command(SUBCOMMANDS.CODE.UPDATE)
1151
1201
  .description('Update OpenCode and agents to latest versions')
@@ -1196,6 +1246,10 @@ All agents follow these principles:
1196
1246
  ),
1197
1247
  )
1198
1248
 
1249
+ // Load latest agent configuration to ensure consistency
1250
+ const latestAgentConfig = await loadLatestAgentConfig()
1251
+ const modelConfig = getModelConfig()
1252
+
1199
1253
  // Create latest configuration with all improvements
1200
1254
  const latestConfig = {
1201
1255
  $schema: 'https://opencode.ai/config.json',
@@ -1203,11 +1257,11 @@ All agents follow these principles:
1203
1257
  theme: 'berget-dark',
1204
1258
  share: 'manual',
1205
1259
  autoupdate: true,
1206
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1207
- small_model: MODEL_CONFIG.AGENT_MODELS.small,
1260
+ model: modelConfig.primary,
1261
+ small_model: modelConfig.small,
1208
1262
  agent: {
1209
1263
  fullstack: {
1210
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1264
+ model: modelConfig.primary,
1211
1265
  temperature: 0.3,
1212
1266
  top_p: 0.9,
1213
1267
  mode: 'primary',
@@ -1218,7 +1272,7 @@ All agents follow these principles:
1218
1272
  'Voice: Scandinavian calm—precise, concise, confident; no fluff. You are Berget Code Fullstack agent. Act as a router and coordinator in a monorepo. Bottom-up schema: database → OpenAPI → generated types. Top-down types: API → UI → components. Use openapi-fetch and Zod at every boundary; compile-time errors are desired when contracts change. Routing rules: if task/paths match /apps/frontend or React (.tsx) → use frontend; if /apps/app or Expo/React Native → app; if /infra, /k8s, flux-system, kustomization.yaml, Helm values → devops; if /services, Koa routers, services/adapters/domain → backend. If ambiguous, remain fullstack and outline the end-to-end plan, then delegate subtasks to the right persona. Security: validate inputs; secrets via FluxCD SOPS/Sealed Secrets. Documentation is generated from code—never duplicated. CRITICAL: When all implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
1219
1273
  },
1220
1274
  frontend: {
1221
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1275
+ model: modelConfig.primary,
1222
1276
  temperature: 0.4,
1223
1277
  top_p: 0.9,
1224
1278
  mode: 'primary',
@@ -1230,7 +1284,7 @@ All agents follow these principles:
1230
1284
  'You are Berget Code Frontend agent. Voice: Scandinavian calm—precise, concise, confident. React 18 + TypeScript. Tailwind + Shadcn UI only via the design system (index.css, tailwind.config.ts). Use semantic tokens for color/spacing/typography/motion; never ad-hoc classes or inline colors. Components are pure and responsive; props-first data; minimal global state (Zustand/Jotai). Accessibility and keyboard navigation mandatory. Mock data only at init under /data via typed hooks (e.g., useProducts() reading /data/products.json). Design: minimal, balanced, quiet motion. CRITICAL: When all frontend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
1231
1285
  },
1232
1286
  backend: {
1233
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1287
+ model: modelConfig.primary,
1234
1288
  temperature: 0.3,
1235
1289
  top_p: 0.9,
1236
1290
  mode: 'primary',
@@ -1240,8 +1294,9 @@ All agents follow these principles:
1240
1294
  prompt:
1241
1295
  'You are Berget Code Backend agent. Voice: Scandinavian calm—precise, concise, confident. TypeScript + Koa. Prefer many small pure functions; avoid big try/catch blocks. Routes thin; logic in services/adapters/domain. Validate with Zod; auto-generate OpenAPI. Adapters isolate external systems; domain never depends on framework. Test with supertest; idempotent and stateless by default. Each microservice emits an OpenAPI contract; changes propagate upward to types. Code Quality & Refactoring Principles: Apply Single Responsibility Principle, fail fast with explicit errors, eliminate code duplication, remove nested complexity, use descriptive error codes, keep functions under 30 lines. Always leave code cleaner and more readable than you found it. CRITICAL: When all backend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
1242
1296
  },
1243
- devops: {
1244
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1297
+ // Use centralized devops configuration with Helm guidelines
1298
+ devops: latestAgentConfig.devops || {
1299
+ model: modelConfig.primary,
1245
1300
  temperature: 0.3,
1246
1301
  top_p: 0.8,
1247
1302
  mode: 'primary',
@@ -1252,7 +1307,7 @@ All agents follow these principles:
1252
1307
  'You are Berget Code DevOps agent. Voice: Scandinavian calm—precise, concise, confident. Start simple: k8s/{deployment,service,ingress}. Add FluxCD sync to repo and image automation. Use Kustomize bases/overlays (staging, production). Add dependencies via Helm from upstream sources; prefer native operators when available (CloudNativePG, cert-manager, external-dns). SemVer with -rc tags keeps CI environments current. Observability with Prometheus/Grafana. No manual kubectl in production—Git is the source of truth. For testing, building, and PR management, use @quality subagent.',
1253
1308
  },
1254
1309
  app: {
1255
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1310
+ model: modelConfig.primary,
1256
1311
  temperature: 0.4,
1257
1312
  top_p: 0.9,
1258
1313
  mode: 'primary',
@@ -1264,7 +1319,7 @@ All agents follow these principles:
1264
1319
  'You are Berget Code App agent. Voice: Scandinavian calm—precise, concise, confident. Expo + React Native + TypeScript. Structure by components/hooks/services/navigation. Components are pure; data via props; refactor shared logic into hooks/stores. Share tokens with frontend. Mock data in /data via typed hooks; later replace with live APIs. Offline via SQLite/MMKV; notifications via Expo. Request permissions only when needed. Subtle, meaningful motion; light/dark parity. For testing, building, and PR management, use @quality subagent.',
1265
1320
  },
1266
1321
  security: {
1267
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1322
+ model: modelConfig.primary,
1268
1323
  temperature: 0.2,
1269
1324
  top_p: 0.8,
1270
1325
  mode: 'subagent',
@@ -1275,7 +1330,7 @@ All agents follow these principles:
1275
1330
  'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Security agent. Expert in application security, penetration testing, and OWASP standards. Core responsibilities: Conduct security assessments and penetration tests, Validate OWASP Top 10 compliance, Review code for security vulnerabilities, Implement security headers and Content Security Policy (CSP), Audit API security, Check for sensitive data exposure, Validate input sanitization and output encoding, Assess dependency security and supply chain risks. Tools and techniques: OWASP ZAP, Burp Suite, security linters, dependency scanners, manual code review. Always provide specific, actionable security recommendations with priority levels. Workflow: Always follow branch_strategy and commit_convention from workflow section. Never work directly in main. Agent awareness: Review code from all personas (frontend, backend, app, devops). If implementation changes are needed, suggest <tab> to switch to appropriate persona after security assessment.',
1276
1331
  },
1277
1332
  quality: {
1278
- model: MODEL_CONFIG.AGENT_MODELS.primary,
1333
+ model: modelConfig.primary,
1279
1334
  temperature: 0.1,
1280
1335
  top_p: 0.9,
1281
1336
  mode: 'subagent',
@@ -1343,7 +1398,7 @@ All agents follow these principles:
1343
1398
  baseURL: 'https://api.berget.ai/v1',
1344
1399
  apiKey: '{env:BERGET_API_KEY}',
1345
1400
  },
1346
- models: MODEL_CONFIG.PROVIDER_MODELS,
1401
+ models: getProviderModels(),
1347
1402
  },
1348
1403
  },
1349
1404
  }
@@ -1389,7 +1444,7 @@ All agents follow these principles:
1389
1444
 
1390
1445
  // Check for GLM-4.6 optimizations
1391
1446
  if (
1392
- !currentConfig.provider?.berget?.models?.[MODEL_CONFIG.AGENT_MODELS.primary.replace('berget/', '')]?.limit?.context
1447
+ !currentConfig.provider?.berget?.models?.[modelConfig.primary.replace('berget/', '')]?.limit?.context
1393
1448
  ) {
1394
1449
  console.log(
1395
1450
  chalk.cyan(' • GLM-4.6 token limits and auto-compaction'),
@@ -1556,6 +1611,12 @@ Declarative GitOps infrastructure with FluxCD, Kustomize, Helm, and operators.
1556
1611
  - Operator-first approach
1557
1612
  - SemVer with release candidates
1558
1613
 
1614
+ **Helm Values Configuration Process:**
1615
+ 1. Documentation First Approach: Always fetch official documentation from Artifact Hub/GitHub for the specific chart version before writing values. Search Artifact Hub for exact chart version documentation, check the chart's GitHub repository for official docs and examples, verify the exact version being used in the deployment.
1616
+ 2. Validation Requirements: Check for available validation schemas before committing YAML files. Use Helm's built-in validation tools (helm lint, helm template). Validate against JSON schema if available for the chart. Ensure YAML syntax correctness with linters.
1617
+ 3. Standard Workflow: Identify chart name and exact version. Fetch official documentation from Artifact Hub/GitHub. Check for available schemas and validation tools. Write values according to official documentation. Validate against schema (if available). Test with helm template or helm lint. Commit validated YAML files.
1618
+ 4. Quality Assurance: Never commit unvalidated Helm values. Use helm dependency update when adding new charts. Test rendering with helm template --dry-run before deployment. Document any custom values with comments referencing official docs.
1619
+
1559
1620
  #### app
1560
1621
  Expo + React Native applications with props-first architecture and offline awareness.
1561
1622
 
@@ -39,6 +39,7 @@ export const SUBCOMMANDS = {
39
39
  INIT: 'init',
40
40
  RUN: 'run',
41
41
  UPDATE: 'update',
42
+ SERVE: 'serve',
42
43
  },
43
44
 
44
45
  // API Keys commands
@@ -233,6 +234,7 @@ export const COMMAND_DESCRIPTIONS = {
233
234
  [`${COMMAND_GROUPS.CODE} ${SUBCOMMANDS.CODE.INIT}`]:
234
235
  'Initialize project for AI coding assistant',
235
236
  [`${COMMAND_GROUPS.CODE} ${SUBCOMMANDS.CODE.RUN}`]: 'Run AI coding assistant',
237
+ [`${COMMAND_GROUPS.CODE} ${SUBCOMMANDS.CODE.SERVE}`]: 'Start OpenCode web server',
236
238
  [`${COMMAND_GROUPS.CODE} ${SUBCOMMANDS.CODE.UPDATE}`]:
237
239
  'Update OpenCode and agents to latest versions',
238
240
  }
@@ -70,13 +70,111 @@ export class ApiKeyService {
70
70
  */
71
71
  public async create(options: CreateApiKeyOptions): Promise<ApiKeyResponse> {
72
72
  try {
73
+ // Validate input before sending request
74
+ if (!options.name || options.name.trim().length === 0) {
75
+ throw new Error('API key name is required and cannot be empty')
76
+ }
77
+
78
+ if (options.name.length > 100) {
79
+ throw new Error('API key name must be 100 characters or less')
80
+ }
81
+
82
+ if (options.description && options.description.length > 500) {
83
+ throw new Error('API key description must be 500 characters or less')
84
+ }
85
+
73
86
  const { data, error } = await this.client.POST('/v1/api-keys', {
74
87
  body: options,
75
88
  })
76
- if (error) throw new Error(JSON.stringify(error))
77
- return data!
89
+
90
+ if (error) {
91
+ // Enhanced error handling with specific troubleshooting
92
+
93
+ // Handle specific error cases
94
+ if (typeof error === 'object' && error !== null) {
95
+ const errorObj = error as any
96
+
97
+ if (errorObj.error?.code === 'API_KEY_CREATION_FAILED') {
98
+ let detailedMessage =
99
+ 'Failed to create API key. This could be due to:\n'
100
+ detailedMessage += '• Account limits or quota restrictions\n'
101
+ detailedMessage +=
102
+ '• Insufficient permissions for API key creation\n'
103
+ detailedMessage += '• Temporary server issues\n'
104
+ detailedMessage += '• Billing or subscription issues\n\n'
105
+ detailedMessage += 'Troubleshooting steps:\n'
106
+ detailedMessage +=
107
+ '1. Check if you have reached your API key limit\n'
108
+ detailedMessage +=
109
+ '2. Verify your account has API key creation permissions\n'
110
+ detailedMessage += '3. Check your billing status and subscription\n'
111
+ detailedMessage +=
112
+ '4. Try again in a few minutes if this is a temporary issue\n'
113
+ detailedMessage += '5. Contact support if the problem persists'
114
+
115
+ throw new Error(detailedMessage)
116
+ }
117
+
118
+ if (errorObj.error?.code === 'QUOTA_EXCEEDED') {
119
+ throw new Error(
120
+ 'You have reached your API key limit. Please delete existing keys or contact support to increase your quota.',
121
+ )
122
+ }
123
+
124
+ if (errorObj.error?.code === 'INSUFFICIENT_PERMISSIONS') {
125
+ throw new Error(
126
+ 'Your account does not have permission to create API keys. Please contact your administrator.',
127
+ )
128
+ }
129
+
130
+ if (errorObj.error?.code === 'BILLING_REQUIRED') {
131
+ throw new Error(
132
+ 'A valid billing method is required to create API keys. Please add a payment method.',
133
+ )
134
+ }
135
+ }
136
+
137
+ throw new Error(JSON.stringify(error))
138
+ }
139
+
140
+ if (!data) {
141
+ throw new Error('No data received from server')
142
+ }
143
+
144
+ return data
78
145
  } catch (error) {
79
146
  console.error('Failed to create API key:', error)
147
+
148
+ // Add additional context for common issues
149
+ if (error instanceof Error) {
150
+ if (error.message.includes('ECONNREFUSED')) {
151
+ throw new Error(
152
+ 'Cannot connect to Berget API. Please check your internet connection.',
153
+ )
154
+ }
155
+
156
+ if (error.message.includes('ENOTFOUND')) {
157
+ throw new Error(
158
+ 'Cannot resolve Berget API hostname. Please check your DNS settings.',
159
+ )
160
+ }
161
+
162
+ if (
163
+ error.message.includes('401') ||
164
+ error.message.includes('Unauthorized')
165
+ ) {
166
+ throw new Error(
167
+ 'Authentication failed. Please run `berget auth login` to log in again.',
168
+ )
169
+ }
170
+
171
+ if (error.message.includes('403')) {
172
+ throw new Error(
173
+ 'Access forbidden. Your account may not have permission to create API keys.',
174
+ )
175
+ }
176
+ }
177
+
80
178
  throw error
81
179
  }
82
180
  }
@@ -82,6 +82,23 @@ export class ChatService {
82
82
 
83
83
  const headers: Record<string, string> = {}
84
84
 
85
+ // First try to use the authenticated client (with refresh token support)
86
+ // Only fall back to API key flow if explicitly requested or no auth tokens available
87
+ const { TokenManager } = await import('../utils/token-manager')
88
+ const tokenManagerInstance = TokenManager.getInstance()
89
+ const hasValidAuth = tokenManagerInstance.getAccessToken() && !tokenManagerInstance.isTokenExpired()
90
+
91
+ const envApiKeyForAuth = process.env.BERGET_API_KEY
92
+ const hasExplicitApiKey = !!optionsCopy.apiKey || !!envApiKeyForAuth
93
+
94
+ // If we have valid auth tokens and no explicit API key, use authenticated client
95
+ if (hasValidAuth && !hasExplicitApiKey) {
96
+ logger.debug('Using authenticated client with refresh token support')
97
+ // Create a copy without apiKey to let the authenticated client handle auth automatically
98
+ const { apiKey, ...optionsWithoutKey } = optionsCopy
99
+ return this.executeCompletion(optionsWithoutKey, {})
100
+ }
101
+
85
102
  // Check for environment variables first - prioritize this over everything else
86
103
  const envApiKey = process.env.BERGET_API_KEY
87
104
  if (envApiKey) {