codebuff 1.0.244 → 1.0.246

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 (158) hide show
  1. package/dist/code-map/tsconfig.tsbuildinfo +1 -1
  2. package/dist/common/actions.d.ts +86 -104
  3. package/dist/common/actions.js +0 -1
  4. package/dist/common/actions.js.map +1 -1
  5. package/dist/common/bigquery/client.js +29 -10
  6. package/dist/common/bigquery/client.js.map +1 -1
  7. package/dist/common/constants.d.ts +13 -32
  8. package/dist/common/constants.js +23 -72
  9. package/dist/common/constants.js.map +1 -1
  10. package/dist/common/env.mjs +1 -0
  11. package/dist/common/env.mjs.map +1 -1
  12. package/dist/common/types/usage.d.ts +4 -7
  13. package/dist/common/types/usage.js +0 -1
  14. package/dist/common/types/usage.js.map +1 -1
  15. package/dist/common/util/currency.d.ts +14 -0
  16. package/dist/common/util/currency.js +23 -0
  17. package/dist/common/util/currency.js.map +1 -0
  18. package/dist/common/websockets/websocket-schema.d.ts +172 -202
  19. package/package.json +4 -2
  20. package/dist/background-process-manager.d.ts +0 -50
  21. package/dist/background-process-manager.js +0 -359
  22. package/dist/background-process-manager.js.map +0 -1
  23. package/dist/browser-runner.d.ts +0 -35
  24. package/dist/browser-runner.js +0 -680
  25. package/dist/browser-runner.js.map +0 -1
  26. package/dist/chat-storage.d.ts +0 -2
  27. package/dist/chat-storage.js +0 -93
  28. package/dist/chat-storage.js.map +0 -1
  29. package/dist/checkpoints/checkpoint-manager.d.ts +0 -94
  30. package/dist/checkpoints/checkpoint-manager.js +0 -280
  31. package/dist/checkpoints/checkpoint-manager.js.map +0 -1
  32. package/dist/checkpoints/file-manager.d.ts +0 -72
  33. package/dist/checkpoints/file-manager.js +0 -311
  34. package/dist/checkpoints/file-manager.js.map +0 -1
  35. package/dist/cli-handlers/api-key.d.ts +0 -25
  36. package/dist/cli-handlers/api-key.js +0 -66
  37. package/dist/cli-handlers/api-key.js.map +0 -1
  38. package/dist/cli-handlers/checkpoint.d.ts +0 -18
  39. package/dist/cli-handlers/checkpoint.js +0 -195
  40. package/dist/cli-handlers/checkpoint.js.map +0 -1
  41. package/dist/cli-handlers/diff.d.ts +0 -2
  42. package/dist/cli-handlers/diff.js +0 -31
  43. package/dist/cli-handlers/diff.js.map +0 -1
  44. package/dist/cli-handlers/easter-egg.d.ts +0 -1
  45. package/dist/cli-handlers/easter-egg.js +0 -126
  46. package/dist/cli-handlers/easter-egg.js.map +0 -1
  47. package/dist/cli-handlers/inititalization-flow.d.ts +0 -1
  48. package/dist/cli-handlers/inititalization-flow.js +0 -24
  49. package/dist/cli-handlers/inititalization-flow.js.map +0 -1
  50. package/dist/cli.d.ts +0 -44
  51. package/dist/cli.js +0 -463
  52. package/dist/cli.js.map +0 -1
  53. package/dist/client.d.ts +0 -149
  54. package/dist/client.js +0 -820
  55. package/dist/client.js.map +0 -1
  56. package/dist/common/billing/auto-topup.d.ts +0 -8
  57. package/dist/common/billing/auto-topup.js +0 -192
  58. package/dist/common/billing/auto-topup.js.map +0 -1
  59. package/dist/common/billing/balance-calculator.d.ts +0 -57
  60. package/dist/common/billing/balance-calculator.js +0 -218
  61. package/dist/common/billing/balance-calculator.js.map +0 -1
  62. package/dist/common/billing/conversion.d.ts +0 -9
  63. package/dist/common/billing/conversion.js +0 -20
  64. package/dist/common/billing/conversion.js.map +0 -1
  65. package/dist/common/billing/credit-conversion.d.ts +0 -24
  66. package/dist/common/billing/credit-conversion.js +0 -48
  67. package/dist/common/billing/credit-conversion.js.map +0 -1
  68. package/dist/common/billing/grant-credits.d.ts +0 -43
  69. package/dist/common/billing/grant-credits.js +0 -266
  70. package/dist/common/billing/grant-credits.js.map +0 -1
  71. package/dist/common/billing/plans.d.ts +0 -13
  72. package/dist/common/billing/plans.js +0 -44
  73. package/dist/common/billing/plans.js.map +0 -1
  74. package/dist/common/json-config/__tests__/__snapshots__/stringify-schema.test.js.snap +0 -66
  75. package/dist/common/types/plan.d.ts +0 -24
  76. package/dist/common/types/plan.js +0 -3
  77. package/dist/common/types/plan.js.map +0 -1
  78. package/dist/common/util/server/referral.d.ts +0 -14
  79. package/dist/common/util/server/referral.js +0 -85
  80. package/dist/common/util/server/referral.js.map +0 -1
  81. package/dist/config.d.ts +0 -4
  82. package/dist/config.js +0 -12
  83. package/dist/config.js.map +0 -1
  84. package/dist/create-template-project.d.ts +0 -1
  85. package/dist/create-template-project.js +0 -107
  86. package/dist/create-template-project.js.map +0 -1
  87. package/dist/credentials.d.ts +0 -4
  88. package/dist/credentials.js +0 -38
  89. package/dist/credentials.js.map +0 -1
  90. package/dist/dev-process-manager.d.ts +0 -10
  91. package/dist/dev-process-manager.js +0 -54
  92. package/dist/dev-process-manager.js.map +0 -1
  93. package/dist/fingerprint.d.ts +0 -1
  94. package/dist/fingerprint.js +0 -48
  95. package/dist/fingerprint.js.map +0 -1
  96. package/dist/index.d.ts +0 -2
  97. package/dist/index.js +0 -117
  98. package/dist/index.js.map +0 -1
  99. package/dist/menu.d.ts +0 -3
  100. package/dist/menu.js +0 -126
  101. package/dist/menu.js.map +0 -1
  102. package/dist/project-files.d.ts +0 -114
  103. package/dist/project-files.js +0 -513
  104. package/dist/project-files.js.map +0 -1
  105. package/dist/startup-process-handler.d.ts +0 -2
  106. package/dist/startup-process-handler.js +0 -21
  107. package/dist/startup-process-handler.js.map +0 -1
  108. package/dist/tool-handlers.d.ts +0 -28
  109. package/dist/tool-handlers.js +0 -240
  110. package/dist/tool-handlers.js.map +0 -1
  111. package/dist/types.d.ts +0 -9
  112. package/dist/types.js +0 -3
  113. package/dist/types.js.map +0 -1
  114. package/dist/update-codebuff.d.ts +0 -1
  115. package/dist/update-codebuff.js +0 -160
  116. package/dist/update-codebuff.js.map +0 -1
  117. package/dist/utils/__tests__/background-process-manager.test.d.ts +0 -1
  118. package/dist/utils/__tests__/background-process-manager.test.js +0 -289
  119. package/dist/utils/__tests__/background-process-manager.test.js.map +0 -1
  120. package/dist/utils/__tests__/tool-renderers.test.d.ts +0 -1
  121. package/dist/utils/__tests__/tool-renderers.test.js +0 -51
  122. package/dist/utils/__tests__/tool-renderers.test.js.map +0 -1
  123. package/dist/utils/__tests__/xml-stream-parser.test.d.ts +0 -1
  124. package/dist/utils/__tests__/xml-stream-parser.test.js +0 -229
  125. package/dist/utils/__tests__/xml-stream-parser.test.js.map +0 -1
  126. package/dist/utils/analytics.d.ts +0 -6
  127. package/dist/utils/analytics.js +0 -53
  128. package/dist/utils/analytics.js.map +0 -1
  129. package/dist/utils/detect-shell.d.ts +0 -1
  130. package/dist/utils/detect-shell.js +0 -60
  131. package/dist/utils/detect-shell.js.map +0 -1
  132. package/dist/utils/logger.d.ts +0 -21
  133. package/dist/utils/logger.js +0 -80
  134. package/dist/utils/logger.js.map +0 -1
  135. package/dist/utils/spinner.d.ts +0 -11
  136. package/dist/utils/spinner.js +0 -87
  137. package/dist/utils/spinner.js.map +0 -1
  138. package/dist/utils/system-info.d.ts +0 -8
  139. package/dist/utils/system-info.js +0 -22
  140. package/dist/utils/system-info.js.map +0 -1
  141. package/dist/utils/terminal.d.ts +0 -38
  142. package/dist/utils/terminal.js +0 -460
  143. package/dist/utils/terminal.js.map +0 -1
  144. package/dist/utils/tool-renderers.d.ts +0 -16
  145. package/dist/utils/tool-renderers.js +0 -145
  146. package/dist/utils/tool-renderers.js.map +0 -1
  147. package/dist/utils/xml-stream-parser.d.ts +0 -9
  148. package/dist/utils/xml-stream-parser.js +0 -128
  149. package/dist/utils/xml-stream-parser.js.map +0 -1
  150. package/dist/web-scraper.d.ts +0 -3
  151. package/dist/web-scraper.js +0 -57
  152. package/dist/web-scraper.js.map +0 -1
  153. package/dist/workers/checkpoint-worker.d.ts +0 -1
  154. package/dist/workers/checkpoint-worker.js +0 -48
  155. package/dist/workers/checkpoint-worker.js.map +0 -1
  156. package/dist/workers/project-context.d.ts +0 -1
  157. package/dist/workers/project-context.js +0 -17
  158. package/dist/workers/project-context.js.map +0 -1
package/dist/client.js DELETED
@@ -1,820 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Client = void 0;
7
- const child_process_1 = require("child_process");
8
- const fs_1 = require("fs");
9
- const path_1 = __importDefault(require("path"));
10
- const actions_1 = require("./common/actions");
11
- const constants_1 = require("./common/api-keys/constants");
12
- const constants_2 = require("./common/constants");
13
- const constants_3 = require("./common/json-config/constants");
14
- const analytics_events_1 = require("./common/constants/analytics-events");
15
- const agent_state_1 = require("./common/types/agent-state");
16
- const array_1 = require("./common/util/array");
17
- const string_1 = require("./common/util/string");
18
- const websocket_client_1 = require("./common/websockets/websocket-client");
19
- const picocolors_1 = require("picocolors");
20
- const ts_pattern_1 = require("ts-pattern");
21
- const zod_1 = require("zod");
22
- const background_process_manager_1 = require("./background-process-manager");
23
- const browser_runner_1 = require("./browser-runner");
24
- const chat_storage_1 = require("./chat-storage");
25
- const checkpoint_manager_1 = require("./checkpoints/checkpoint-manager");
26
- const config_1 = require("./config");
27
- const credentials_1 = require("./credentials");
28
- const fingerprint_1 = require("./fingerprint");
29
- const menu_1 = require("./menu");
30
- const project_files_1 = require("./project-files");
31
- const tool_handlers_1 = require("./tool-handlers");
32
- const analytics_1 = require("./utils/analytics");
33
- const logger_1 = require("./utils/logger");
34
- const spinner_1 = require("./utils/spinner");
35
- const tool_renderers_1 = require("./utils/tool-renderers");
36
- const xml_stream_parser_1 = require("./utils/xml-stream-parser");
37
- const web_scraper_1 = require("./web-scraper");
38
- const LOW_BALANCE_THRESHOLD = 100;
39
- const WARNING_CONFIG = {
40
- [constants_2.UserState.LOGGED_OUT]: {
41
- message: () => `Type "login" to unlock full access and get free credits!`,
42
- threshold: 100,
43
- },
44
- [constants_2.UserState.DEPLETED]: {
45
- message: () => [
46
- (0, picocolors_1.red)(`\n❌ You have used all your credits.`),
47
- `Visit ${(0, picocolors_1.bold)((0, picocolors_1.blue)(config_1.websiteUrl + '/usage'))} to add more credits and continue coding.`,
48
- ].join('\n'),
49
- threshold: 100,
50
- },
51
- [constants_2.UserState.CRITICAL]: {
52
- message: (credits) => [
53
- (0, picocolors_1.yellow)(`\n🪫 Only ${(0, picocolors_1.bold)((0, string_1.pluralize)(credits, 'credit'))} remaining!`),
54
- (0, picocolors_1.yellow)(`Visit ${(0, picocolors_1.bold)(config_1.websiteUrl + '/usage')} to add more credits.`),
55
- ].join('\n'),
56
- threshold: 85,
57
- },
58
- [constants_2.UserState.ATTENTION_NEEDED]: {
59
- message: (credits) => [
60
- (0, picocolors_1.yellow)(`\n⚠️ ${(0, picocolors_1.bold)((0, string_1.pluralize)(credits, 'credit'))} remaining. Consider topping up soon.`),
61
- ].join('\n'),
62
- threshold: 75,
63
- },
64
- [constants_2.UserState.GOOD_STANDING]: {
65
- message: () => '',
66
- threshold: 0,
67
- },
68
- };
69
- class Client {
70
- webSocket;
71
- freshPrompt;
72
- reconnectWhenNextIdle;
73
- fingerprintId;
74
- costMode;
75
- hadFileChanges = false;
76
- git;
77
- rl;
78
- responseComplete = false;
79
- pendingTopUpMessageAmount = null;
80
- oneTimeFlags = Object.fromEntries(constants_2.ONE_TIME_LABELS.map((tag) => [tag, false]));
81
- usageData = {
82
- usage: 0,
83
- remainingBalance: 0,
84
- balanceBreakdown: undefined,
85
- next_quota_reset: null,
86
- nextMonthlyGrant: 0,
87
- };
88
- fileContext;
89
- lastChanges = [];
90
- agentState;
91
- originalFileVersions = {};
92
- creditsByPromptId = {};
93
- user;
94
- lastWarnedPct = 0;
95
- nextMonthlyGrant = 0;
96
- storedApiKeyTypes = [];
97
- lastToolResults = [];
98
- model;
99
- constructor({ websocketUrl, onWebSocketError, onWebSocketReconnect, freshPrompt, reconnectWhenNextIdle, costMode, git, rl, model, }) {
100
- this.costMode = costMode;
101
- this.model = model;
102
- this.git = git;
103
- this.webSocket = new websocket_client_1.APIRealtimeClient(websocketUrl, onWebSocketError, onWebSocketReconnect);
104
- this.user = this.getUser();
105
- this.initFingerprintId();
106
- this.freshPrompt = freshPrompt;
107
- this.reconnectWhenNextIdle = reconnectWhenNextIdle;
108
- this.rl = rl;
109
- logger_1.logger.info({ eventId: analytics_events_1.AnalyticsEvent.APP_LAUNCHED }, 'App launched');
110
- }
111
- async exit() {
112
- if (browser_runner_1.activeBrowserRunner) {
113
- browser_runner_1.activeBrowserRunner.shutdown();
114
- }
115
- process.exit(0);
116
- }
117
- initAgentState(projectFileContext) {
118
- this.agentState = (0, agent_state_1.getInitialAgentState)(projectFileContext);
119
- this.fileContext = projectFileContext;
120
- }
121
- initFingerprintId() {
122
- if (!this.fingerprintId) {
123
- this.fingerprintId = this.user?.fingerprintId ?? (0, fingerprint_1.calculateFingerprint)();
124
- }
125
- return this.fingerprintId;
126
- }
127
- getUser() {
128
- if (!(0, fs_1.existsSync)(credentials_1.CREDENTIALS_PATH)) {
129
- return;
130
- }
131
- const credentialsFile = (0, fs_1.readFileSync)(credentials_1.CREDENTIALS_PATH, 'utf8');
132
- const user = (0, credentials_1.userFromJson)(credentialsFile);
133
- if (user) {
134
- (0, analytics_1.identifyUser)(user.id, {
135
- email: user.email,
136
- name: user.name,
137
- fingerprintId: this.fingerprintId,
138
- });
139
- logger_1.loggerContext.userId = user.id;
140
- logger_1.loggerContext.userEmail = user.email;
141
- logger_1.loggerContext.fingerprintId = user.fingerprintId;
142
- }
143
- return user;
144
- }
145
- async connect() {
146
- await this.webSocket.connect();
147
- this.setupSubscriptions();
148
- await this.fetchStoredApiKeyTypes();
149
- }
150
- async fetchStoredApiKeyTypes() {
151
- if (!this.user || !this.user.authToken) {
152
- return;
153
- }
154
- const TIMEOUT_MS = 5_000;
155
- // try {
156
- // const timeoutPromise = new Promise<Response>((_, reject) => {
157
- // setTimeout(() => reject(new Error('Request timed out')), TIMEOUT_MS)
158
- // })
159
- // const fetchPromise = fetch(
160
- // `${process.env.NEXT_PUBLIC_APP_URL}/api/api-keys`,
161
- // {
162
- // method: 'GET',
163
- // headers: {
164
- // 'Content-Type': 'application/json',
165
- // Cookie: `next-auth.session-token=${this.user.authToken}`,
166
- // Authorization: `Bearer ${this.user.authToken}`,
167
- // },
168
- // }
169
- // )
170
- // const response = await Promise.race([fetchPromise, timeoutPromise])
171
- // if (response.ok) {
172
- // const { keyTypes } = await response.json()
173
- // this.storedApiKeyTypes = keyTypes as ApiKeyType[]
174
- // } else {
175
- // this.storedApiKeyTypes = []
176
- // }
177
- // } catch (error) {
178
- // if (process.env.NODE_ENV !== 'production') {
179
- // console.error(
180
- // 'Error fetching stored API key types (is there something else on port 3000?):',
181
- // error
182
- // )
183
- // }
184
- // this.storedApiKeyTypes = []
185
- // }
186
- this.storedApiKeyTypes = [];
187
- }
188
- async handleAddApiKey(keyType, apiKey) {
189
- if (!this.user || !this.user.authToken) {
190
- console.log((0, picocolors_1.yellow)("Please log in first using 'login'."));
191
- this.freshPrompt();
192
- return;
193
- }
194
- const readableKeyType = constants_1.READABLE_NAME[keyType];
195
- spinner_1.Spinner.get().start();
196
- try {
197
- const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/api-keys`, {
198
- method: 'POST',
199
- headers: {
200
- 'Content-Type': 'application/json',
201
- Cookie: `next-auth.session-token=${this.user.authToken}`,
202
- },
203
- body: JSON.stringify({
204
- keyType,
205
- apiKey,
206
- authToken: this.user.authToken,
207
- }),
208
- });
209
- spinner_1.Spinner.get().stop();
210
- const respJson = await response.json();
211
- if (response.ok) {
212
- console.log((0, picocolors_1.green)(`Successfully added ${readableKeyType} API key.`));
213
- if (!this.storedApiKeyTypes.includes(keyType)) {
214
- this.storedApiKeyTypes.push(keyType);
215
- }
216
- }
217
- else {
218
- throw new Error(respJson.message);
219
- }
220
- }
221
- catch (e) {
222
- spinner_1.Spinner.get().stop();
223
- const error = e;
224
- console.error((0, picocolors_1.red)('Error adding API key: ' + error.message));
225
- }
226
- finally {
227
- this.freshPrompt();
228
- }
229
- }
230
- async handleReferralCode(referralCode) {
231
- if (this.user) {
232
- try {
233
- const redeemReferralResp = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/referrals`, {
234
- method: 'POST',
235
- headers: {
236
- 'Content-Type': 'application/json',
237
- Cookie: `next-auth.session-token=${this.user.authToken};`,
238
- },
239
- body: JSON.stringify({
240
- referralCode,
241
- authToken: this.user.authToken,
242
- }),
243
- });
244
- const respJson = await redeemReferralResp.json();
245
- if (redeemReferralResp.ok) {
246
- console.log([
247
- (0, picocolors_1.green)(`Noice, you've earned an extra ${respJson.credits_redeemed} credits!`),
248
- `(pssst: you can also refer new users and earn ${constants_2.CREDITS_REFERRAL_BONUS} credits for each referral at: ${process.env.NEXT_PUBLIC_APP_URL}/referrals)`,
249
- ].join('\n'));
250
- this.getUsage();
251
- }
252
- else {
253
- throw new Error(respJson.error);
254
- }
255
- }
256
- catch (e) {
257
- const error = e;
258
- console.error((0, picocolors_1.red)('Error: ' + error.message));
259
- this.freshPrompt();
260
- }
261
- }
262
- else {
263
- await this.login(referralCode);
264
- }
265
- }
266
- async logout() {
267
- if (this.user) {
268
- try {
269
- const response = await fetch(`${config_1.websiteUrl}/api/auth/cli/logout`, {
270
- method: 'POST',
271
- headers: { 'Content-Type': 'application/json' },
272
- body: JSON.stringify({
273
- authToken: this.user.authToken,
274
- userId: this.user.id,
275
- fingerprintId: this.user.fingerprintId,
276
- fingerprintHash: this.user.fingerprintHash,
277
- }),
278
- });
279
- if (!response.ok) {
280
- const error = await response.text();
281
- console.error((0, picocolors_1.red)('Failed to log out: ' + error));
282
- }
283
- try {
284
- (0, fs_1.unlinkSync)(credentials_1.CREDENTIALS_PATH);
285
- console.log(`You (${this.user.name}) have been logged out.`);
286
- this.user = undefined;
287
- this.pendingTopUpMessageAmount = null;
288
- this.usageData = {
289
- usage: 0,
290
- remainingBalance: 0,
291
- balanceBreakdown: undefined,
292
- next_quota_reset: null,
293
- nextMonthlyGrant: 0,
294
- };
295
- this.oneTimeFlags = Object.fromEntries(constants_2.ONE_TIME_LABELS.map((tag) => [tag, false]));
296
- }
297
- catch (error) {
298
- console.error('Error removing credentials file:', error);
299
- }
300
- }
301
- catch (error) {
302
- console.error('Error during logout:', error);
303
- }
304
- }
305
- }
306
- async login(referralCode) {
307
- if (this.user) {
308
- console.log(`You are currently logged in as ${this.user.name}. Please enter "logout" first if you want to login as a different user.`);
309
- this.freshPrompt();
310
- return;
311
- }
312
- try {
313
- const response = await fetch(`${config_1.websiteUrl}/api/auth/cli/code`, {
314
- method: 'POST',
315
- headers: { 'Content-Type': 'application/json' },
316
- body: JSON.stringify({
317
- fingerprintId: await this.fingerprintId,
318
- referralCode,
319
- }),
320
- });
321
- if (!response.ok) {
322
- const error = await response.text();
323
- console.error((0, picocolors_1.red)('Login code request failed: ' + error));
324
- this.freshPrompt();
325
- return;
326
- }
327
- const { loginUrl, fingerprintHash, expiresAt } = await response.json();
328
- const responseToUser = [
329
- '\n',
330
- `Press ${(0, picocolors_1.blue)('ENTER')} to open your browser and finish logging in...`,
331
- ];
332
- console.log(responseToUser.join('\n'));
333
- let shouldRequestLogin = true;
334
- this.rl.once('line', () => {
335
- if (shouldRequestLogin) {
336
- (0, child_process_1.spawn)(`open ${loginUrl}`, { shell: true });
337
- console.log("Opened a browser window to log you in! If it doesn't open automatically, you can click this link:");
338
- console.log();
339
- console.log((0, picocolors_1.blue)((0, picocolors_1.bold)((0, picocolors_1.underline)(loginUrl))));
340
- }
341
- });
342
- const initialTime = Date.now();
343
- const pollInterval = setInterval(async () => {
344
- if (Date.now() - initialTime > 5 * 60 * 1000 && shouldRequestLogin) {
345
- shouldRequestLogin = false;
346
- console.log('Unable to login. Please try again by typing "login" in the terminal.');
347
- this.freshPrompt();
348
- clearInterval(pollInterval);
349
- return;
350
- }
351
- if (!shouldRequestLogin) {
352
- clearInterval(pollInterval);
353
- return;
354
- }
355
- try {
356
- const fingerprintId = await this.fingerprintId;
357
- const statusResponse = await fetch(`${config_1.websiteUrl}/api/auth/cli/status?fingerprintId=${fingerprintId}&fingerprintHash=${fingerprintHash}&expiresAt=${expiresAt}`);
358
- if (!statusResponse.ok) {
359
- if (statusResponse.status !== 401) {
360
- // Ignore 401s during polling
361
- console.error('Error checking login status:', await statusResponse.text());
362
- }
363
- return;
364
- }
365
- const { user, message } = await statusResponse.json();
366
- if (user) {
367
- shouldRequestLogin = false;
368
- this.user = user;
369
- (0, analytics_1.identifyUser)(user.id, {
370
- email: user.email,
371
- name: user.name,
372
- fingerprintId: fingerprintId,
373
- });
374
- logger_1.loggerContext.userId = user.id;
375
- logger_1.loggerContext.userEmail = user.email;
376
- logger_1.loggerContext.fingerprintId = fingerprintId;
377
- logger_1.logger.info({
378
- eventId: analytics_events_1.AnalyticsEvent.LOGIN,
379
- }, 'login');
380
- const credentialsPathDir = path_1.default.dirname(credentials_1.CREDENTIALS_PATH);
381
- (0, fs_1.mkdirSync)(credentialsPathDir, { recursive: true });
382
- (0, fs_1.writeFileSync)(credentials_1.CREDENTIALS_PATH, JSON.stringify({ default: user }));
383
- const referralLink = `${process.env.NEXT_PUBLIC_APP_URL}/referrals`;
384
- const responseToUser = [
385
- 'Authentication successful! 🎉',
386
- (0, picocolors_1.bold)(`Hey there, ${user.name}.`),
387
- `Refer new users and earn ${constants_2.CREDITS_REFERRAL_BONUS} credits per month: ${(0, picocolors_1.blueBright)(referralLink)}`,
388
- ];
389
- console.log('\n' + responseToUser.join('\n'));
390
- this.lastWarnedPct = 0;
391
- this.oneTimeFlags = Object.fromEntries(constants_2.ONE_TIME_LABELS.map((tag) => [tag, false]));
392
- (0, menu_1.displayGreeting)(this.costMode, null);
393
- clearInterval(pollInterval);
394
- this.freshPrompt();
395
- }
396
- }
397
- catch (error) {
398
- console.error('Error checking login status:', error);
399
- }
400
- }, 5000);
401
- }
402
- catch (error) {
403
- console.error('Error during login:', error);
404
- this.freshPrompt();
405
- }
406
- }
407
- setUsage(usageData) {
408
- this.usageData = usageData;
409
- }
410
- reconnect() {
411
- this.webSocket.forceReconnect();
412
- }
413
- setupSubscriptions() {
414
- this.webSocket.subscribe('action-error', (action) => {
415
- if (action.error === 'Insufficient credits') {
416
- console.error(['', (0, picocolors_1.red)(`Error: ${action.message}`)].join('\n'));
417
- console.error(`Visit ${(0, picocolors_1.blue)((0, picocolors_1.bold)(process.env.NEXT_PUBLIC_APP_URL + '/usage'))} to add credits.`);
418
- }
419
- else if (action.error === 'Auto top-up disabled') {
420
- console.error(['', (0, picocolors_1.red)(`Error: ${action.message}`)].join('\n'));
421
- console.error((0, picocolors_1.yellow)(`Visit ${(0, picocolors_1.blue)((0, picocolors_1.bold)(process.env.NEXT_PUBLIC_APP_URL + '/usage'))} to update your payment settings.`));
422
- }
423
- else {
424
- console.error(['', (0, picocolors_1.red)(`Error: ${action.message}`)].join('\n'));
425
- }
426
- this.freshPrompt();
427
- return;
428
- });
429
- this.webSocket.subscribe('read-files', (a) => {
430
- const { filePaths, requestId } = a;
431
- const files = (0, project_files_1.getFiles)(filePaths);
432
- this.webSocket.sendAction({
433
- type: 'read-files-response',
434
- files,
435
- requestId,
436
- });
437
- });
438
- this.webSocket.subscribe('npm-version-status', (action) => {
439
- const { isUpToDate } = action;
440
- if (!isUpToDate) {
441
- console.warn((0, picocolors_1.yellow)(`\nThere's a new version of Codebuff! Please update to ensure proper functionality.\nUpdate now by running: npm install -g codebuff`));
442
- }
443
- });
444
- this.webSocket.subscribe('message-cost-response', (action) => {
445
- const parsedAction = actions_1.MessageCostResponseSchema.safeParse(action);
446
- if (!parsedAction.success)
447
- return;
448
- const response = parsedAction.data;
449
- // Store credits used for this prompt
450
- if (!this.creditsByPromptId[response.promptId]) {
451
- this.creditsByPromptId[response.promptId] = [];
452
- }
453
- this.creditsByPromptId[response.promptId].push(response.credits);
454
- });
455
- this.webSocket.subscribe('usage-response', (action) => {
456
- const parsedAction = actions_1.UsageReponseSchema.safeParse(action);
457
- if (!parsedAction.success) {
458
- console.error((0, picocolors_1.red)('Received invalid usage data from server:'), parsedAction.error.errors);
459
- return;
460
- }
461
- this.setUsage(parsedAction.data);
462
- // Store auto-topup info if it occurred
463
- if (parsedAction.data.autoTopupAdded) {
464
- this.pendingTopUpMessageAmount = parsedAction.data.autoTopupAdded;
465
- }
466
- // Only show warning if the response is complete
467
- if (this.responseComplete) {
468
- this.showUsageWarning();
469
- }
470
- });
471
- // Used to handle server restarts gracefully
472
- this.webSocket.subscribe('request-reconnect', () => {
473
- this.reconnectWhenNextIdle();
474
- });
475
- }
476
- showUsageWarning() {
477
- // Determine user state based on login status and credit balance
478
- const state = (0, ts_pattern_1.match)({
479
- isLoggedIn: !!this.user,
480
- credits: this.usageData.remainingBalance,
481
- })
482
- .with({ isLoggedIn: false }, () => constants_2.UserState.LOGGED_OUT)
483
- .with({ credits: ts_pattern_1.P.number.gte(100) }, () => constants_2.UserState.GOOD_STANDING)
484
- .with({ credits: ts_pattern_1.P.number.gte(20) }, () => constants_2.UserState.ATTENTION_NEEDED)
485
- .with({ credits: ts_pattern_1.P.number.gte(1) }, () => constants_2.UserState.CRITICAL)
486
- .otherwise(() => constants_2.UserState.DEPLETED);
487
- const config = WARNING_CONFIG[state];
488
- // Reset warning percentage if in good standing
489
- if (state === constants_2.UserState.GOOD_STANDING) {
490
- this.lastWarnedPct = 0;
491
- return;
492
- }
493
- // Show warning if we haven't warned at this threshold yet
494
- if (this.lastWarnedPct < config.threshold) {
495
- const message = config.message(this.usageData.remainingBalance);
496
- console.warn(message);
497
- this.lastWarnedPct = config.threshold;
498
- this.freshPrompt();
499
- }
500
- }
501
- async generateCommitMessage(stagedChanges) {
502
- return new Promise(async (resolve, reject) => {
503
- const unsubscribe = this.webSocket.subscribe('commit-message-response', (action) => {
504
- unsubscribe();
505
- resolve(action.commitMessage);
506
- });
507
- this.webSocket.sendAction({
508
- type: 'generate-commit-message',
509
- fingerprintId: await this.fingerprintId,
510
- authToken: this.user?.authToken,
511
- stagedChanges,
512
- });
513
- });
514
- }
515
- async sendUserInput(prompt) {
516
- if (!this.agentState) {
517
- throw new Error('Agent state not initialized');
518
- }
519
- const userInputId = `mc-input-` + Math.random().toString(36).substring(2, 15);
520
- logger_1.loggerContext.clientRequestId = userInputId;
521
- const { responsePromise, stopResponse } = this.subscribeToResponse((chunk) => {
522
- spinner_1.Spinner.get().stop();
523
- process.stdout.write(chunk);
524
- }, userInputId, () => {
525
- spinner_1.Spinner.get().stop();
526
- process.stdout.write((0, picocolors_1.green)((0, picocolors_1.underline)('\nCodebuff') + ':') + ' ');
527
- }, prompt);
528
- const urls = (0, web_scraper_1.parseUrlsFromContent)(prompt);
529
- const scrapedBlocks = await (0, web_scraper_1.getScrapedContentBlocks)(urls);
530
- const scrapedContent = scrapedBlocks.length > 0 ? scrapedBlocks.join('\n\n') + '\n\n' : '';
531
- // Append process updates to existing tool results
532
- const toolResults = (0, array_1.buildArray)(...(this.lastToolResults || []), ...(0, background_process_manager_1.getBackgroundProcessUpdates)(), scrapedContent && {
533
- id: 'scraped-content',
534
- name: 'web-scraper',
535
- result: scrapedContent,
536
- });
537
- spinner_1.Spinner.get().start();
538
- this.webSocket.sendAction({
539
- type: 'prompt',
540
- promptId: userInputId,
541
- prompt,
542
- agentState: this.agentState,
543
- toolResults,
544
- fingerprintId: await this.fingerprintId,
545
- authToken: this.user?.authToken,
546
- costMode: this.costMode,
547
- model: this.model,
548
- });
549
- return {
550
- responsePromise,
551
- stopResponse,
552
- };
553
- }
554
- subscribeToResponse(onChunk, userInputId, onStreamStart, prompt) {
555
- let responseBuffer = '';
556
- let streamStarted = false;
557
- let responseStopped = false;
558
- let resolveResponse;
559
- let rejectResponse;
560
- let unsubscribeChunks;
561
- let unsubscribeComplete;
562
- const responsePromise = new Promise((resolve, reject) => {
563
- resolveResponse = resolve;
564
- rejectResponse = reject;
565
- });
566
- const stopResponse = () => {
567
- responseStopped = true;
568
- unsubscribeChunks();
569
- unsubscribeComplete();
570
- const additionalMessages = [
571
- { role: 'user', content: prompt },
572
- {
573
- role: 'user',
574
- content: `<system><assistant_message>${responseBuffer}</assistant_message>[RESPONSE_CANCELED_BY_USER]</system>`,
575
- },
576
- ];
577
- // Update the agent state with just the assistant's response
578
- const { messageHistory } = this.agentState;
579
- const newMessages = [...messageHistory, ...additionalMessages];
580
- this.agentState = {
581
- ...this.agentState,
582
- messageHistory: newMessages,
583
- };
584
- (0, chat_storage_1.setMessages)(newMessages);
585
- resolveResponse({
586
- type: 'prompt-response',
587
- promptId: userInputId,
588
- agentState: this.agentState,
589
- toolCalls: [],
590
- toolResults: [],
591
- wasStoppedByUser: true,
592
- });
593
- };
594
- const xmlStreamParser = (0, xml_stream_parser_1.createXMLStreamParser)(tool_renderers_1.toolRenderers, (chunk) => {
595
- onChunk(chunk);
596
- responseBuffer += chunk;
597
- });
598
- unsubscribeChunks = this.webSocket.subscribe('response-chunk', (a) => {
599
- if (a.userInputId !== userInputId)
600
- return;
601
- const { chunk } = a;
602
- const trimmed = chunk.trim();
603
- for (const tag of constants_2.ONE_TIME_TAGS) {
604
- if (trimmed.startsWith(`<${tag}>`) && trimmed.endsWith(`</${tag}>`)) {
605
- if (this.oneTimeFlags[tag]) {
606
- return;
607
- }
608
- spinner_1.Spinner.get().stop();
609
- const warningMessage = trimmed
610
- .replace(`<${tag}>`, '')
611
- .replace(`</${tag}>`, '');
612
- console.warn((0, picocolors_1.yellow)(`\n${warningMessage}`));
613
- this.oneTimeFlags[tag] = true;
614
- return;
615
- }
616
- }
617
- if (chunk && chunk.trim()) {
618
- if (!streamStarted && chunk.trim()) {
619
- streamStarted = true;
620
- onStreamStart();
621
- }
622
- }
623
- try {
624
- xmlStreamParser.write(chunk, 'utf8');
625
- }
626
- catch (e) {
627
- // console.error('Error writing chunk', e)
628
- }
629
- });
630
- unsubscribeComplete = this.webSocket.subscribe('prompt-response', async (action) => {
631
- const parsedAction = actions_1.PromptResponseSchema.safeParse(action);
632
- if (!parsedAction.success)
633
- return;
634
- if (action.promptId !== userInputId)
635
- return;
636
- const a = parsedAction.data;
637
- let isComplete = false;
638
- spinner_1.Spinner.get().stop();
639
- this.agentState = a.agentState;
640
- const toolResults = [...a.toolResults];
641
- for (const toolCall of a.toolCalls) {
642
- try {
643
- if (toolCall.name === 'end_turn') {
644
- this.responseComplete = true;
645
- isComplete = true;
646
- continue;
647
- }
648
- if (toolCall.name === 'write_file') {
649
- // Save lastChanges for `diff` command
650
- this.lastChanges.push(actions_1.FileChangeSchema.parse(toolCall.parameters));
651
- this.hadFileChanges = true;
652
- }
653
- if (toolCall.name === 'run_terminal_command' &&
654
- toolCall.parameters.mode === 'user') {
655
- // Special case: when terminal command is run it as a user command, then no need to reprompt assistant.
656
- this.responseComplete = true;
657
- isComplete = true;
658
- }
659
- if (toolCall.name === 'run_terminal_command' &&
660
- toolCall.parameters.mode === 'assistant' &&
661
- toolCall.parameters.process_type === 'BACKGROUND') {
662
- this.oneTimeFlags[constants_2.SHOULD_ASK_CONFIG] = true;
663
- }
664
- const toolResult = await (0, tool_handlers_1.handleToolCall)(toolCall, (0, project_files_1.getProjectRoot)());
665
- toolResults.push(toolResult);
666
- }
667
- catch (error) {
668
- console.error((0, picocolors_1.red)(`Error parsing tool call ${toolCall.name}:\n${error}`));
669
- }
670
- }
671
- if (toolResults.length > 0 ||
672
- a.toolCalls.some((call) => call.name === 'end_turn')) {
673
- console.log();
674
- }
675
- // If we had any file changes, update the project context
676
- if (this.hadFileChanges) {
677
- this.fileContext = await (0, project_files_1.getProjectFileContext)((0, project_files_1.getProjectRoot)(), {});
678
- }
679
- if (!isComplete) {
680
- // Append process updates to existing tool results
681
- toolResults.push(...(0, background_process_manager_1.getBackgroundProcessUpdates)());
682
- // Continue the prompt with the tool results.
683
- this.webSocket.sendAction({
684
- type: 'prompt',
685
- promptId: userInputId,
686
- prompt: undefined,
687
- agentState: this.agentState,
688
- toolResults,
689
- fingerprintId: await this.fingerprintId,
690
- authToken: this.user?.authToken,
691
- costMode: this.costMode,
692
- model: this.model,
693
- });
694
- return;
695
- }
696
- this.lastToolResults = toolResults;
697
- xmlStreamParser.end();
698
- askConfig: if (this.oneTimeFlags[constants_2.SHOULD_ASK_CONFIG] &&
699
- !this.oneTimeFlags[constants_2.ASKED_CONFIG]) {
700
- this.oneTimeFlags[constants_2.ASKED_CONFIG] = true;
701
- if ((0, fs_1.existsSync)(path_1.default.join((0, project_files_1.getProjectRoot)(), constants_3.codebuffConfigFile))) {
702
- break askConfig;
703
- }
704
- console.log((0, picocolors_1.yellow)(`✨ Recommended: run the 'init' command in order to create a configuration file!
705
-
706
- If you would like background processes (like this one) to run automatically whenever Codebuff starts, creating a ${constants_3.codebuffConfigFile} config file can improve your workflow.
707
- Go to https://www.codebuff.com/config for more information.
708
- `));
709
- }
710
- if (this.agentState) {
711
- (0, chat_storage_1.setMessages)(this.agentState.messageHistory);
712
- }
713
- // Show total credits used for this prompt if significant
714
- const credits = this.creditsByPromptId[userInputId]?.reduce((a, b) => a + b, 0) ?? 0;
715
- if (credits >= constants_2.REQUEST_CREDIT_SHOW_THRESHOLD) {
716
- console.log(`${(0, string_1.pluralize)(credits, 'credit')} used for this request.`);
717
- }
718
- // Show auto top-up success message if it occurred during this response
719
- if (this.pendingTopUpMessageAmount) {
720
- console.log((0, picocolors_1.green)(`Auto top-up successful! ${this.pendingTopUpMessageAmount.toLocaleString()} credits added.`));
721
- this.pendingTopUpMessageAmount = null;
722
- }
723
- if (this.hadFileChanges) {
724
- let checkpointAddendum = '';
725
- try {
726
- checkpointAddendum = ` or "checkpoint ${checkpoint_manager_1.checkpointManager.getLatestCheckpoint().id}" to revert`;
727
- }
728
- catch (error) {
729
- // No latest checkpoint, don't show addendum
730
- }
731
- console.log(`\nComplete! Type "diff" to review changes${checkpointAddendum}.`);
732
- this.hadFileChanges = false;
733
- this.freshPrompt();
734
- }
735
- unsubscribeChunks();
736
- unsubscribeComplete();
737
- resolveResponse({ ...a, wasStoppedByUser: false });
738
- });
739
- // Reset flags at the start of each response
740
- this.responseComplete = false;
741
- return {
742
- responsePromise,
743
- stopResponse,
744
- };
745
- }
746
- async getUsage() {
747
- try {
748
- const response = await fetch(`${config_1.backendUrl}/api/usage`, {
749
- method: 'POST',
750
- headers: {
751
- 'Content-Type': 'application/json',
752
- },
753
- body: JSON.stringify({
754
- fingerprintId: await this.fingerprintId,
755
- authToken: this.user?.authToken,
756
- }),
757
- });
758
- const data = await response.json();
759
- // Use zod schema to validate response
760
- const parsedResponse = actions_1.UsageReponseSchema.parse(data);
761
- if (data.type === 'action-error') {
762
- console.error((0, picocolors_1.red)(data.message));
763
- return;
764
- }
765
- this.setUsage(parsedResponse);
766
- const usageLink = `${config_1.websiteUrl}/usage`;
767
- const remainingColor = this.usageData.remainingBalance <= 0
768
- ? picocolors_1.red
769
- : this.usageData.remainingBalance <= LOW_BALANCE_THRESHOLD
770
- ? picocolors_1.red
771
- : picocolors_1.green;
772
- const totalCreditsUsedThisSession = Object.values(this.creditsByPromptId)
773
- .flat()
774
- .reduce((sum, credits) => sum + credits, 0);
775
- console.log(`Session usage: ${totalCreditsUsedThisSession.toLocaleString()}. Credits Remaining: ${remainingColor(this.usageData.remainingBalance.toLocaleString())}`);
776
- if (this.usageData.next_quota_reset) {
777
- const resetDate = new Date(this.usageData.next_quota_reset);
778
- const today = new Date();
779
- const isToday = resetDate.toDateString() === today.toDateString();
780
- const dateDisplay = isToday
781
- ? resetDate.toLocaleString() // Show full date and time for today
782
- : resetDate.toLocaleDateString(); // Just show date otherwise
783
- console.log(`Free credits will renew on ${dateDisplay}. Details: ${(0, picocolors_1.underline)((0, picocolors_1.blue)(usageLink))}`);
784
- }
785
- this.showUsageWarning();
786
- }
787
- catch (error) {
788
- console.error((0, picocolors_1.red)(`Error checking usage: Please reach out to ${process.env.NEXT_PUBLIC_SUPPORT_EMAIL} for help.`));
789
- // Check if it's a ZodError for more specific feedback
790
- if (error instanceof zod_1.z.ZodError) {
791
- console.error((0, picocolors_1.red)('Data validation failed:'), error.errors);
792
- }
793
- else {
794
- console.error(error);
795
- }
796
- }
797
- finally {
798
- this.freshPrompt();
799
- }
800
- }
801
- async warmContextCache() {
802
- const fileContext = await (0, project_files_1.getProjectFileContext)((0, project_files_1.getProjectRoot)(), {});
803
- this.webSocket.subscribe('init-response', (a) => {
804
- const parsedAction = actions_1.InitResponseSchema.safeParse(a);
805
- if (!parsedAction.success)
806
- return;
807
- // Set initial usage data from the init response
808
- this.setUsage(parsedAction.data);
809
- });
810
- this.webSocket.sendAction({
811
- type: 'init',
812
- fingerprintId: await this.fingerprintId,
813
- authToken: this.user?.authToken,
814
- fileContext,
815
- });
816
- await this.fetchStoredApiKeyTypes();
817
- }
818
- }
819
- exports.Client = Client;
820
- //# sourceMappingURL=client.js.map