-
Notifications
You must be signed in to change notification settings - Fork 567
Expand file tree
/
Copy pathserverReview.ts
More file actions
747 lines (705 loc) · 23.1 KB
/
Copy pathserverReview.ts
File metadata and controls
747 lines (705 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
import { execSync, spawnSync } from "node:child_process";
import { readFileSync, existsSync } from "node:fs";
import { createServer } from "node:http";
import os from "node:os";
import { Readable } from "node:stream";
import { contentHash, deleteDraft } from "../generated/draft.js";
import { saveConfig, detectGitUser, getServerConfig, isSafeCustomPath } from "../generated/config.js";
export type {
DiffOption,
DiffType,
GitContext,
} from "../generated/review-core.js";
import {
getDisplayRepo,
getMRLabel,
getMRNumberLabel,
type PRMetadata,
type PRReviewFileComment,
prRefFromMetadata,
} from "../generated/pr-provider.js";
import {
type DiffType,
type GitCommandResult,
type GitContext,
getFileContentsForDiff as getFileContentsForDiffCore,
getGitContext as getGitContextCore,
gitAddFile as gitAddFileCore,
gitResetFile as gitResetFileCore,
parseWorktreeDiffType,
type ReviewGitRuntime,
runGitDiff as runGitDiffCore,
validateFilePath,
} from "../generated/review-core.js";
import { createEditorAnnotationHandler } from "./annotations.js";
import { createAgentJobHandler } from "./agent-jobs.js";
import { createExternalAnnotationHandler } from "./external-annotations.js";
import {
handleDraftRequest,
handleFavicon,
handleImageRequest,
handleUploadRequest,
} from "./handlers.js";
import { html, json, parseBody, requestUrl, toWebRequest } from "./helpers.js";
import { isRemoteSession, listenOnPort } from "./network.js";
import {
fetchPRContext,
fetchPRFileContent,
fetchPRViewedFiles,
getPRUser,
markPRFilesViewed,
submitPRReview,
} from "./pr.js";
import { getRepoInfo } from "./project.js";
import {
CODEX_REVIEW_SYSTEM_PROMPT,
buildCodexReviewUserMessage,
buildCodexCommand,
generateOutputPath,
parseCodexOutput,
transformReviewFindings,
} from "../generated/codex-review.js";
import {
CLAUDE_REVIEW_PROMPT,
buildClaudeCommand,
parseClaudeStreamOutput,
transformClaudeFindings,
} from "../generated/claude-review.js";
/** Detect if running inside WSL (Windows Subsystem for Linux) */
function detectWSL(): boolean {
if (process.platform !== "linux") return false;
if (os.release().toLowerCase().includes("microsoft")) return true;
try {
if (existsSync("/proc/version")) {
const content = readFileSync("/proc/version", "utf-8").toLowerCase();
return content.includes("wsl") || content.includes("microsoft");
}
} catch { /* ignore */ }
return false;
}
export interface ReviewServerResult {
port: number;
portSource: "env" | "remote-default" | "random";
url: string;
isRemote: boolean;
waitForDecision: () => Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}>;
stop: () => void;
}
export const reviewRuntime: ReviewGitRuntime = {
async runGit(
args: string[],
options?: { cwd?: string },
): Promise<GitCommandResult> {
const result = spawnSync("git", args, {
cwd: options?.cwd,
encoding: "utf-8",
});
return {
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
exitCode: result.status ?? (result.error ? 1 : 0),
};
},
async readTextFile(path: string): Promise<string | null> {
try {
return readFileSync(path, "utf-8");
} catch {
return null;
}
},
};
export function getGitContext(cwd?: string): Promise<GitContext> {
return getGitContextCore(reviewRuntime, cwd);
}
export function runGitDiff(
diffType: DiffType,
defaultBranch = "main",
cwd?: string,
): Promise<{ patch: string; label: string; error?: string }> {
return runGitDiffCore(reviewRuntime, diffType, defaultBranch, cwd);
}
export async function startReviewServer(options: {
rawPatch: string;
gitRef: string;
htmlContent: string;
origin?: string;
diffType?: DiffType;
gitContext?: GitContext;
error?: string;
sharingEnabled?: boolean;
shareBaseUrl?: string;
prMetadata?: PRMetadata;
/** Working directory for agent processes (e.g., --local worktree). Independent of diff pipeline. */
agentCwd?: string;
/** Cleanup callback invoked when server stops (e.g., remove temp worktree) */
onCleanup?: () => void | Promise<void>;
/** Called when server starts with the URL, remote status, and port */
onReady?: (url: string, isRemote: boolean, port: number) => void;
}): Promise<ReviewServerResult> {
const gitUser = detectGitUser();
const draftKey = contentHash(options.rawPatch);
const prMeta = options.prMetadata;
const isPRMode = !!prMeta;
const hasLocalAccess = !!options.gitContext;
const isRemote = isRemoteSession();
const wslFlag = detectWSL();
const prRef = prMeta ? prRefFromMetadata(prMeta) : null;
const platformUser = prRef ? await getPRUser(prRef) : null;
// Fetch GitHub viewed file state (non-blocking — errors are silently ignored)
let initialViewedFiles: string[] = [];
if (isPRMode && prRef) {
try {
const viewedMap = await fetchPRViewedFiles(prRef);
initialViewedFiles = Object.entries(viewedMap)
.filter(([, isViewed]) => isViewed)
.map(([path]) => path);
} catch {
// Non-fatal: viewed state is best-effort
}
}
const repoInfo = prMeta
? {
display: getDisplayRepo(prMeta),
branch: `${getMRLabel(prMeta)} ${getMRNumberLabel(prMeta)}`,
}
: getRepoInfo();
const editorAnnotations = createEditorAnnotationHandler();
const externalAnnotations = createExternalAnnotationHandler("review");
let currentPatch = options.rawPatch;
let currentGitRef = options.gitRef;
let currentDiffType: DiffType = options.diffType || "uncommitted";
let currentError = options.error;
// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
// Worktree-aware cwd resolver — shared by getCwd, buildCommand, and onJobComplete
function resolveAgentCwd(): string {
if (options.agentCwd) return options.agentCwd;
if (currentDiffType.startsWith("worktree:")) {
const parsed = parseWorktreeDiffType(currentDiffType);
if (parsed) return parsed.path;
}
return options.gitContext?.cwd ?? process.cwd();
}
const agentJobs = createAgentJobHandler({
mode: "review",
getServerUrl: () => serverUrl,
getCwd: resolveAgentCwd,
async buildCommand(provider) {
const cwd = resolveAgentCwd();
const hasAgentLocalAccess = !!options.agentCwd || !!options.gitContext;
const userMessage = buildCodexReviewUserMessage(
currentPatch,
currentDiffType,
{ defaultBranch: options.gitContext?.defaultBranch, hasLocalAccess: hasAgentLocalAccess },
options.prMetadata,
);
if (provider === "codex") {
const outputPath = generateOutputPath();
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
const command = await buildCodexCommand({ cwd, outputPath, prompt });
return { command, outputPath, prompt, label: "Codex Review" };
}
if (provider === "claude") {
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
const { command, stdinPrompt } = buildClaudeCommand(prompt);
return { command, stdinPrompt, prompt, cwd, label: "Claude Code Review", captureStdout: true };
}
return null;
},
async onJobComplete(job, meta) {
const cwd = resolveAgentCwd();
if (job.provider === "codex" && meta.outputPath) {
const output = await parseCodexOutput(meta.outputPath);
if (!output) return;
// Override verdict if there are blocking findings (P0/P1) — Codex's
// freeform correctness string can say "mostly correct" with real bugs.
const hasBlockingFindings = output.findings.some((f: any) => f.priority !== null && f.priority <= 1);
job.summary = {
correctness: hasBlockingFindings ? "Issues Found" : output.overall_correctness,
explanation: output.overall_explanation,
confidence: output.overall_confidence_score,
};
if (output.findings.length > 0) {
const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex");
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error);
}
return;
}
if (job.provider === "claude" && meta.stdout) {
const output = parseClaudeStreamOutput(meta.stdout);
if (!output) return;
const total = output.summary.important + output.summary.nit + output.summary.pre_existing;
job.summary = {
correctness: output.summary.important === 0 ? "Correct" : "Issues Found",
explanation: `${output.summary.important} important, ${output.summary.nit} nit, ${output.summary.pre_existing} pre-existing`,
confidence: total === 0 ? 1.0 : Math.max(0, 1.0 - (output.summary.important * 0.2)),
};
if (output.findings.length > 0) {
const annotations = transformClaudeFindings(output.findings, job.source, cwd);
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error);
}
return;
}
},
});
const sharingEnabled =
options.sharingEnabled ?? process.env.PLANNOTATOR_SHARE !== "disabled";
const shareBaseUrl =
(options.shareBaseUrl ?? process.env.PLANNOTATOR_SHARE_URL) || undefined;
let resolveDecision!: (result: {
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}) => void;
const decisionPromise = new Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}>((r) => {
resolveDecision = r;
});
// AI provider setup (graceful — AI features degrade if SDK unavailable)
// Types are `any` because @plannotator/ai is a dynamic import
let aiEndpoints: Record<string, (req: Request) => Promise<Response>> | null =
null;
let aiSessionManager: { disposeAll: () => void } | null = null;
let aiRegistry: { disposeAll: () => void } | null = null;
try {
const ai = await import("../generated/ai/index.js");
const registry = new ai.ProviderRegistry();
const sessionManager = new ai.SessionManager();
// which() helper for Node.js
const whichCmd = (cmd: string): string | null => {
try {
return (
execSync(`which ${cmd}`, {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim() || null
);
} catch {
return null;
}
};
// Claude Agent SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/claude-agent-sdk.js");
const claudePath = whichCmd("claude");
const provider = await ai.createProvider({
type: "claude-agent-sdk",
cwd: process.cwd(),
...(claudePath && { claudeExecutablePath: claudePath }),
});
registry.register(provider);
} catch {
/* Claude SDK not available */
}
// Codex SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/codex-sdk.js");
await import("@openai/codex-sdk");
const codexPath = whichCmd("codex");
const provider = await ai.createProvider({
type: "codex-sdk",
cwd: process.cwd(),
...(codexPath && { codexExecutablePath: codexPath }),
});
registry.register(provider);
} catch {
/* Codex SDK not available */
}
// Pi SDK (Node.js variant)
try {
await import("../generated/ai/providers/pi-sdk-node.js");
const piPath = whichCmd("pi");
if (piPath) {
const provider = await ai.createProvider({
type: "pi-sdk",
cwd: process.cwd(),
piExecutablePath: piPath,
} as any);
if (provider && "fetchModels" in provider) {
await (
provider as { fetchModels: () => Promise<void> }
).fetchModels();
}
registry.register(provider);
}
} catch {
/* Pi not available */
}
// OpenCode SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/opencode-sdk.js");
const opencodePath = whichCmd("opencode");
if (opencodePath) {
const provider = await ai.createProvider({
type: "opencode-sdk",
cwd: process.cwd(),
});
if (provider && "fetchModels" in provider) {
await (
provider as { fetchModels: () => Promise<void> }
).fetchModels();
}
registry.register(provider);
}
} catch {
/* OpenCode not available */
}
if (registry.size > 0) {
aiEndpoints = ai.createAIEndpoints({
registry,
sessionManager,
getCwd: resolveAgentCwd,
});
aiSessionManager = sessionManager;
aiRegistry = registry;
}
} catch {
/* AI backbone not available */
}
const server = createServer(async (req, res) => {
const url = requestUrl(req);
if (url.pathname === "/api/diff" && req.method === "GET") {
json(res, {
rawPatch: currentPatch,
gitRef: currentGitRef,
origin: options.origin ?? "pi",
diffType: hasLocalAccess ? currentDiffType : undefined,
gitContext: hasLocalAccess ? options.gitContext : undefined,
sharingEnabled,
shareBaseUrl,
repoInfo,
isWSL: wslFlag,
...(options.agentCwd && { agentCwd: options.agentCwd }),
...(isPRMode && { prMetadata: prMeta, platformUser }),
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
...(currentError && { error: currentError }),
serverConfig: getServerConfig(gitUser),
});
} else if (url.pathname === "/api/diff/switch" && req.method === "POST") {
if (!hasLocalAccess) {
json(res, { error: "Not available without local file access" }, 400);
return;
}
try {
const body = await parseBody(req);
const newType = body.diffType as DiffType;
if (!newType) {
json(res, { error: "Missing diffType" }, 400);
return;
}
const defaultBranch = options.gitContext?.defaultBranch || "main";
const defaultCwd = options.gitContext?.cwd;
const result = await runGitDiff(newType, defaultBranch, defaultCwd);
currentPatch = result.patch;
currentGitRef = result.label;
currentDiffType = newType;
currentError = result.error;
json(res, {
rawPatch: currentPatch,
gitRef: currentGitRef,
diffType: currentDiffType,
...(currentError ? { error: currentError } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to switch diff";
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/pr-context" && req.method === "GET") {
if (!isPRMode || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
try {
const context = await fetchPRContext(prRef);
json(res, context);
} catch (err) {
json(
res,
{
error:
err instanceof Error ? err.message : "Failed to fetch PR context",
},
500,
);
}
} else if (url.pathname === "/api/pr-action" && req.method === "POST") {
if (!isPRMode || !prMeta || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
try {
const body = await parseBody(req);
const fileComments = (body.fileComments as PRReviewFileComment[]) || [];
console.error(`[pr-action] ${body.action} with ${fileComments.length} file comment(s), headSha=${prMeta.headSha}`);
await submitPRReview(
prRef,
prMeta.headSha,
body.action as "approve" | "comment",
body.body as string,
fileComments,
);
console.error(`[pr-action] Success`);
json(res, { ok: true, prUrl: prMeta.url });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to submit PR review";
console.error(`[pr-action] Failed: ${message}`);
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/pr-viewed" && req.method === "POST") {
if (!isPRMode || !prMeta || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
if (prMeta.platform !== "github") {
json(res, { error: "Viewed sync only supported for GitHub" }, 400);
return;
}
const prNodeId = prMeta.prNodeId;
if (!prNodeId) {
json(res, { error: "PR node ID not available" }, 400);
return;
}
try {
const body = await parseBody(req);
await markPRFilesViewed(
prRef,
prNodeId,
body.filePaths as string[],
body.viewed as boolean,
);
json(res, { ok: true });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to update viewed state";
console.error("[plannotator] /api/pr-viewed error:", message);
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/file-content" && req.method === "GET") {
const filePath = url.searchParams.get("path");
if (!filePath) {
json(res, { error: "Missing path" }, 400);
return;
}
try {
validateFilePath(filePath);
} catch {
json(res, { error: "Invalid path" }, 400);
return;
}
const oldPath = url.searchParams.get("oldPath") || undefined;
if (oldPath) {
try {
validateFilePath(oldPath);
} catch {
json(res, { error: "Invalid path" }, 400);
return;
}
}
// Local mode first (matches Bun server priority)
if (hasLocalAccess && !isPRMode) {
const defaultBranch = options.gitContext?.defaultBranch || "main";
const defaultCwd = options.gitContext?.cwd;
const result = await getFileContentsForDiffCore(
reviewRuntime,
currentDiffType,
defaultBranch,
filePath,
oldPath,
defaultCwd,
);
json(res, result);
return;
}
// PR mode: fetch from platform API using merge-base/head SHAs
if (isPRMode && prRef && prMeta) {
try {
const oldSha = prMeta.mergeBaseSha ?? prMeta.baseSha;
const [oldContent, newContent] = await Promise.all([
fetchPRFileContent(prRef, oldSha, oldPath || filePath),
fetchPRFileContent(prRef, prMeta.headSha, filePath),
]);
json(res, { oldContent, newContent });
} catch (err) {
json(
res,
{
error:
err instanceof Error
? err.message
: "Failed to fetch file content",
},
500,
);
}
return;
}
json(res, { error: "No file access available" }, 400);
} else if (url.pathname === "/api/config" && req.method === "POST") {
try {
const body = (await parseBody(req)) as { displayName?: string; diffOptions?: Record<string, unknown>; conventionalComments?: boolean; planSave?: { enabled?: boolean; customPath?: string | null; saveOnArrival?: boolean } };
const toSave: Record<string, unknown> = {};
if (body.displayName !== undefined) toSave.displayName = body.displayName;
if (body.diffOptions !== undefined) toSave.diffOptions = body.diffOptions;
if (body.conventionalComments !== undefined) toSave.conventionalComments = body.conventionalComments;
if (body.planSave !== undefined) {
if (body.planSave.customPath !== undefined && !isSafeCustomPath(body.planSave.customPath)) {
json(res, { error: "Invalid planSave.customPath" }, 400);
return;
}
toSave.planSave = body.planSave;
}
if (Object.keys(toSave).length > 0) saveConfig(toSave as Parameters<typeof saveConfig>[0]);
json(res, { ok: true });
} catch {
json(res, { error: "Invalid request" }, 400);
}
} else if (url.pathname === "/api/image") {
handleImageRequest(res, url);
} else if (url.pathname === "/api/upload" && req.method === "POST") {
await handleUploadRequest(req, res);
} else if (url.pathname === "/api/agents" && req.method === "GET") {
json(res, { agents: [] });
} else if (url.pathname === "/api/git-add" && req.method === "POST") {
// Staging only available for local diff types that support it (not PR mode, not branch diffs).
// Worktree diff types use composite format "worktree:/path:uncommitted" — extract the base type.
const baseDiffType = currentDiffType.startsWith("worktree:")
? (parseWorktreeDiffType(currentDiffType)?.subType ?? currentDiffType)
: currentDiffType;
const canStage = baseDiffType === "uncommitted" || baseDiffType === "unstaged";
if (isPRMode || !canStage) {
json(res, { error: "Staging not available" }, 400);
return;
}
try {
const body = await parseBody(req);
const filePath = body.filePath as string | undefined;
if (!filePath) {
json(res, { error: "Missing filePath" }, 400);
return;
}
let cwd: string | undefined;
if (currentDiffType.startsWith("worktree:")) {
const parsed = parseWorktreeDiffType(currentDiffType);
if (parsed) cwd = parsed.path;
}
if (!cwd) {
cwd = options.gitContext?.cwd;
}
if (body.undo) {
await gitResetFileCore(reviewRuntime, filePath, cwd);
} else {
await gitAddFileCore(reviewRuntime, filePath, cwd);
}
json(res, { ok: true });
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to stage file";
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/draft") {
await handleDraftRequest(req, res, draftKey);
} else if (url.pathname === "/favicon.svg") {
handleFavicon(res);
} else if (await editorAnnotations.handle(req, res, url)) {
return;
} else if (await externalAnnotations.handle(req, res, url)) {
return;
} else if (await agentJobs.handle(req, res, url)) {
return;
} else if (aiEndpoints && url.pathname.startsWith("/api/ai/")) {
const handler = aiEndpoints[url.pathname];
if (handler) {
try {
const webReq = toWebRequest(req);
const webRes = await handler(webReq);
// Pipe Web Response → node:http response
const headers: Record<string, string> = {};
webRes.headers.forEach((v, k) => {
headers[k] = v;
});
res.writeHead(webRes.status, headers);
if (webRes.body) {
const nodeStream = Readable.fromWeb(webRes.body as any);
nodeStream.pipe(res);
} else {
res.end();
}
} catch (err) {
json(
res,
{ error: err instanceof Error ? err.message : "AI endpoint error" },
500,
);
}
return;
}
json(res, { error: "Not found" }, 404);
} else if (url.pathname === "/api/exit" && req.method === "POST") {
deleteDraft(draftKey);
resolveDecision({ approved: false, feedback: '', annotations: [], exit: true });
json(res, { ok: true });
} else if (url.pathname === "/api/feedback" && req.method === "POST") {
try {
const body = await parseBody(req);
deleteDraft(draftKey);
resolveDecision({
approved: (body.approved as boolean) ?? false,
feedback: (body.feedback as string) || "",
annotations: (body.annotations as unknown[]) || [],
agentSwitch: body.agentSwitch as string | undefined,
});
json(res, { ok: true });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to process feedback";
json(res, { error: message }, 500);
}
} else {
html(res, options.htmlContent);
}
});
const { port, portSource } = await listenOnPort(server);
serverUrl = `http://localhost:${port}`;
const exitHandler = () => agentJobs.killAll();
process.once("exit", exitHandler);
if (options.onReady) {
options.onReady(serverUrl, isRemote, port);
}
return {
port,
portSource,
url: serverUrl,
isRemote,
waitForDecision: () => decisionPromise,
stop: () => {
process.removeListener("exit", exitHandler);
agentJobs.killAll();
aiSessionManager?.disposeAll();
aiRegistry?.disposeAll();
server.close();
// Invoke cleanup callback (e.g., remove temp worktree)
if (options.onCleanup) {
try {
const result = options.onCleanup();
if (result instanceof Promise) result.catch(() => {});
} catch { /* best effort */ }
}
},
};
}