codeant-cli 0.4.14 → 0.5.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 CodeAnt AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -236,6 +236,24 @@ node src/index.js secrets --last-commit
236
236
  node src/index.js secrets --all
237
237
  ```
238
238
 
239
+ ## MCP / Claude Connector
240
+
241
+ This package also ships an MCP (Model Context Protocol) server that exposes CodeAnt's scan, review, and PR data as tools to Claude and other MCP clients. The same source tree is packaged as a Desktop Extension (`.mcpb`) for one-click install in Claude Desktop.
242
+
243
+ See [mcp.md](mcp.md) for the tools listing, install paths (Claude Code CLI, Claude Desktop manual config, MCPB double-click), and bundling/submission instructions.
244
+
245
+ ## Privacy Policy
246
+
247
+ Full policy: **https://codeant.ai/privacy**
248
+
249
+ Summary of what this CLI / MCP server sends and stores:
250
+
251
+ - **Data sent to CodeAnt servers.** Authentication tokens, repository metadata (org, repo, branch, PR identifiers), and — for local review and secrets scanning — the code snippets and diffs you explicitly ask CodeAnt to scan. Nothing is sent on its own; every call is in response to a command you run or a tool Claude invokes.
252
+ - **Where it is stored.** On CodeAnt's infrastructure (https://api.codeant.ai or your self-hosted instance). Locally, the auth token is cached in `~/.codeant/config.json` on your machine.
253
+ - **Third-party sharing.** None beyond CodeAnt's own infrastructure. CodeAnt does not sell or share your data with third parties for marketing.
254
+ - **Retention.** Scan findings and PR data are retained per the CodeAnt account's retention policy (see the privacy URL above). Local config persists until you run `codeant logout` or delete `~/.codeant/config.json`.
255
+ - **Contact.** support@codeant.ai
256
+
239
257
  ## License
240
258
 
241
259
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeant-cli",
3
- "version": "0.4.14",
3
+ "version": "0.5.2",
4
4
  "description": "Code review CLI tool",
5
5
  "type": "module",
6
6
  "bin": {
@@ -9,7 +9,8 @@
9
9
  "scripts": {
10
10
  "start": "node src/index.js",
11
11
  "test": "vitest run",
12
- "test:watch": "vitest"
12
+ "test:watch": "vitest",
13
+ "mcpb:build": "node scripts/build-mcpb.mjs"
13
14
  },
14
15
  "keywords": [
15
16
  "cli",
@@ -20,7 +21,7 @@
20
21
  "license": "MIT",
21
22
  "repository": {
22
23
  "type": "git",
23
- "url": ""
24
+ "url": "https://github.com/CodeAnt-AI/codeant-cli"
24
25
  },
25
26
  "main": "./src/reviewHeadless.js",
26
27
  "exports": {
@@ -40,6 +41,7 @@
40
41
  ],
41
42
  "dependencies": {
42
43
  "@gitbeaker/rest": "^43.8.0",
44
+ "@modelcontextprotocol/sdk": "^1.29.0",
43
45
  "@octokit/rest": "^22.0.1",
44
46
  "azure-devops-node-api": "^15.1.2",
45
47
  "bitbucket": "^2.12.0",
@@ -49,7 +51,9 @@
49
51
  "open": "^10.1.0",
50
52
  "posthog-node": "^5.28.5",
51
53
  "react": "^18.3.1",
52
- "smol-toml": "^1.6.1"
54
+ "smol-toml": "^1.6.1",
55
+ "undici": "^6.26.0",
56
+ "zod": "^3.25.76"
53
57
  },
54
58
  "devDependencies": {
55
59
  "vitest": "^1.6.1"
@@ -1,7 +1,7 @@
1
1
  import React, { useState, useEffect } from 'react';
2
2
  import { Text, Box, useApp } from 'ink';
3
3
  import { getConfigValue, setConfigValue } from '../utils/config.js';
4
- import { getBaseUrl } from '../utils/baseUrl.js';
4
+ import { getBaseUrl, getDashboardUrl } from '../utils/baseUrl.js';
5
5
  import { randomUUID } from 'crypto';
6
6
 
7
7
  const POLL_INTERVAL = 10000; // 10 seconds
@@ -24,49 +24,55 @@ export default function Login() {
24
24
 
25
25
  const token = randomUUID();
26
26
  const baseUrl = getBaseUrl();
27
- const loginUrl = `https://app.codeant.ai?ideLoginToken=${token}`;
28
- setLoginUrl(loginUrl);
29
27
  const pollUrl = `${baseUrl}/extension/login/status?apiKey=${token}`;
30
28
 
31
- // Open browser
32
- import('open').then(({ default: open }) => {
33
- open(loginUrl);
34
- setStatus('waiting');
35
- }).catch(() => {
36
- // Fallback: just show the URL
37
- console.log(`\nOpen this URL in your browser:\n${loginUrl}\n`);
38
- setStatus('waiting');
39
- });
40
-
41
- // Poll for login status
29
+ let intervalId;
42
30
  let timeoutId;
43
- const intervalId = setInterval(async () => {
44
- try {
45
- const response = await fetch(pollUrl);
46
- const data = await response.json();
47
31
 
48
- if (data.status === 'yes') {
49
- clearInterval(intervalId);
50
- clearTimeout(timeoutId);
51
-
52
- // Save the API key
53
- setConfigValue('apiKeyV2', token);
54
-
55
- setStatus('success');
56
- setTimeout(() => exit(), 100);
32
+ (async () => {
33
+ const dashboardUrl = await getDashboardUrl();
34
+ const loginUrl = `${dashboardUrl}?ideLoginToken=${token}`;
35
+ setLoginUrl(loginUrl);
36
+
37
+ // Open browser
38
+ import('open').then(({ default: open }) => {
39
+ open(loginUrl);
40
+ setStatus('waiting');
41
+ }).catch(() => {
42
+ // Fallback: just show the URL
43
+ console.log(`\nOpen this URL in your browser:\n${loginUrl}\n`);
44
+ setStatus('waiting');
45
+ });
46
+
47
+ // Poll for login status
48
+ intervalId = setInterval(async () => {
49
+ try {
50
+ const response = await fetch(pollUrl);
51
+ const data = await response.json();
52
+
53
+ if (data.status === 'yes') {
54
+ clearInterval(intervalId);
55
+ clearTimeout(timeoutId);
56
+
57
+ // Save the API key
58
+ setConfigValue('apiKeyV2', token);
59
+
60
+ setStatus('success');
61
+ setTimeout(() => exit(), 100);
62
+ }
63
+ } catch (err) {
64
+ // Silently continue polling
57
65
  }
58
- } catch (err) {
59
- // Silently continue polling
60
- }
61
- }, POLL_INTERVAL);
62
-
63
- // Timeout after 10 minutes
64
- timeoutId = setTimeout(() => {
65
- clearInterval(intervalId);
66
- setError('Login timed out. Please try again.');
67
- setStatus('error');
68
- setTimeout(() => exit(new Error('Login timed out')), 100);
69
- }, TIMEOUT);
66
+ }, POLL_INTERVAL);
67
+
68
+ // Timeout after 10 minutes
69
+ timeoutId = setTimeout(() => {
70
+ clearInterval(intervalId);
71
+ setError('Login timed out. Please try again.');
72
+ setStatus('error');
73
+ setTimeout(() => exit(new Error('Login timed out')), 100);
74
+ }, TIMEOUT);
75
+ })();
70
76
 
71
77
  // Cleanup
72
78
  return () => {
@@ -190,7 +190,7 @@ export default function ScanCenter({ filterDismissed = false, includeFalsePositi
190
190
 
191
191
  // ── Step 3: repo selected → fetch scan history ──
192
192
  const handleSelectRepo = (item) =>
193
- _handleSelectRepo({ STEPS, item, setSelectedRepo, setStep, setLoadingMsg, setError, setScanHistory });
193
+ _handleSelectRepo({ STEPS, item, selectedConnection, setSelectedRepo, setStep, setLoadingMsg, setError, setScanHistory });
194
194
 
195
195
  // ── Step 4: scan selected → show result type menu ──
196
196
  const handleSelectScan = (item) =>
package/src/index.js CHANGED
@@ -397,6 +397,15 @@ program
397
397
  // ─── Settings commands ───
398
398
  registerSettingsCommands(program, { runCmd });
399
399
 
400
+ // ─── MCP server (for Claude Code plugin and other MCP clients) ───
401
+ program
402
+ .command('mcp')
403
+ .description('Run the CodeAnt MCP server over stdio (used by Claude Code plugin)')
404
+ .action(async () => {
405
+ const { startMcpServer } = await import('./mcp/server.js');
406
+ await startMcpServer();
407
+ });
408
+
400
409
  // ─── Telemetry control ───
401
410
  program
402
411
  .command('set-telemetry <enabled>')
@@ -0,0 +1,489 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { z } from 'zod';
4
+ import { createRequire } from 'module';
5
+
6
+ import { runOrgs } from '../commands/scans/orgs.js';
7
+ import { runRepos } from '../commands/scans/repos.js';
8
+ import { runHistory } from '../commands/scans/history.js';
9
+ import { runGet } from '../commands/scans/get.js';
10
+ import { runResults } from '../commands/scans/results.js';
11
+ import { runDismissed } from '../commands/scans/dismissed.js';
12
+ import { runStartScan } from '../commands/scans/start-scan.js';
13
+ import { runReviewHeadless } from '../reviewHeadless.js';
14
+ import * as scm from '../scm/index.js';
15
+ import { isAlreadyLoggedIn, runLoginFlow } from '../utils/loginFlow.js';
16
+ import { getConfigValue, setConfigValue } from '../utils/config.js';
17
+
18
+ const require = createRequire(import.meta.url);
19
+ const pkg = require('../../package.json');
20
+
21
+ const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
22
+ const WRITE_NON_DESTRUCTIVE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
23
+
24
+ // Write-side tools are gated behind CODEANT_READ_ONLY. Default = read-only.
25
+ function isReadOnly() {
26
+ const v = process.env.CODEANT_READ_ONLY;
27
+ if (v === undefined) return true;
28
+ return v !== '0' && v.toLowerCase() !== 'false';
29
+ }
30
+
31
+ function ok(value) {
32
+ return { content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] };
33
+ }
34
+
35
+ function fail(err) {
36
+ const message = err instanceof Error ? err.message : String(err);
37
+ return {
38
+ isError: true,
39
+ content: [{ type: 'text', text: JSON.stringify({ error: message }, null, 2) }],
40
+ };
41
+ }
42
+
43
+ function resolveRepoOpts(input) {
44
+ const remote = input.remote || scm.detectRemote();
45
+ const name = input.name || scm.detectRepoName();
46
+ const defaultBranch = input.defaultBranch || scm.detectDefaultBranch();
47
+ if (!remote) throw new Error('Could not detect remote. Pass `remote` (github|gitlab|bitbucket|azure).');
48
+ if (!name) throw new Error('Could not detect repo name. Pass `name` (owner/repo).');
49
+ return { ...input, remote, name, defaultBranch };
50
+ }
51
+
52
+ // Capture stdout from a function that writes JSON to stdout (used for `scans results` and `scans start-scan`).
53
+ async function captureStdout(fn) {
54
+ const chunks = [];
55
+ const origWrite = process.stdout.write.bind(process.stdout);
56
+ process.stdout.write = (chunk) => {
57
+ chunks.push(typeof chunk === 'string' ? chunk : chunk.toString('utf8'));
58
+ return true;
59
+ };
60
+ try {
61
+ await fn();
62
+ } finally {
63
+ process.stdout.write = origWrite;
64
+ }
65
+ return chunks.join('');
66
+ }
67
+
68
+ async function ensureAuthenticated() {
69
+ const envToken = process.env.CODEANT_API_TOKEN;
70
+ if (envToken && envToken.trim()) return;
71
+ if (isAlreadyLoggedIn()) {
72
+ process.env.CODEANT_API_TOKEN = getConfigValue('apiKeyV2');
73
+ return;
74
+ }
75
+
76
+ console.error('[codeant-mcp] No API token configured. Call the codeant_login tool to sign in, or set CODEANT_API_TOKEN.');
77
+ }
78
+
79
+ export async function startMcpServer() {
80
+ await ensureAuthenticated();
81
+
82
+ const server = new McpServer({ name: 'codeant', version: pkg.version });
83
+ const readOnly = isReadOnly();
84
+
85
+ // ─── Scans: discovery ────────────────────────────────────────────────────
86
+ server.registerTool(
87
+ 'codeant_scans_orgs',
88
+ {
89
+ title: 'List CodeAnt organizations',
90
+ description: 'List the CodeAnt organizations the current user is authenticated to. Use this first when the user has not specified an org.',
91
+ inputSchema: {},
92
+ annotations: READ,
93
+ },
94
+ async () => {
95
+ try { return ok(await runOrgs()); } catch (err) { return fail(err); }
96
+ }
97
+ );
98
+
99
+ server.registerTool(
100
+ 'codeant_scans_repos',
101
+ {
102
+ title: 'List repositories in a CodeAnt org',
103
+ description: 'List repositories connected to CodeAnt for a given organization. Use this to enumerate repos before fanning out org-wide queries (e.g. "secrets across all repos"). If `org` is omitted and the user has exactly one org, it is auto-picked.',
104
+ inputSchema: {
105
+ org: z.string().optional().describe('Organization name. Optional when only one org is authenticated.'),
106
+ },
107
+ annotations: READ,
108
+ },
109
+ async ({ org }) => {
110
+ try { return ok(await runRepos({ org })); } catch (err) { return fail(err); }
111
+ }
112
+ );
113
+
114
+ // ─── Scans: history + metadata ───────────────────────────────────────────
115
+ server.registerTool(
116
+ 'codeant_scans_history',
117
+ {
118
+ title: 'List scan history for a repo',
119
+ description: 'Show recent scan runs for a single repository. Use this to find a scan ID/commit SHA to drill into, or to answer "when did this repo last get scanned".',
120
+ inputSchema: {
121
+ repo: z.string().describe('Repository in owner/repo form.'),
122
+ branch: z.string().optional().describe('Filter by branch name.'),
123
+ since: z.string().optional().describe('ISO 8601 date; only return scans newer than this.'),
124
+ limit: z.number().int().positive().max(100).optional().describe('Max scans returned (default 20).'),
125
+ },
126
+ annotations: READ,
127
+ },
128
+ async ({ repo, branch, since, limit }) => {
129
+ try { return ok(await runHistory({ repo, branch, since, limit: limit ?? 20 })); } catch (err) { return fail(err); }
130
+ }
131
+ );
132
+
133
+ server.registerTool(
134
+ 'codeant_scans_get',
135
+ {
136
+ title: 'Get scan metadata summary',
137
+ description: 'Get summary metadata for a single scan (severity + category counts only — no findings). Use this to size up a scan before pulling full results.',
138
+ inputSchema: {
139
+ repo: z.string().describe('Repository in owner/repo form.'),
140
+ scan: z.string().optional().describe('Specific commit SHA. Either `scan` or `branch` should be provided.'),
141
+ branch: z.string().optional().describe('Resolve the latest scan on this branch.'),
142
+ types: z.string().optional().describe('Comma-separated scan types (default "all"). e.g. "sast,secrets".'),
143
+ },
144
+ annotations: READ,
145
+ },
146
+ async ({ repo, scan, branch, types }) => {
147
+ try { return ok(await runGet({ repo, scan, branch, types: types ?? 'all' })); } catch (err) { return fail(err); }
148
+ }
149
+ );
150
+
151
+ // ─── Scans: findings ─────────────────────────────────────────────────────
152
+ server.registerTool(
153
+ 'codeant_scans_results',
154
+ {
155
+ title: 'Fetch scan findings',
156
+ description: 'Fetch full findings (SAST, SCA, secrets, IaC, dead code, anti-patterns, etc.) for a single scan on a single repository. Returns the raw findings as JSON. For org-wide queries, call `codeant_scans_repos` first and fan out per-repo.',
157
+ inputSchema: {
158
+ repo: z.string().describe('Repository in owner/repo form.'),
159
+ scan: z.string().optional().describe('Specific commit SHA.'),
160
+ branch: z.string().optional().describe('Resolve the latest scan on this branch.'),
161
+ types: z.string().optional().describe('Comma-separated types: sast,sca,secrets,iac,dead_code,sbom,anti_patterns,docstring,complex_functions,all (default "all").'),
162
+ severity: z.string().optional().describe('Comma-separated severities (e.g. "critical,high").'),
163
+ path: z.string().optional().describe('File path glob filter.'),
164
+ check: z.string().optional().describe('Filter by check ID or name (regex).'),
165
+ filterDismissed: z.boolean().optional().describe('Exclude dismissed findings (default false).'),
166
+ includeFalsePositives: z.boolean().optional().describe('Include false positives (default true).'),
167
+ fields: z.string().optional().describe('Project findings to a subset of fields (comma-separated).'),
168
+ limit: z.number().int().positive().max(500).optional().describe('Max findings per page (default 100).'),
169
+ offset: z.number().int().nonnegative().optional().describe('Pagination offset (default 0).'),
170
+ },
171
+ annotations: READ,
172
+ },
173
+ async (input) => {
174
+ try {
175
+ const text = await captureStdout(() =>
176
+ runResults({
177
+ repo: input.repo,
178
+ scan: input.scan,
179
+ branch: input.branch,
180
+ types: input.types ?? 'all',
181
+ severity: input.severity,
182
+ path: input.path,
183
+ check: input.check,
184
+ filterDismissed: input.filterDismissed ?? false,
185
+ includeFalsePositives: input.includeFalsePositives ?? true,
186
+ format: 'json',
187
+ output: undefined,
188
+ fields: input.fields,
189
+ limit: input.limit ?? 100,
190
+ offset: input.offset ?? 0,
191
+ failFast: false,
192
+ })
193
+ );
194
+ // runResults already emits JSON; pass it through unparsed to preserve shape.
195
+ return { content: [{ type: 'text', text: text || '{}' }] };
196
+ } catch (err) {
197
+ return fail(err);
198
+ }
199
+ }
200
+ );
201
+
202
+ server.registerTool(
203
+ 'codeant_scans_dismissed',
204
+ {
205
+ title: 'List dismissed alerts',
206
+ description: 'List dismissed alerts (false positives, accepted risk, etc.) for a repository. Useful when triaging to avoid re-surfacing already-handled findings.',
207
+ inputSchema: {
208
+ repo: z.string().describe('Repository in owner/repo form.'),
209
+ analysisType: z.enum(['security', 'secrets']).optional().describe('Analysis type (default "security").'),
210
+ },
211
+ annotations: READ,
212
+ },
213
+ async ({ repo, analysisType }) => {
214
+ try { return ok(await runDismissed({ repo, analysisType: analysisType ?? 'security' })); } catch (err) { return fail(err); }
215
+ }
216
+ );
217
+
218
+ // ─── Pull requests (SCM, read-only) ──────────────────────────────────────
219
+ server.registerTool(
220
+ 'codeant_pr_list',
221
+ {
222
+ title: 'List pull requests',
223
+ description: 'List pull requests / merge requests on the current repo (auto-detected from git remote unless `name`+`remote` are provided).',
224
+ inputSchema: {
225
+ name: z.string().optional().describe('Repository in owner/repo form. Auto-detected if omitted.'),
226
+ remote: z.enum(['github', 'gitlab', 'bitbucket', 'azure']).optional().describe('Auto-detected if omitted.'),
227
+ defaultBranch: z.string().optional(),
228
+ sourceBranch: z.string().optional(),
229
+ author: z.string().optional().describe('Filter by author login (fuzzy).'),
230
+ state: z.enum(['open', 'closed']).optional().describe('Default "open".'),
231
+ limit: z.number().int().positive().max(100).optional(),
232
+ offset: z.number().int().nonnegative().optional(),
233
+ },
234
+ annotations: READ,
235
+ },
236
+ async (input) => {
237
+ try {
238
+ const opts = resolveRepoOpts(input);
239
+ return ok(
240
+ await scm.listPullRequests({
241
+ name: opts.name,
242
+ remote: opts.remote,
243
+ defaultBranch: opts.defaultBranch,
244
+ sourceBranch: opts.sourceBranch,
245
+ authorLogin: opts.author,
246
+ state: opts.state ?? 'open',
247
+ limit: opts.limit ?? 20,
248
+ offset: opts.offset ?? 0,
249
+ })
250
+ );
251
+ } catch (err) { return fail(err); }
252
+ }
253
+ );
254
+
255
+ server.registerTool(
256
+ 'codeant_pr_get',
257
+ {
258
+ title: 'Get pull request details',
259
+ description: 'Fetch detailed information for a single PR/MR including review analysis.',
260
+ inputSchema: {
261
+ prNumber: z.number().int().positive(),
262
+ name: z.string().optional(),
263
+ remote: z.enum(['github', 'gitlab', 'bitbucket', 'azure']).optional(),
264
+ defaultBranch: z.string().optional(),
265
+ },
266
+ annotations: READ,
267
+ },
268
+ async (input) => {
269
+ try {
270
+ const opts = resolveRepoOpts(input);
271
+ return ok(
272
+ await scm.getPullRequest({
273
+ name: opts.name,
274
+ remote: opts.remote,
275
+ defaultBranch: opts.defaultBranch,
276
+ prNumber: input.prNumber,
277
+ })
278
+ );
279
+ } catch (err) { return fail(err); }
280
+ }
281
+ );
282
+
283
+ server.registerTool(
284
+ 'codeant_pr_comments',
285
+ {
286
+ title: 'List PR comments',
287
+ description: 'List comments on a PR/MR with optional filters (CodeAnt-authored only, resolved/unresolved, date range).',
288
+ inputSchema: {
289
+ prNumber: z.number().int().positive(),
290
+ name: z.string().optional(),
291
+ remote: z.enum(['github', 'gitlab', 'bitbucket', 'azure']).optional(),
292
+ defaultBranch: z.string().optional(),
293
+ codeantGenerated: z.boolean().optional().describe('Only return comments authored by CodeAnt.'),
294
+ addressed: z.boolean().optional().describe('Filter by addressed/resolved status.'),
295
+ createdAfter: z.string().optional().describe('ISO 8601.'),
296
+ createdBefore: z.string().optional().describe('ISO 8601.'),
297
+ },
298
+ annotations: READ,
299
+ },
300
+ async (input) => {
301
+ try {
302
+ const opts = resolveRepoOpts(input);
303
+ return ok(
304
+ await scm.listPullRequestComments({
305
+ name: opts.name,
306
+ remote: opts.remote,
307
+ defaultBranch: opts.defaultBranch,
308
+ prNumber: input.prNumber,
309
+ codeantGenerated: input.codeantGenerated,
310
+ addressed: input.addressed,
311
+ createdAfter: input.createdAfter,
312
+ createdBefore: input.createdBefore,
313
+ })
314
+ );
315
+ } catch (err) { return fail(err); }
316
+ }
317
+ );
318
+
319
+ server.registerTool(
320
+ 'codeant_comments_search',
321
+ {
322
+ title: 'Search CodeAnt review comments',
323
+ description: 'Search across CodeAnt review comments by free-text query. Returns matching comments with repo, PR, and file context.',
324
+ inputSchema: {
325
+ query: z.string(),
326
+ name: z.string().optional(),
327
+ remote: z.enum(['github', 'gitlab', 'bitbucket', 'azure']).optional(),
328
+ limit: z.number().int().positive().max(50).optional(),
329
+ includeAddressed: z.boolean().optional(),
330
+ createdAfter: z.string().optional().describe('ISO 8601.'),
331
+ },
332
+ annotations: READ,
333
+ },
334
+ async (input) => {
335
+ try {
336
+ const opts = resolveRepoOpts(input);
337
+ return ok(
338
+ await scm.searchComments({
339
+ name: opts.name,
340
+ remote: opts.remote,
341
+ query: input.query,
342
+ limit: input.limit ?? 10,
343
+ includeAddressed: input.includeAddressed ?? false,
344
+ createdAfter: input.createdAfter,
345
+ })
346
+ );
347
+ } catch (err) { return fail(err); }
348
+ }
349
+ );
350
+
351
+ // ─── Local review (read-only — does not modify files) ────────────────────
352
+ server.registerTool(
353
+ 'codeant_review_local',
354
+ {
355
+ title: 'Review local working-copy changes',
356
+ description: 'Run a CodeAnt AI review on local working-copy changes and return the findings as JSON. Does not modify files — pair with editor tools to apply fixes. Use this for "review my changes" / "check my staged files" prompts.',
357
+ inputSchema: {
358
+ scope: z
359
+ .enum(['all', 'uncommitted', 'staged-only', 'committed', 'last-commit', 'last-n-commits', 'base-branch', 'base-commit'])
360
+ .optional()
361
+ .describe('Review scope. Default "uncommitted".'),
362
+ lastNCommits: z.number().int().positive().max(5).optional(),
363
+ baseBranch: z.string().optional(),
364
+ baseCommit: z.string().optional(),
365
+ include: z.array(z.string()).optional().describe('Glob patterns to include.'),
366
+ exclude: z.array(z.string()).optional().describe('Glob patterns to exclude.'),
367
+ },
368
+ annotations: READ,
369
+ },
370
+ async (input) => {
371
+ try {
372
+ const result = await runReviewHeadless({
373
+ workspacePath: process.cwd(),
374
+ scanType: input.scope ?? 'uncommitted',
375
+ lastNCommits: input.lastNCommits ?? 1,
376
+ include: input.include ?? [],
377
+ exclude: input.exclude ?? [],
378
+ baseBranch: input.baseBranch ?? null,
379
+ baseCommit: input.baseCommit ?? null,
380
+ onProgress: () => {},
381
+ onFilesReady: () => {},
382
+ });
383
+ return ok(result);
384
+ } catch (err) { return fail(err); }
385
+ }
386
+ );
387
+
388
+ // ─── Auth (always registered — login is needed even in read-only mode) ───
389
+ server.registerTool(
390
+ 'codeant_login',
391
+ {
392
+ title: 'Sign in to CodeAnt AI',
393
+ description: 'Opens the configured CodeAnt dashboard in the user\'s browser and waits up to 10 minutes for them to complete sign-in. Tell the user to check their browser and finish the flow there. On success the API token is saved to ~/.codeant/config.json (apiKeyV2) and set on the running MCP process, so subsequent tool calls are authenticated without restart. Returns { alreadyLoggedIn: true } immediately if a token is already configured, unless `force` is true.',
394
+ inputSchema: {
395
+ force: z.boolean().optional().describe('Re-authenticate even if a token is already configured. Default false.'),
396
+ },
397
+ annotations: { ...WRITE_NON_DESTRUCTIVE, idempotentHint: true },
398
+ },
399
+ async ({ force }) => {
400
+ try {
401
+ const envToken = process.env.CODEANT_API_TOKEN;
402
+ if (!force && ((envToken && envToken.trim()) || isAlreadyLoggedIn())) {
403
+ return ok({ alreadyLoggedIn: true });
404
+ }
405
+ const { token, loginUrl } = await runLoginFlow();
406
+ const masked = token ? `${token.slice(0, 8)}…` : null;
407
+ return ok({ status: 'success', loginUrl, token: masked });
408
+ } catch (err) { return fail(err); }
409
+ }
410
+ );
411
+
412
+ server.registerTool(
413
+ 'codeant_logout',
414
+ {
415
+ title: 'Sign out of CodeAnt AI',
416
+ description: 'Clears the saved API token from ~/.codeant/config.json and unsets CODEANT_API_TOKEN on the running MCP process. Returns { wasLoggedIn: false } immediately if no token was configured.',
417
+ inputSchema: {},
418
+ annotations: { ...WRITE_NON_DESTRUCTIVE, idempotentHint: true },
419
+ },
420
+ async () => {
421
+ try {
422
+ const wasLoggedIn = !!(process.env.CODEANT_API_TOKEN?.trim() || getConfigValue('apiKeyV2'));
423
+ setConfigValue('apiKeyV2', null);
424
+ delete process.env.CODEANT_API_TOKEN;
425
+ return ok({ wasLoggedIn, status: wasLoggedIn ? 'logged_out' : 'not_logged_in' });
426
+ } catch (err) { return fail(err); }
427
+ }
428
+ );
429
+
430
+ // ─── Write-side tools (gated behind CODEANT_READ_ONLY=0) ─────────────────
431
+ if (!readOnly) {
432
+ server.registerTool(
433
+ 'codeant_scans_start',
434
+ {
435
+ title: 'Trigger a new scan',
436
+ description: 'Trigger a new scan run for a repository. WRITE OPERATION — only enabled when CODEANT_READ_ONLY=0.',
437
+ inputSchema: {
438
+ repo: z.string().optional().describe('owner/repo (auto-detected from git remote if omitted).'),
439
+ branch: z.string().optional(),
440
+ commit: z.string().optional(),
441
+ include: z.string().optional().describe('Comma-separated globs.'),
442
+ exclude: z.string().optional().describe('Comma-separated globs.'),
443
+ },
444
+ annotations: WRITE_NON_DESTRUCTIVE,
445
+ },
446
+ async (input) => {
447
+ try {
448
+ const text = await captureStdout(() => runStartScan(input));
449
+ return { content: [{ type: 'text', text: text || '{}' }] };
450
+ } catch (err) { return fail(err); }
451
+ }
452
+ );
453
+
454
+ server.registerTool(
455
+ 'codeant_pr_resolve',
456
+ {
457
+ title: 'Resolve a PR conversation',
458
+ description: 'Resolve a conversation/comment thread on a PR. WRITE OPERATION — only enabled when CODEANT_READ_ONLY=0.',
459
+ inputSchema: {
460
+ prNumber: z.number().int().positive(),
461
+ name: z.string().optional(),
462
+ remote: z.enum(['github', 'gitlab', 'bitbucket', 'azure']).optional(),
463
+ commentId: z.number().int().optional(),
464
+ threadId: z.string().optional(),
465
+ discussionId: z.string().optional(),
466
+ },
467
+ annotations: { ...WRITE_NON_DESTRUCTIVE, idempotentHint: true },
468
+ },
469
+ async (input) => {
470
+ try {
471
+ const opts = resolveRepoOpts(input);
472
+ return ok(
473
+ await scm.resolveConversation({
474
+ name: opts.name,
475
+ remote: opts.remote,
476
+ prNumber: input.prNumber,
477
+ commentId: input.commentId,
478
+ threadId: input.threadId,
479
+ discussionId: input.discussionId,
480
+ })
481
+ );
482
+ } catch (err) { return fail(err); }
483
+ }
484
+ );
485
+ }
486
+
487
+ const transport = new StdioServerTransport();
488
+ await server.connect(transport);
489
+ }
@@ -125,27 +125,34 @@ export async function runReviewHeadless(options = {}) {
125
125
  // ── Split into per-file requests ────────────────────────────────────
126
126
  const perFileRequests = ReviewApiHelper.splitIntoPerFileRequests(requestBody);
127
127
 
128
- onProgress(`Analyzing ${perFileRequests.length} file${perFileRequests.length !== 1 ? 's' : ''} in parallel...`);
128
+ const totalFiles = perFileRequests.reduce((n, r) => n + (r._filenames?.length || 0), 0);
129
+ onProgress(`Analyzing ${totalFiles} file${totalFiles !== 1 ? 's' : ''}...`);
129
130
 
130
- // ── Per-file agent turn loops (parallel, fault-tolerant) ─────────────
131
+ // ── Per-batch agent turn loops (parallel, fault-tolerant) ────────────
132
+ // Each batch covers up to 5 files; backend reviews the multi-file diff
133
+ // in a single session (matches pragent's FileBatcher).
131
134
  const perFileResults = await Promise.all(
132
135
  perFileRequests.map(async (fileReq) => {
133
- const filename = fileReq._filename;
134
- delete fileReq._filename;
135
-
136
- if (fileReq.file_contents?.[filename]) {
137
- fileReq.file_content = fileReq.file_contents[filename];
138
- fileReq.file_path = filename;
136
+ const filenames = fileReq._filenames || [];
137
+ delete fileReq._filenames;
138
+ const label = filenames.join(', ');
139
+
140
+ // Single-file batch: still pass file_content/file_path so backend can
141
+ // build head_file_str. Multi-file batches drop these (head_file_str
142
+ // becomes empty; agent gathers context via tools instead).
143
+ if (filenames.length === 1 && fileReq.file_contents?.[filenames[0]]) {
144
+ fileReq.file_content = fileReq.file_contents[filenames[0]];
145
+ fileReq.file_path = filenames[0];
139
146
  }
140
147
  delete fileReq.file_contents;
141
148
 
142
149
  try {
143
- onProgress(`Reviewing ${filename}...`);
150
+ onProgress(`Reviewing ${label}...`);
144
151
  const result = await runTurnLoop(fileReq, gitRoot, false);
145
- onProgress(`Done reviewing ${filename}`);
152
+ onProgress(`Done reviewing ${label}`);
146
153
  return result;
147
154
  } catch (err) {
148
- console.error(`[error] Failed to review ${filename}: ${err.message}`);
155
+ console.error(`[error] Failed to review ${label}: ${err.message}`);
149
156
  return { finalMessage: null, finalOutput: null };
150
157
  }
151
158
  })
@@ -158,7 +165,12 @@ export async function runReviewHeadless(options = {}) {
158
165
  output: perFileResults[i].finalOutput,
159
166
  })).filter(r => r.output?.code_suggestions?.length > 0);
160
167
 
161
- onProgress(`${perFileWithSuggestions.length} file(s) have suggestions, running reflector...`);
168
+ const filesWithSuggestions = new Set(
169
+ perFileWithSuggestions.flatMap(r =>
170
+ (r.output?.code_suggestions || []).map(s => (s.relevant_file || '').trim()).filter(Boolean)
171
+ )
172
+ ).size;
173
+ onProgress(`${filesWithSuggestions} file${filesWithSuggestions !== 1 ? 's' : ''} have suggestions, running reflector...`);
162
174
 
163
175
  // ── Per-file reflector loops (parallel, fault-tolerant) ──────────────
164
176
  const reflectorResults = await Promise.all(
@@ -180,15 +192,34 @@ export async function runReviewHeadless(options = {}) {
180
192
  })
181
193
  );
182
194
 
183
- // ── Parse results ───────────────────────────────────────────────────
184
- const issues = reflectorResults.flatMap(r =>
185
- (r.finalOutput?.code_suggestions || []).map((issue) => ({
195
+ // ── Parse results, carrying generator labels through reflector ──────
196
+ // Pragent's rejector schema drops `label`; preserve it by matching the
197
+ // reflector's per-issue (file, start_line) back to the generator's output.
198
+ const issues = reflectorResults.flatMap((r, i) => {
199
+ const genSuggestions = perFileWithSuggestions[i]?.output?.code_suggestions || [];
200
+ const norm = (v) => (typeof v === 'string' ? v.trim() : v);
201
+ const labelFor = (issue) => {
202
+ if (norm(issue.label)) return norm(issue.label);
203
+ // Match by summary (pragent's primary strategy): rejector's
204
+ // suggestion_summary (renamed to issue_content server-side) is
205
+ // "Repeated from the input" — i.e. the generator's one_sentence_summary.
206
+ const summary = norm(issue.issue_content);
207
+ if (summary) {
208
+ const exact = genSuggestions.find(g => norm(g.one_sentence_summary) === summary);
209
+ if (norm(exact?.label)) return norm(exact.label);
210
+ }
211
+ // Fallback: first generator suggestion in the same file with a label.
212
+ const file = norm(issue.relevant_file);
213
+ const sameFile = genSuggestions.find(g => norm(g.relevant_file) === file && norm(g.label));
214
+ return norm(sameFile?.label) || 'Code Quality';
215
+ };
216
+ return (r.finalOutput?.code_suggestions || []).map((issue) => ({
186
217
  issue_content: issue.issue_content || '',
187
218
  relevant_file: issue.relevant_file || 'Unknown',
188
219
  start_line: issue.start_line || 0,
189
- label: issue.label || 'Code Quality',
190
- }))
191
- );
220
+ label: labelFor(issue),
221
+ }));
222
+ });
192
223
 
193
224
  const labelCounts = {};
194
225
  for (const i of issues) { labelCounts[i.label] = (labelCounts[i.label] || 0) + 1; }
@@ -4071,16 +4071,6 @@ regex = '''(?i)\b(phx_[a-zA-Z0-9_\-]{47})(?:\\?['"\x60]|[\s;]|\\[nr]|$)'''
4071
4071
  entropy = 3
4072
4072
  keywords = ["phx_"]
4073
4073
 
4074
- # ──────────────────────────────────────────────────────────────────────────────
4075
- # posthog-project-api-key
4076
- # ──────────────────────────────────────────────────────────────────────────────
4077
- [[rules]]
4078
- id = "posthog-project-api-key"
4079
- description = "Detected a PostHog Project API Key, which may expose product analytics data and event tracking to unauthorized access."
4080
- regex = '''(?i)\b(phc_[a-zA-Z0-9_\-]{43})(?:\\?['"\x60]|[\s;]|\\[nr]|$)'''
4081
- entropy = 3
4082
- keywords = ["phc_"]
4083
-
4084
4074
  # ──────────────────────────────────────────────────────────────────────────────
4085
4075
  # postman-api-token
4086
4076
  # ──────────────────────────────────────────────────────────────────────────────
@@ -1,9 +1,15 @@
1
1
  import { getScanHistory } from '../scans/getScanHistory.js';
2
2
 
3
- export async function handleSelectRepo({ STEPS, item, setSelectedRepo, setStep, setLoadingMsg, setError, setScanHistory }) {
3
+ export async function handleSelectRepo({ STEPS, item, selectedConnection, setSelectedRepo, setStep, setLoadingMsg, setError, setScanHistory }) {
4
4
  setSelectedRepo(item.value);
5
5
  setStep(STEPS.LOADING);
6
- const repoFullName = item.value.full_name || item.value.name;
6
+ const orgName = selectedConnection?.organizationName;
7
+ const repoName = item.value.name;
8
+ const repoFullName = item.value.full_name || (orgName && repoName ? `${orgName}/${repoName}` : repoName);
9
+ if (!repoFullName || !repoFullName.includes('/')) {
10
+ setError(`Cannot resolve repository in org/repo form (got "${repoFullName}")`, STEPS.SELECT_REPO);
11
+ return;
12
+ }
7
13
  setLoadingMsg(`Loading scan history for ${repoFullName}…`);
8
14
  const res = await getScanHistory(repoFullName);
9
15
  if (!res.success) {
@@ -70,6 +70,7 @@ export async function fetchScanResults(repo, commitId, resultType, opts = {}) {
70
70
  filter_dismissed: filterDismissed,
71
71
  include_false_positives: includeFalsePositives,
72
72
  });
73
+ console.error("dropship: ", JSON.stringify(response, null, 2));
73
74
 
74
75
  if (!response) {
75
76
  return { success: false, error: 'Failed to connect to CodeAnt server' };
@@ -0,0 +1,20 @@
1
+ import { readTool } from './readTool.js';
2
+
3
+ const MAX_FILES = 10;
4
+
5
+ export async function bulkReadTool(args, cwd) {
6
+ const files = Array.isArray(args.files) ? args.files.slice(0, MAX_FILES) : [];
7
+ if (!files.length) return 'Error: BulkRead requires a non-empty `files` array';
8
+
9
+ const parts = await Promise.all(
10
+ files.map(async (f) => {
11
+ try {
12
+ const content = await readTool(f, cwd);
13
+ return `===== ${f.file_path} =====\n${content}`;
14
+ } catch (err) {
15
+ return `===== ${f.file_path} =====\nError: ${err.message}`;
16
+ }
17
+ })
18
+ );
19
+ return parts.join('\n\n');
20
+ }
@@ -2,28 +2,41 @@ import { readTool } from './readTool.js';
2
2
  import { globTool } from './globTool.js';
3
3
  import { grepTool } from './grepTool.js';
4
4
  import { lsTool } from './lsTool.js';
5
+ import { bulkReadTool } from './bulkReadTool.js';
5
6
 
6
- export async function executeTool(toolCall, cwd) {
7
- const { name, args } = toolCall;
8
-
9
- try {
10
- if (name === 'Read') {
11
- return await readTool(args, cwd);
12
- }
7
+ // Pragent prompts instruct the model to use absolute paths rooted at /workspace.
8
+ // The CLI works relative to the user's cwd, so strip that prefix (and any other
9
+ // leading slash) before handing off to the tool implementations.
10
+ function stripWorkspace(p) {
11
+ if (typeof p !== 'string') return p;
12
+ return p.replace(/^\/workspace\/?/, '').replace(/^\/+/, '');
13
+ }
13
14
 
14
- if (name === 'Glob') {
15
- return await globTool(args, cwd);
16
- }
15
+ function normalizeArgs(args) {
16
+ if (!args || typeof args !== 'object') return args;
17
+ const out = { ...args };
18
+ if ('file_path' in out) out.file_path = stripWorkspace(out.file_path);
19
+ if ('path' in out) out.path = stripWorkspace(out.path);
20
+ if (Array.isArray(out.files)) {
21
+ out.files = out.files.map((f) =>
22
+ f && typeof f === 'object' ? { ...f, file_path: stripWorkspace(f.file_path) } : f
23
+ );
24
+ }
25
+ return out;
26
+ }
17
27
 
18
- if (name === 'Grep') {
19
- return await grepTool(args, cwd);
20
- }
28
+ export async function executeTool(toolCall, cwd) {
29
+ const { name } = toolCall;
30
+ const args = normalizeArgs(toolCall.args);
21
31
 
22
- if (name === 'LS') {
23
- return await lsTool(args, cwd);
24
- }
32
+ try {
33
+ if (name === 'Read') return await readTool(args, cwd);
34
+ if (name === 'Glob') return await globTool(args, cwd);
35
+ if (name === 'Grep') return await grepTool(args, cwd);
36
+ if (name === 'LS') return await lsTool(args, cwd);
37
+ if (name === 'BulkRead') return await bulkReadTool(args, cwd);
25
38
 
26
- // Bash tool intentionally removed to prevent arbitrary command execution
39
+ // Bash intentionally not supported — see Extension/AgenticReview/tools.py.
27
40
  return `Unknown tool: ${name}`;
28
41
  } catch (err) {
29
42
  return `Error: ${err.message}`;
@@ -1,8 +1,10 @@
1
1
  import path from 'path';
2
+ import { assertInsideCwd } from './pathUtils.js';
2
3
 
3
4
  export async function globTool(args, cwd) {
4
5
  const { globSync } = await import('glob');
5
6
  const pattern = path.resolve(cwd, args.pattern);
7
+ assertInsideCwd(pattern.replace(/[*?{[\\].*$/, '') || cwd, cwd);
6
8
  const matches = globSync(pattern);
7
9
  if (!matches.length) return 'No files found';
8
10
  return matches.map(m => path.relative(cwd, m)).join('\n');
@@ -1,8 +1,10 @@
1
1
  import { spawn } from 'child_process';
2
2
  import path from 'path';
3
+ import { assertInsideCwd } from './pathUtils.js';
3
4
 
4
5
  export async function grepTool(args, cwd) {
5
6
  const target = args.path ? path.resolve(cwd, args.path) : cwd;
7
+ assertInsideCwd(target, cwd);
6
8
  const result = await new Promise((resolve) => {
7
9
  const proc = spawn('grep', ['-rn', args.pattern, target], {
8
10
  cwd,
@@ -1,7 +1,9 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { assertInsideCwd } from './pathUtils.js';
3
4
 
4
5
  export async function lsTool(args, cwd) {
5
6
  const dirPath = args.path ? path.resolve(cwd, args.path) : cwd;
7
+ assertInsideCwd(dirPath, cwd);
6
8
  return fs.readdirSync(dirPath).sort().join('\n');
7
9
  }
@@ -0,0 +1,9 @@
1
+ import path from 'path';
2
+
3
+ export function assertInsideCwd(resolved, cwd) {
4
+ const base = path.resolve(cwd);
5
+ const target = path.resolve(resolved);
6
+ if (target !== base && !target.startsWith(base + path.sep)) {
7
+ throw new Error(`Access denied: path is outside the working directory`);
8
+ }
9
+ }
@@ -1,8 +1,10 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { assertInsideCwd } from './pathUtils.js';
3
4
 
4
5
  export async function readTool(args, cwd) {
5
6
  const filePath = path.resolve(cwd, args.file_path);
7
+ assertInsideCwd(filePath, cwd);
6
8
  const content = await fs.promises.readFile(filePath, 'utf8');
7
9
  const lines = content.split('\n');
8
10
  const offset = args.offset || 1;
@@ -1,5 +1,6 @@
1
1
  import { getConfigValue } from './config.js';
2
2
 
3
+ //
3
4
  const NEW_BASE_URL = 'https://service.codeant.ai';
4
5
 
5
6
  const getBaseUrl = () => {
@@ -8,4 +9,15 @@ const getBaseUrl = () => {
8
9
  return url;
9
10
  };
10
11
 
11
- export { getBaseUrl };
12
+ const getDashboardUrl = async () => {
13
+ try {
14
+ const response = await fetch(`${getBaseUrl()}/extension/get/dashboard`);
15
+ // console.log('Fetching dashboard URL from:', `${getBaseUrl()}/extension/get/dashboard`);
16
+ const data = await response.json();
17
+ return data.dashboard_url || 'https://app.codeant.ai';
18
+ } catch {
19
+ return 'https://app.codeant.ai';
20
+ }
21
+ };
22
+
23
+ export { getBaseUrl, getDashboardUrl };
@@ -1,6 +1,28 @@
1
+ import { Agent, setGlobalDispatcher } from 'undici';
1
2
  import { getConfigValue } from './config.js';
2
3
  import { getBaseUrl } from './baseUrl.js';
3
4
 
5
+ // Undici's default TCP connect timeout (10s) is too short for cold-start
6
+ // Lambda / API-Gateway TLS handshakes under burst load (the headless review
7
+ // fan-outs 8 requests at once). Bump to 60s globally + retry on transient
8
+ // network errors so cold starts don't break the run.
9
+ setGlobalDispatcher(
10
+ new Agent({
11
+ connect: { timeout: 60_000 },
12
+ connections: 32,
13
+ })
14
+ );
15
+
16
+ const RETRYABLE_CAUSES = new Set([
17
+ 'UND_ERR_CONNECT_TIMEOUT',
18
+ 'UND_ERR_SOCKET',
19
+ 'ECONNRESET',
20
+ 'ETIMEDOUT',
21
+ 'ENOTFOUND',
22
+ ]);
23
+
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+
4
26
  const fetchApi = async (endpoint, method = 'GET', body = null) => {
5
27
  const url = endpoint.startsWith('http') ? endpoint : `${getBaseUrl()}${endpoint}`;
6
28
 
@@ -21,25 +43,39 @@ const fetchApi = async (endpoint, method = 'GET', body = null) => {
21
43
  options.body = JSON.stringify(body);
22
44
  }
23
45
 
24
- try {
25
- const response = await fetch(url, options);
26
- console.error('API Response Status:', response.status);
46
+ // Retry transient network/cold-start failures up to 2 times.
47
+ const MAX_ATTEMPTS = 3;
48
+ let lastErr;
49
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
50
+ try {
51
+ const response = await fetch(url, options);
52
+ // console.error('API Response Status:', response.status);
27
53
 
28
- if (response.status === 403) {
29
- throw new Error('Access denied (403). Please run `codeant logout` and then `codeant login` to re-authenticate.');
30
- }
54
+ if (response.status === 403) {
55
+ throw new Error('Access denied (403). Please run `codeant logout` and then `codeant login` to re-authenticate.');
56
+ }
31
57
 
32
- const data = await response.json();
58
+ const data = await response.json();
33
59
 
34
- if (!response.ok) {
35
- throw new Error(data.message || `HTTP error ${response.status}`);
36
- }
60
+ if (!response.ok) {
61
+ throw new Error(data.message || `HTTP error ${response.status}`);
62
+ }
37
63
 
38
- return data;
39
- } catch (err) {
40
- console.error(`API Error: ${err.message}`);
41
- throw err;
64
+ return data;
65
+ } catch (err) {
66
+ lastErr = err;
67
+ const cause = err?.cause?.code || err?.cause?.message || err?.cause || '';
68
+ const retryable = RETRYABLE_CAUSES.has(err?.cause?.code) && attempt < MAX_ATTEMPTS;
69
+ if (retryable) {
70
+ console.error(`API Retry ${attempt}/${MAX_ATTEMPTS - 1} after ${cause}`);
71
+ await sleep(1000 * attempt);
72
+ continue;
73
+ }
74
+ console.error(`API Error: ${err.message}${cause ? ` (cause: ${cause})` : ''}`);
75
+ throw err;
76
+ }
42
77
  }
78
+ throw lastErr;
43
79
  };
44
80
 
45
81
  export { fetchApi };
@@ -0,0 +1,75 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { getConfigValue, setConfigValue } from './config.js';
3
+ import { getBaseUrl, getDashboardUrl } from './baseUrl.js';
4
+
5
+ const DEFAULT_POLL_INTERVAL = 10_000;
6
+ const DEFAULT_TIMEOUT = 10 * 60 * 1000;
7
+
8
+ export function isAlreadyLoggedIn() {
9
+ return !!getConfigValue('apiKeyV2');
10
+ }
11
+
12
+ export async function startLoginFlow() {
13
+ const token = randomUUID();
14
+ const baseUrl = getBaseUrl();
15
+ const dashboardUrl = await getDashboardUrl();
16
+ const loginUrl = `${dashboardUrl}?ideLoginToken=${token}`;
17
+ const pollUrl = `${baseUrl}/extension/login/status?apiKey=${token}`;
18
+
19
+ let browserOpened = false;
20
+ try {
21
+ const { default: open } = await import('open');
22
+ await open(loginUrl);
23
+ browserOpened = true;
24
+ } catch {
25
+ // Caller can fall back to printing loginUrl.
26
+ }
27
+
28
+ return { token, loginUrl, pollUrl, browserOpened };
29
+ }
30
+
31
+ export async function awaitLoginCompletion({
32
+ token,
33
+ pollUrl,
34
+ pollIntervalMs = DEFAULT_POLL_INTERVAL,
35
+ timeoutMs = DEFAULT_TIMEOUT,
36
+ signal,
37
+ } = {}) {
38
+ if (!token || !pollUrl) {
39
+ throw new Error('awaitLoginCompletion requires token and pollUrl');
40
+ }
41
+
42
+ const deadline = Date.now() + timeoutMs;
43
+
44
+ while (Date.now() < deadline) {
45
+ if (signal?.aborted) throw new Error('Login aborted');
46
+
47
+ try {
48
+ const response = await fetch(pollUrl);
49
+ const data = await response.json();
50
+ if (data.status === 'yes') {
51
+ setConfigValue('apiKeyV2', token);
52
+ process.env.CODEANT_API_TOKEN = token;
53
+ return { ok: true, token };
54
+ }
55
+ } catch {
56
+ // Network blip — keep polling.
57
+ }
58
+
59
+ const remaining = deadline - Date.now();
60
+ if (remaining <= 0) break;
61
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, remaining)));
62
+ }
63
+
64
+ throw new Error('Login timed out. Please try again.');
65
+ }
66
+
67
+ export async function runLoginFlow({
68
+ pollIntervalMs = DEFAULT_POLL_INTERVAL,
69
+ timeoutMs = DEFAULT_TIMEOUT,
70
+ signal,
71
+ } = {}) {
72
+ const { token, loginUrl, pollUrl, browserOpened } = await startLoginFlow();
73
+ const result = await awaitLoginCompletion({ token, pollUrl, pollIntervalMs, timeoutMs, signal });
74
+ return { ...result, loginUrl, browserOpened };
75
+ }
@@ -265,33 +265,39 @@ class ReviewApiHelper extends CommonApiHelper {
265
265
  }
266
266
 
267
267
  /**
268
- * Split a combined review request into per-file payloads.
269
- * Each payload has a single file's diff and content.
268
+ * Split a combined review request into batched payloads.
269
+ * Files are grouped in chunks of up to FILES_PER_BATCH so each backend
270
+ * session reviews multiple files at once (matches pragent's batching).
270
271
  */
271
- static splitIntoPerFileRequests(requestBody) {
272
+ static splitIntoPerFileRequests(requestBody, batchSize = 5) {
272
273
  if (!requestBody?.diff_content?.length) return [];
273
274
 
274
275
  const fileSections = requestBody.diff_content.split(/(?=^diff --git )/m).filter(Boolean);
275
- const perFileRequests = [];
276
+ const perFile = [];
276
277
 
277
278
  for (const section of fileSections) {
278
279
  const nameMatch = section.match(/^diff --git a\/.+ b\/(.+)$/m);
279
280
  if (!nameMatch) continue;
280
- const filename = nameMatch[1];
281
+ perFile.push({ section, filename: nameMatch[1] });
282
+ }
281
283
 
284
+ const batches = [];
285
+ for (let i = 0; i < perFile.length; i += batchSize) {
286
+ const slice = perFile.slice(i, i + batchSize);
282
287
  const fileContents = {};
283
- if (requestBody.file_contents?.[filename]) {
284
- fileContents[filename] = requestBody.file_contents[filename];
288
+ for (const { filename } of slice) {
289
+ if (requestBody.file_contents?.[filename]) {
290
+ fileContents[filename] = requestBody.file_contents[filename];
291
+ }
285
292
  }
286
-
287
- perFileRequests.push({
288
- diff_content: section,
293
+ batches.push({
294
+ diff_content: slice.map((f) => f.section).join(''),
289
295
  file_contents: fileContents,
290
- _filename: filename,
296
+ _filenames: slice.map((f) => f.filename),
291
297
  });
292
298
  }
293
299
 
294
- return perFileRequests;
300
+ return batches;
295
301
  }
296
302
  }
297
303