codebuff 1.0.233 → 1.0.234

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