berget 2.2.6 → 2.2.8

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 (145) hide show
  1. package/.github/workflows/publish.yml +2 -2
  2. package/.github/workflows/test.yml +10 -4
  3. package/.husky/pre-commit +1 -0
  4. package/.prettierignore +15 -0
  5. package/.prettierrc +7 -3
  6. package/CONTRIBUTING.md +38 -0
  7. package/README.md +2 -148
  8. package/dist/index.js +10 -11
  9. package/dist/package.json +30 -2
  10. package/dist/src/agents/app.js +28 -0
  11. package/dist/src/agents/backend.js +25 -0
  12. package/dist/src/agents/devops.js +34 -0
  13. package/dist/src/agents/frontend.js +25 -0
  14. package/dist/src/agents/fullstack.js +25 -0
  15. package/dist/src/agents/index.js +61 -0
  16. package/dist/src/agents/quality.js +70 -0
  17. package/dist/src/agents/security.js +26 -0
  18. package/dist/src/agents/types.js +2 -0
  19. package/dist/src/client.js +97 -117
  20. package/dist/src/commands/api-keys.js +75 -90
  21. package/dist/src/commands/auth.js +7 -16
  22. package/dist/src/commands/autocomplete.js +1 -1
  23. package/dist/src/commands/billing.js +6 -17
  24. package/dist/src/commands/chat.js +68 -101
  25. package/dist/src/commands/clusters.js +9 -18
  26. package/dist/src/commands/code/__tests__/auth-sync.test.js +351 -0
  27. package/dist/src/commands/code/__tests__/fake-api-key-service.js +13 -0
  28. package/dist/src/commands/code/__tests__/fake-auth-service.js +47 -0
  29. package/dist/src/commands/code/__tests__/fake-command-runner.js +21 -34
  30. package/dist/src/commands/code/__tests__/fake-file-store.js +20 -33
  31. package/dist/src/commands/code/__tests__/fake-prompter.js +83 -57
  32. package/dist/src/commands/code/__tests__/setup-flow.test.js +359 -92
  33. package/dist/src/commands/code/adapters/clack-prompter.js +15 -22
  34. package/dist/src/commands/code/adapters/fs-file-store.js +26 -40
  35. package/dist/src/commands/code/adapters/spawn-command-runner.js +27 -37
  36. package/dist/src/commands/code/auth-sync.js +270 -0
  37. package/dist/src/commands/code/errors.js +12 -9
  38. package/dist/src/commands/code/ports/auth-services.js +2 -0
  39. package/dist/src/commands/code/setup.js +387 -281
  40. package/dist/src/commands/code.js +205 -332
  41. package/dist/src/commands/index.js +5 -5
  42. package/dist/src/commands/models.js +6 -17
  43. package/dist/src/commands/users.js +5 -16
  44. package/dist/src/constants/command-structure.js +104 -104
  45. package/dist/src/services/api-key-service.js +132 -157
  46. package/dist/src/services/auth-service.js +89 -342
  47. package/dist/src/services/browser-auth.js +268 -0
  48. package/dist/src/services/chat-service.js +371 -401
  49. package/dist/src/services/cluster-service.js +47 -62
  50. package/dist/src/services/collaborator-service.js +10 -25
  51. package/dist/src/services/flux-service.js +14 -29
  52. package/dist/src/services/helm-service.js +10 -25
  53. package/dist/src/services/kubectl-service.js +16 -33
  54. package/dist/src/utils/config-checker.js +3 -3
  55. package/dist/src/utils/config-loader.js +95 -95
  56. package/dist/src/utils/default-api-key.js +124 -134
  57. package/dist/src/utils/env-manager.js +55 -66
  58. package/dist/src/utils/error-handler.js +20 -21
  59. package/dist/src/utils/logger.js +72 -65
  60. package/dist/src/utils/markdown-renderer.js +27 -27
  61. package/dist/src/utils/opencode-validator.js +63 -68
  62. package/dist/src/utils/token-manager.js +74 -45
  63. package/dist/tests/commands/chat.test.js +16 -25
  64. package/dist/tests/commands/code.test.js +95 -104
  65. package/dist/tests/utils/config-loader.test.js +48 -48
  66. package/dist/tests/utils/env-manager.test.js +43 -52
  67. package/dist/tests/utils/opencode-validator.test.js +22 -21
  68. package/dist/vitest.config.js +1 -1
  69. package/eslint.config.mjs +67 -0
  70. package/index.ts +35 -42
  71. package/package.json +30 -2
  72. package/src/agents/app.ts +27 -0
  73. package/src/agents/backend.ts +24 -0
  74. package/src/agents/devops.ts +33 -0
  75. package/src/agents/frontend.ts +24 -0
  76. package/src/agents/fullstack.ts +24 -0
  77. package/src/agents/index.ts +73 -0
  78. package/src/agents/quality.ts +69 -0
  79. package/src/agents/security.ts +26 -0
  80. package/src/agents/types.ts +17 -0
  81. package/src/client.ts +118 -152
  82. package/src/commands/api-keys.ts +241 -333
  83. package/src/commands/auth.ts +22 -27
  84. package/src/commands/autocomplete.ts +9 -9
  85. package/src/commands/billing.ts +20 -24
  86. package/src/commands/chat.ts +248 -338
  87. package/src/commands/clusters.ts +27 -26
  88. package/src/commands/code/__tests__/auth-sync.test.ts +482 -0
  89. package/src/commands/code/__tests__/fake-api-key-service.ts +13 -0
  90. package/src/commands/code/__tests__/fake-auth-service.ts +50 -0
  91. package/src/commands/code/__tests__/fake-command-runner.ts +45 -42
  92. package/src/commands/code/__tests__/fake-file-store.ts +32 -23
  93. package/src/commands/code/__tests__/fake-prompter.ts +116 -77
  94. package/src/commands/code/__tests__/setup-flow.test.ts +624 -268
  95. package/src/commands/code/adapters/clack-prompter.ts +53 -39
  96. package/src/commands/code/adapters/fs-file-store.ts +32 -27
  97. package/src/commands/code/adapters/spawn-command-runner.ts +38 -29
  98. package/src/commands/code/auth-sync.ts +329 -0
  99. package/src/commands/code/errors.ts +18 -18
  100. package/src/commands/code/ports/auth-services.ts +14 -0
  101. package/src/commands/code/ports/command-runner.ts +8 -4
  102. package/src/commands/code/ports/file-store.ts +5 -4
  103. package/src/commands/code/ports/prompter.ts +24 -18
  104. package/src/commands/code/setup.ts +570 -340
  105. package/src/commands/code.ts +338 -539
  106. package/src/commands/index.ts +20 -19
  107. package/src/commands/models.ts +28 -32
  108. package/src/commands/users.ts +15 -21
  109. package/src/constants/command-structure.ts +134 -157
  110. package/src/services/api-key-service.ts +105 -122
  111. package/src/services/auth-service.ts +99 -345
  112. package/src/services/browser-auth.ts +296 -0
  113. package/src/services/chat-service.ts +265 -299
  114. package/src/services/cluster-service.ts +42 -45
  115. package/src/services/collaborator-service.ts +14 -19
  116. package/src/services/flux-service.ts +23 -25
  117. package/src/services/helm-service.ts +19 -21
  118. package/src/services/kubectl-service.ts +17 -19
  119. package/src/types/api.d.ts +1905 -1907
  120. package/src/types/json.d.ts +2 -2
  121. package/src/utils/config-checker.ts +10 -10
  122. package/src/utils/config-loader.ts +162 -178
  123. package/src/utils/default-api-key.ts +114 -125
  124. package/src/utils/env-manager.ts +53 -57
  125. package/src/utils/error-handler.ts +61 -56
  126. package/src/utils/logger.ts +79 -73
  127. package/src/utils/markdown-renderer.ts +31 -31
  128. package/src/utils/opencode-validator.ts +85 -89
  129. package/src/utils/token-manager.ts +108 -87
  130. package/templates/agents/app.md +1 -0
  131. package/templates/agents/backend.md +1 -0
  132. package/templates/agents/devops.md +2 -0
  133. package/templates/agents/frontend.md +1 -0
  134. package/templates/agents/fullstack.md +1 -0
  135. package/templates/agents/quality.md +45 -40
  136. package/templates/agents/security.md +1 -0
  137. package/tests/commands/chat.test.ts +53 -62
  138. package/tests/commands/code.test.ts +265 -310
  139. package/tests/utils/config-loader.test.ts +189 -188
  140. package/tests/utils/env-manager.test.ts +110 -113
  141. package/tests/utils/opencode-validator.test.ts +52 -56
  142. package/tsconfig.json +4 -3
  143. package/vitest.config.ts +3 -3
  144. package/AGENTS.md +0 -374
  145. package/TODO.md +0 -19
@@ -1,43 +1,57 @@
1
- import * as p from '@clack/prompts'
2
- import { CancelledError } from '../errors'
3
- import type { Prompter, Spinner } from '../ports/prompter'
1
+ import * as p from '@clack/prompts';
4
2
 
5
- const unwrap = <T>(v: T | symbol): T => {
6
- if (p.isCancel(v)) throw new CancelledError()
7
- return v as T
8
- }
3
+ import type { Prompter, Spinner } from '../ports/prompter';
4
+
5
+ import { CancelledError } from '../errors';
6
+
7
+ const unwrap = <T>(v: symbol | T): T => {
8
+ if (p.isCancel(v)) throw new CancelledError();
9
+ return v as T;
10
+ };
9
11
 
10
12
  export class ClackPrompter implements Prompter {
11
- intro(message: string): void {
12
- p.intro(message)
13
- }
14
- outro(message: string): void {
15
- p.outro(message)
16
- }
17
- note(message: string, title?: string): void {
18
- p.note(message, title)
19
- }
20
- spinner(): Spinner {
21
- const s = p.spinner()
22
- return {
23
- start: (msg: string) => s.start(msg),
24
- stop: (msg: string) => s.stop(msg),
25
- }
26
- }
27
- async select<T>(opts: {
28
- message: string
29
- options: ReadonlyArray<{
30
- value: T
31
- label: string
32
- hint?: string
33
- }>
34
- }): Promise<T> {
35
- return unwrap(await p.select(opts as any))
36
- }
37
- async confirm(opts: {
38
- message: string
39
- initialValue?: boolean
40
- }): Promise<boolean> {
41
- return unwrap(await p.confirm(opts))
42
- }
13
+ async confirm(options: { initialValue?: boolean; message: string }): Promise<boolean> {
14
+ return unwrap(await p.confirm(options));
15
+ }
16
+ intro(message: string): void {
17
+ p.intro(message);
18
+ }
19
+ async multiselect<T>(options: {
20
+ message: string;
21
+ options: ReadonlyArray<{
22
+ hint?: string;
23
+ label: string;
24
+ value: T;
25
+ }>;
26
+ }): Promise<T[]> {
27
+ return unwrap(await p.multiselect(options as any));
28
+ }
29
+ note(message: string, title?: string): void {
30
+ p.note(message, title);
31
+ }
32
+ outro(message: string): void {
33
+ p.outro(message);
34
+ }
35
+ async select<T>(options: {
36
+ message: string;
37
+ options: ReadonlyArray<{
38
+ hint?: string;
39
+ label: string;
40
+ value: T;
41
+ }>;
42
+ }): Promise<T> {
43
+ return unwrap(await p.select(options as any));
44
+ }
45
+
46
+ spinner(): Spinner {
47
+ const s = p.spinner();
48
+ return {
49
+ start: (message: string) => s.start(message),
50
+ stop: (message: string) => s.stop(message),
51
+ };
52
+ }
53
+
54
+ async text(options: { message: string; placeholder?: string }): Promise<string> {
55
+ return unwrap(await p.text(options));
56
+ }
43
57
  }
@@ -1,33 +1,38 @@
1
- import { promises as fs } from 'node:fs'
2
- import * as path from 'node:path'
3
- import type { FileStore } from '../ports/file-store'
1
+ import { promises as fs } from 'node:fs';
2
+ import * as path from 'node:path';
3
+
4
+ import type { FileStore } from '../ports/file-store';
4
5
 
5
6
  export class FsFileStore implements FileStore {
6
- async exists(filePath: string): Promise<boolean> {
7
- try {
8
- await fs.access(filePath)
9
- return true
10
- } catch {
11
- return false
12
- }
13
- }
7
+ async chmod(filePath: string, mode: number): Promise<void> {
8
+ await fs.chmod(filePath, mode);
9
+ }
10
+
11
+ async exists(filePath: string): Promise<boolean> {
12
+ try {
13
+ await fs.access(filePath);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
14
19
 
15
- async readFile(filePath: string): Promise<string | null> {
16
- try {
17
- return await fs.readFile(filePath, 'utf8')
18
- } catch (err: any) {
19
- if (err.code === 'ENOENT') return null
20
- throw err
21
- }
22
- }
20
+ async mkdir(dir: string): Promise<void> {
21
+ await fs.mkdir(dir, { recursive: true });
22
+ }
23
23
 
24
- async writeFile(filePath: string, content: string): Promise<void> {
25
- const dir = path.dirname(filePath)
26
- await fs.mkdir(dir, { recursive: true })
27
- await fs.writeFile(filePath, content, 'utf8')
28
- }
24
+ async readFile(filePath: string): Promise<null | string> {
25
+ try {
26
+ return await fs.readFile(filePath, 'utf8');
27
+ } catch (error: any) {
28
+ if (error.code === 'ENOENT') return null;
29
+ throw error;
30
+ }
31
+ }
29
32
 
30
- async mkdir(dir: string): Promise<void> {
31
- await fs.mkdir(dir, { recursive: true })
32
- }
33
+ async writeFile(filePath: string, content: string): Promise<void> {
34
+ const dir = path.dirname(filePath);
35
+ await fs.mkdir(dir, { recursive: true });
36
+ await fs.writeFile(filePath, content, 'utf8');
37
+ }
33
38
  }
@@ -1,36 +1,45 @@
1
- import { spawn } from 'node:child_process'
2
- import type { CommandRunner } from '../ports/command-runner'
1
+ import { spawn } from 'node:child_process';
2
+
3
+ import type { CommandRunner } from '../ports/command-runner';
3
4
 
4
5
  export class SpawnCommandRunner implements CommandRunner {
5
- async checkInstalled(binary: string): Promise<boolean> {
6
- return new Promise((resolve) => {
7
- const child = spawn('which', [binary], { stdio: 'pipe' })
8
- child.on('close', (code) => resolve(code === 0))
9
- child.on('error', () => resolve(false))
10
- })
11
- }
6
+ async checkInstalled(binary: string): Promise<boolean> {
7
+ return new Promise((resolve) => {
8
+ const child = spawn('which', [binary], { stdio: 'pipe' });
9
+ child.on('close', (code) => resolve(code === 0));
10
+ child.on('error', () => resolve(false));
11
+ });
12
+ }
12
13
 
13
- async run(command: string, args: readonly string[], options?: { cwd?: string }): Promise<string> {
14
- return new Promise<string>((resolve, reject) => {
15
- const child = spawn(command, args as string[], {
16
- stdio: 'pipe',
17
- cwd: options?.cwd || process.cwd(),
18
- })
14
+ async run(
15
+ command: string,
16
+ arguments_: readonly string[],
17
+ options?: { cwd?: string },
18
+ ): Promise<string> {
19
+ return new Promise<string>((resolve, reject) => {
20
+ const child = spawn(command, arguments_ as string[], {
21
+ cwd: options?.cwd || process.cwd(),
22
+ stdio: 'pipe',
23
+ });
19
24
 
20
- let stdout = ''
21
- let stderr = ''
25
+ let stdout = '';
26
+ let stderr = '';
22
27
 
23
- child.stdout?.on('data', (d) => { stdout += d.toString() })
24
- child.stderr?.on('data', (d) => { stderr += d.toString() })
28
+ child.stdout?.on('data', (d) => {
29
+ stdout += d.toString();
30
+ });
31
+ child.stderr?.on('data', (d) => {
32
+ stderr += d.toString();
33
+ });
25
34
 
26
- child.on('close', (code) => {
27
- if (code === 0) {
28
- resolve(stdout)
29
- } else {
30
- reject(new Error(stderr.trim() || `Command failed with exit code ${code}`))
31
- }
32
- })
33
- child.on('error', (err) => reject(err))
34
- })
35
- }
35
+ child.on('close', (code) => {
36
+ if (code === 0) {
37
+ resolve(stdout);
38
+ } else {
39
+ reject(new Error(stderr.trim() || `Command failed with exit code ${code}`));
40
+ }
41
+ });
42
+ child.on('error', (error) => reject(error));
43
+ });
44
+ }
36
45
  }
@@ -0,0 +1,329 @@
1
+ import type { ApiKeyServicePort, AuthServicePort } from './ports/auth-services';
2
+ import type { FileStore } from './ports/file-store';
3
+ import type { Prompter } from './ports/prompter';
4
+
5
+ export interface AuthDeps {
6
+ apiKeyService: ApiKeyServicePort;
7
+ authService: AuthServicePort;
8
+ files: FileStore;
9
+ homeDir: string;
10
+ prompter: Prompter;
11
+ }
12
+
13
+ export interface AuthResult {
14
+ authenticated: boolean;
15
+ }
16
+
17
+ export interface CliAuth {
18
+ access_token: string;
19
+ expires_at: number;
20
+ refresh_token: string;
21
+ }
22
+
23
+ const CLI_AUTH_PATH = (homeDir: string) => homeDir + '/.berget/auth.json';
24
+
25
+ const TOOL_AUTH_PATHS = {
26
+ opencode: (homeDir: string) => homeDir + '/.local/share/opencode/auth.json',
27
+ pi: (homeDir: string) => homeDir + '/.pi/agent/auth.json',
28
+ } as const;
29
+
30
+ const TOOL_API_KEY_TYPES: Record<'opencode' | 'pi', string> = {
31
+ opencode: 'api',
32
+ pi: 'api_key',
33
+ };
34
+
35
+ export async function configureAuth(deps: AuthDeps, tool: 'opencode' | 'pi'): Promise<AuthResult> {
36
+ const { apiKeyService, authService, files, homeDir, prompter } = deps;
37
+
38
+ const alreadyAuth = await isToolAuthenticated(files, homeDir, tool);
39
+
40
+ if (alreadyAuth) {
41
+ const choice = await prompter.select<'keep' | 'reconfigure'>({
42
+ message: `Account is already connected to Berget AI (${tool === 'opencode' ? 'OpenCode' : 'Pi'}). How do you want to proceed?`,
43
+ options: [
44
+ { label: 'Keep existing authentication', value: 'keep' },
45
+ { label: 'Reconfigure — choose a different method', value: 'reconfigure' },
46
+ ],
47
+ });
48
+
49
+ if (choice === 'keep') {
50
+ return { authenticated: true };
51
+ }
52
+ // Fall through to reconfigure
53
+ } else {
54
+ prompter.note('Authentication required to use Berget AI.', 'Connect your account');
55
+ }
56
+
57
+ // Try to reuse existing CLI tokens (from ~/.berget/auth.json)
58
+ let cliAuth: CliAuth | null = await readCliAuth(files, homeDir);
59
+
60
+ if (!cliAuth || isTokenExpired(cliAuth.expires_at)) {
61
+ // No valid tokens → full browser login
62
+ const s = prompter.spinner();
63
+ s.start('Waiting for browser login...');
64
+
65
+ const loginResult = await authService.loginInteractive();
66
+ if (!loginResult.success) {
67
+ s.stop('Login failed.');
68
+ prompter.note(
69
+ `${loginResult.error || 'Login timed out or was cancelled.'}\n\nPlease run \`berget auth login\` manually, then run \`berget code setup\` again.`,
70
+ 'Authentication Failed',
71
+ );
72
+ return { authenticated: false };
73
+ }
74
+
75
+ s.stop('Successfully logged in to Berget.');
76
+
77
+ const jwtExpiresAt = extractJwtExpiresAt(loginResult.accessToken!);
78
+ if (jwtExpiresAt === 0) {
79
+ s.stop('Login succeeded but received invalid token.');
80
+ prompter.note('Please try logging in again or contact support.', 'Authentication Error');
81
+ return { authenticated: false };
82
+ }
83
+
84
+ cliAuth = {
85
+ access_token: loginResult.accessToken!,
86
+ expires_at: jwtExpiresAt,
87
+ refresh_token: loginResult.refreshToken!,
88
+ };
89
+ }
90
+
91
+ // Check Berget Code seat
92
+ const jwtPayload = decodeJwtPayload(cliAuth.access_token);
93
+ const hasSeat = jwtPayload ? hasBergetCodeSeat(cliAuth.access_token) : true;
94
+
95
+ // If we can't decode the JWT, sync OAuth anyway — the tokens are valid even if
96
+ // we can't verify the subscription role. Let the tool handle authorization.
97
+ if (!jwtPayload) {
98
+ const s = prompter.spinner();
99
+ s.start('Authenticating with Berget AI...');
100
+ await syncOAuthToTool(files, homeDir, tool, cliAuth);
101
+ s.stop('Authenticated.');
102
+ prompter.note(
103
+ 'Warning: Could not verify Berget Code subscription status.\nIf you do not have a subscription, the tool may show an authorization error.',
104
+ 'Authentication',
105
+ );
106
+ return { authenticated: true };
107
+ }
108
+
109
+ if (hasSeat) {
110
+ // Case B: Has seat — ask how to authenticate
111
+ const method = await prompter.select<'api_key' | 'subscription'>({
112
+ message: 'You have a Berget Code subscription. How do you want to authenticate?',
113
+ options: [
114
+ { label: 'Use my Berget Code subscription', value: 'subscription' },
115
+ { label: 'Use an API key instead', value: 'api_key' },
116
+ ],
117
+ });
118
+
119
+ if (method === 'subscription') {
120
+ const s = prompter.spinner();
121
+ s.start('Authenticating with Berget AI via subscription...');
122
+ await syncOAuthToTool(files, homeDir, tool, cliAuth);
123
+ s.stop('Authenticated.');
124
+ return { authenticated: true };
125
+ }
126
+
127
+ // Create API key instead
128
+ const s = prompter.spinner();
129
+ s.start('Creating API key...');
130
+ try {
131
+ const { key } = await apiKeyService.create({
132
+ description: 'Created by berget code setup',
133
+ name: `${tool === 'opencode' ? 'OpenCode' : 'Pi'} (created by berget CLI)`,
134
+ });
135
+ await syncApiKeyToTool(files, homeDir, tool, key);
136
+ s.stop('API key created and saved.');
137
+ return { authenticated: true };
138
+ } catch {
139
+ s.stop('API key creation failed.');
140
+ prompter.note(
141
+ 'Could not create API key. Please create one manually with `berget api-keys create`.',
142
+ 'Error',
143
+ );
144
+ return { authenticated: false };
145
+ }
146
+ }
147
+
148
+ // No Berget Code seat — prompt for API key creation
149
+ const shouldCreate = await prompter.confirm({
150
+ initialValue: true,
151
+ message: 'You do not have a Berget Code subscription. Would you like to create a new API key?',
152
+ });
153
+
154
+ if (shouldCreate) {
155
+ const s = prompter.spinner();
156
+ s.start('Creating API key...');
157
+ try {
158
+ const { key } = await apiKeyService.create({
159
+ description: 'Created by berget code setup',
160
+ name: `${tool === 'opencode' ? 'OpenCode' : 'Pi'} (created by berget CLI)`,
161
+ });
162
+ await syncApiKeyToTool(files, homeDir, tool, key);
163
+ s.stop('API key created and saved.');
164
+ return { authenticated: true };
165
+ } catch {
166
+ s.stop('API key creation failed.');
167
+ prompter.note(
168
+ 'Could not create API key. Please create one manually with `berget api-keys create`.',
169
+ 'Error',
170
+ );
171
+ return { authenticated: false };
172
+ }
173
+ }
174
+
175
+ // Case D: Declined
176
+ prompter.note(
177
+ 'Authentication skipped. You\'ll need to set up authentication manually:\n1. Run: berget api-keys create --name "My Key"\n2. Set BERGET_API_KEY environment variable, or\n3. Run `berget auth login` and try again',
178
+ 'Authentication',
179
+ );
180
+ return { authenticated: false };
181
+ }
182
+
183
+ export function decodeJwtPayload(token: string): null | unknown {
184
+ try {
185
+ const parts = token.split('.');
186
+ if (parts.length !== 3) return null;
187
+ const payload = Buffer.from(parts[1], 'base64url').toString('utf8');
188
+ return JSON.parse(payload);
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+
194
+ export function hasBergetCodeSeat(accessToken: string): boolean {
195
+ const payload = decodeJwtPayload(accessToken);
196
+ if (!payload || typeof payload !== 'object') return false;
197
+ const p = payload as Record<string, unknown>;
198
+ const realmAccess = p.realm_access as Record<string, unknown> | undefined;
199
+ if (!realmAccess) return false;
200
+ const roles = realmAccess.roles as string[] | undefined;
201
+ if (!Array.isArray(roles)) return false;
202
+ return roles.includes('berget_code_seat');
203
+ }
204
+
205
+ export function isTokenExpired(expiresAt: number): boolean {
206
+ const now = Date.now();
207
+ const timeUntilExpiry = expiresAt - now;
208
+ const buffer = Math.min(30 * 1000, timeUntilExpiry * 0.1);
209
+ return now + buffer >= expiresAt;
210
+ }
211
+
212
+ export async function isToolAuthenticated(
213
+ files: FileStore,
214
+ homeDir: string,
215
+ tool: 'opencode' | 'pi',
216
+ ): Promise<boolean> {
217
+ const content = await files.readFile(TOOL_AUTH_PATHS[tool](homeDir));
218
+ if (!content) return false;
219
+ try {
220
+ const parsed = JSON.parse(content);
221
+ return typeof parsed.berget === 'object' && parsed.berget !== null;
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+
227
+ export async function readCliAuth(files: FileStore, homeDir: string): Promise<CliAuth | null> {
228
+ const content = await files.readFile(CLI_AUTH_PATH(homeDir));
229
+ if (!content) return null;
230
+ try {
231
+ const parsed = JSON.parse(content);
232
+ if (parsed.access_token && parsed.refresh_token) {
233
+ // Extract the actual expiry time from the JWT token instead of using the stored expires_at
234
+ const jwtExpiresAt = extractJwtExpiresAt(parsed.access_token);
235
+ if (jwtExpiresAt === 0) {
236
+ // Invalid token, return null
237
+ return null;
238
+ }
239
+ return {
240
+ access_token: parsed.access_token,
241
+ expires_at: jwtExpiresAt,
242
+ refresh_token: parsed.refresh_token,
243
+ };
244
+ }
245
+ return null;
246
+ } catch {
247
+ return null;
248
+ }
249
+ }
250
+
251
+ export async function syncApiKeyToTool(
252
+ files: FileStore,
253
+ homeDir: string,
254
+ tool: 'opencode' | 'pi',
255
+ apiKey: string,
256
+ ): Promise<void> {
257
+ const authPath = TOOL_AUTH_PATHS[tool](homeDir);
258
+ let existing: Record<string, unknown> = {};
259
+
260
+ const content = await files.readFile(authPath);
261
+ if (content) {
262
+ try {
263
+ existing = JSON.parse(content) as Record<string, unknown>;
264
+ } catch {
265
+ existing = {};
266
+ }
267
+ }
268
+
269
+ const updated = {
270
+ ...existing,
271
+ berget: {
272
+ key: apiKey,
273
+ type: TOOL_API_KEY_TYPES[tool],
274
+ },
275
+ };
276
+
277
+ await files.writeFile(authPath, JSON.stringify(updated, null, 2) + '\n');
278
+ await files.chmod(authPath, 0o600);
279
+ }
280
+
281
+ export async function syncOAuthToTool(
282
+ files: FileStore,
283
+ homeDir: string,
284
+ tool: 'opencode' | 'pi',
285
+ cliAuth: CliAuth,
286
+ ): Promise<void> {
287
+ const authPath = TOOL_AUTH_PATHS[tool](homeDir);
288
+ let existing: Record<string, unknown> = {};
289
+
290
+ const content = await files.readFile(authPath);
291
+ if (content) {
292
+ try {
293
+ existing = JSON.parse(content) as Record<string, unknown>;
294
+ } catch {
295
+ existing = {};
296
+ }
297
+ }
298
+
299
+ // Use the JWT's actual expiry time for consistency
300
+ const jwtExpiresAt = extractJwtExpiresAt(cliAuth.access_token);
301
+
302
+ const updated = {
303
+ ...existing,
304
+ berget: {
305
+ access: cliAuth.access_token,
306
+ expires: jwtExpiresAt,
307
+ refresh: cliAuth.refresh_token,
308
+ type: 'oauth',
309
+ },
310
+ };
311
+
312
+ await files.writeFile(authPath, JSON.stringify(updated, null, 2) + '\n');
313
+ await files.chmod(authPath, 0o600);
314
+ }
315
+
316
+ function extractJwtExpiresAt(accessToken: string): number {
317
+ try {
318
+ const parts = accessToken.split('.');
319
+ if (parts.length !== 3) return 0;
320
+ const payload = Buffer.from(parts[1], 'base64url').toString('utf8');
321
+ const decoded = JSON.parse(payload);
322
+ if (typeof decoded.exp === 'number') {
323
+ return decoded.exp * 1000; // JWT exp is in seconds, convert to milliseconds
324
+ }
325
+ } catch {
326
+ // If decoding fails, return 0 (treated as expired)
327
+ }
328
+ return 0;
329
+ }
@@ -1,23 +1,23 @@
1
- export class PrerequisiteError extends Error {
2
- constructor(public readonly binary: string) {
3
- super(`Required binary not found: ${binary}`)
4
- this.name = 'PrerequisiteError'
5
- }
6
- }
7
-
8
1
  export class CancelledError extends Error {
9
- constructor() {
10
- super('Wizard cancelled')
11
- this.name = 'CancelledError'
12
- }
2
+ constructor() {
3
+ super('Wizard cancelled');
4
+ this.name = 'CancelledError';
5
+ }
13
6
  }
14
7
 
15
8
  export class CommandFailedError extends Error {
16
- constructor(
17
- public readonly command: string,
18
- public readonly exitCode: number
19
- ) {
20
- super(`Command "${command}" failed with exit code ${exitCode}`)
21
- this.name = 'CommandFailedError'
22
- }
9
+ constructor(
10
+ public readonly command: string,
11
+ public readonly exitCode: number,
12
+ ) {
13
+ super(`Command "${command}" failed with exit code ${exitCode}`);
14
+ this.name = 'CommandFailedError';
15
+ }
16
+ }
17
+
18
+ export class PrerequisiteError extends Error {
19
+ constructor(public readonly binary: string) {
20
+ super(`Required binary not found: ${binary}`);
21
+ this.name = 'PrerequisiteError';
22
+ }
23
23
  }
@@ -0,0 +1,14 @@
1
+ export interface ApiKeyServicePort {
2
+ create(options: { description?: string; name: string }): Promise<{ key: string }>;
3
+ }
4
+
5
+ export interface AuthServicePort {
6
+ login(): Promise<boolean>;
7
+ loginInteractive(): Promise<{
8
+ accessToken?: string;
9
+ error?: string;
10
+ expiresIn?: number;
11
+ refreshToken?: string;
12
+ success: boolean;
13
+ }>;
14
+ }
@@ -1,6 +1,10 @@
1
1
  export interface CommandRunner {
2
- checkInstalled(binary: string): Promise<boolean>
3
- run(command: string, args: readonly string[], options?: {
4
- cwd?: string
5
- }): Promise<string>
2
+ checkInstalled(binary: string): Promise<boolean>;
3
+ run(
4
+ command: string,
5
+ arguments_: readonly string[],
6
+ options?: {
7
+ cwd?: string;
8
+ },
9
+ ): Promise<string>;
6
10
  }
@@ -1,6 +1,7 @@
1
1
  export interface FileStore {
2
- exists(path: string): Promise<boolean>
3
- readFile(path: string): Promise<string | null>
4
- writeFile(path: string, content: string): Promise<void>
5
- mkdir(path: string): Promise<void>
2
+ chmod(path: string, mode: number): Promise<void>;
3
+ exists(path: string): Promise<boolean>;
4
+ mkdir(path: string): Promise<void>;
5
+ readFile(path: string): Promise<null | string>;
6
+ writeFile(path: string, content: string): Promise<void>;
6
7
  }