@firstpick/pi-package-webui 0.6.8 → 0.7.0

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/bin/pi-webui.mjs CHANGED
@@ -4,7 +4,7 @@ import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto"
4
4
  import { createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
- import { access, copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
7
+ import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { homedir, networkInterfaces, platform, tmpdir } from "node:os";
9
9
  import path from "node:path";
10
10
  import { StringDecoder } from "node:string_decoder";
@@ -85,7 +85,8 @@ const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROO
85
85
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
86
86
  let piPackageJson = {};
87
87
  try {
88
- const piPackageJsonPath = require.resolve("@earendil-works/pi-coding-agent/package.json", { paths: [packageRoot] });
88
+ const piPackageEntryPath = fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent"));
89
+ const piPackageJsonPath = path.resolve(path.dirname(piPackageEntryPath), "..", "package.json");
89
90
  piPackageJson = JSON.parse(await readFile(piPackageJsonPath, "utf8"));
90
91
  } catch {
91
92
  piPackageJson = {};
@@ -110,9 +111,12 @@ const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
110
111
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
111
112
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
112
113
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
114
+ const PI_RELEASES_API_BASE_URL = (process.env.PI_WEBUI_PI_RELEASES_API_BASE_URL || "https://api.github.com/repos/earendil-works/pi/releases/tags").replace(/\/+$/, "");
115
+ const PI_RELEASES_PAGE_BASE_URL = "https://github.com/earendil-works/pi/releases/tag";
113
116
  const NPM_REGISTRY_URL = (process.env.PI_WEBUI_NPM_REGISTRY_URL || "https://registry.npmjs.org").replace(/\/+$/, "");
114
117
  const UPDATE_STATUS_CACHE_MS = 10 * 60 * 1000;
115
118
  const UPDATE_STATUS_TIMEOUT_MS = 10 * 1000;
119
+ const PI_RELEASE_NOTES_MAX_CHARS = 250_000;
116
120
  const PI_UPDATE_TIMEOUT_MS = 15 * 60 * 1000;
117
121
  const PI_UPDATE_OUTPUT_MAX_CHARS = 120_000;
118
122
  const CORE_UPDATE_PACKAGE_NAMES = [PI_CODING_AGENT_PACKAGE, WEBUI_PACKAGE];
@@ -126,6 +130,10 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
126
130
  const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
127
131
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
128
132
  const BODY_LIMIT_BYTES = 1024 * 1024;
133
+ const RECOVERY_ENDPOINT_PATH = "/api/recovery/plan";
134
+ const RECOVERY_BODY_LIMIT_BYTES = 256 * 1024;
135
+ const RECOVERY_PROMPT_MAX_CHARS = 200_000;
136
+ const RECOVERY_TITLE = "Anthropic compatibility recovery";
129
137
  const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
130
138
  const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
131
139
  const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
@@ -146,6 +154,9 @@ const ATTACHMENT_UPLOAD_MAX_FILE_BYTES = 64 * 1024 * 1024;
146
154
  const ATTACHMENT_UPLOAD_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
147
155
  const INLINE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
148
156
  const INLINE_IMAGE_TOTAL_MAX_BYTES = 16 * 1024 * 1024;
157
+ // Keep enough headroom for base64-encoded inline images plus their RPC envelope.
158
+ // Pi RPC output is JSONL, so this caps one physical line rather than a response.
159
+ const PI_RPC_JSONL_LINE_MAX_BYTES = 32 * 1024 * 1024;
149
160
  const RPC_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
150
161
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
151
162
  const SETTINGS_TRANSPORT_CHOICES = ["sse", "websocket", "websocket-cached", "auto"];
@@ -302,6 +313,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
302
313
  ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
303
314
  ["releaseNpm", "@firstpick/pi-extension-release-npm"],
304
315
  ["releaseAur", "@firstpick/pi-extension-release-aur"],
316
+ ["aurReview", "@firstpick/pi-extension-aur-review"],
305
317
  ["workflows", "@firstpick/pi-extension-workflows"],
306
318
  ["safetyGuard", "@firstpick/pi-extension-safety-guard"],
307
319
  ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills"],
@@ -577,22 +589,123 @@ async function fetchJsonWithTimeout(url, { timeoutMs = UPDATE_STATUS_TIMEOUT_MS,
577
589
  return response.json();
578
590
  }
579
591
 
592
+ function installedPiRelease() {
593
+ const version = String(piPackageJson.version || "").trim().replace(/^v/i, "");
594
+ if (!parsePackageVersion(version)) throw makeHttpError(503, "The installed Pi version could not be determined");
595
+ const tagName = `v${version}`;
596
+ return {
597
+ version,
598
+ tagName,
599
+ apiUrl: `${PI_RELEASES_API_BASE_URL}/${encodeURIComponent(tagName)}`,
600
+ pageUrl: `${PI_RELEASES_PAGE_BASE_URL}/${encodeURIComponent(tagName)}`,
601
+ };
602
+ }
603
+
604
+ let piReleaseNotesCache = null;
605
+
606
+ async function installedPiReleaseNotes() {
607
+ const release = installedPiRelease();
608
+ if (piReleaseNotesCache?.tagName === release.tagName) return piReleaseNotesCache;
609
+ if (process.env.PI_OFFLINE) throw makeHttpError(503, "Pi release notes are unavailable while PI_OFFLINE is set");
610
+
611
+ let data;
612
+ try {
613
+ data = await fetchJsonWithTimeout(release.apiUrl, {
614
+ headers: {
615
+ "User-Agent": `pi-webui/${packageJson.version} pi/${release.version}`,
616
+ accept: "application/vnd.github+json",
617
+ "X-GitHub-Api-Version": "2022-11-28",
618
+ },
619
+ });
620
+ } catch (error) {
621
+ throw makeHttpError(502, `Could not fetch Pi ${release.tagName} release notes from GitHub: ${sanitizeError(error)}`);
622
+ }
623
+
624
+ const responseTag = typeof data?.tag_name === "string" ? data.tag_name.trim() : "";
625
+ if (responseTag && responseTag !== release.tagName) {
626
+ throw makeHttpError(502, `GitHub returned release ${responseTag} instead of ${release.tagName}`);
627
+ }
628
+ const fullBody = typeof data?.body === "string" ? data.body.trim() : "";
629
+ piReleaseNotesCache = {
630
+ version: release.version,
631
+ tagName: release.tagName,
632
+ title: truncateLongText(typeof data?.name === "string" ? data.name.trim() : "", 240) || `Pi ${release.tagName}`,
633
+ body: truncateLongText(fullBody, PI_RELEASE_NOTES_MAX_CHARS),
634
+ truncated: fullBody.length > PI_RELEASE_NOTES_MAX_CHARS,
635
+ publishedAt: typeof data?.published_at === "string" ? data.published_at : "",
636
+ url: release.pageUrl,
637
+ };
638
+ return piReleaseNotesCache;
639
+ }
640
+
641
+ const stderrMirrorFailureListeners = new Set();
642
+ const stderrMirrorErrorHandlers = new WeakSet();
643
+
644
+ function ensureStderrMirrorErrorHandler(stream) {
645
+ if (stderrMirrorErrorHandlers.has(stream)) return;
646
+ stderrMirrorErrorHandlers.add(stream);
647
+ stream.on("error", (error) => {
648
+ // Do not log from this handler: stderr is the failing sink and recursive
649
+ // diagnostics can otherwise terminate the process. Active writers report
650
+ // the failure through their normal Web UI event path instead.
651
+ for (const reportFailure of [...stderrMirrorFailureListeners]) reportFailure(error);
652
+ });
653
+ }
654
+
655
+ function mirrorPiStderr(text, onFailure) {
656
+ const stream = process.stderr;
657
+ let reported = false;
658
+ const reportFailure = (error) => {
659
+ if (reported) return;
660
+ reported = true;
661
+ stderrMirrorFailureListeners.delete(reportFailure);
662
+ onFailure(error);
663
+ };
664
+
665
+ if (!stream?.writable || stream.destroyed || stream.writableEnded) {
666
+ reportFailure(new Error("Web UI stderr sink is not writable"));
667
+ return;
668
+ }
669
+
670
+ ensureStderrMirrorErrorHandler(stream);
671
+ stderrMirrorFailureListeners.add(reportFailure);
672
+ try {
673
+ stream.write(text, (error) => {
674
+ stderrMirrorFailureListeners.delete(reportFailure);
675
+ if (error) reportFailure(error);
676
+ });
677
+ } catch (error) {
678
+ reportFailure(error);
679
+ }
680
+ }
681
+
580
682
  class PiRpcProcess {
581
- constructor({ command, args, displayCommand, cwd }) {
683
+ constructor({ command, args, displayCommand, cwd, env = process.env }) {
582
684
  this.command = command;
583
685
  this.args = args;
584
686
  this.displayCommand = displayCommand;
585
687
  this.cwd = cwd;
688
+ this.env = env;
586
689
  this.child = undefined;
587
690
  this.pending = new Map();
588
691
  this.listeners = new Set();
589
692
  this.startedAt = new Date().toISOString();
693
+ this.stderrMirrorFailureReported = false;
694
+ }
695
+
696
+ reportStderrMirrorFailure(error) {
697
+ if (this.stderrMirrorFailureReported) return;
698
+ this.stderrMirrorFailureReported = true;
699
+ this.emit({
700
+ type: "pi_stderr_sink_error",
701
+ error: `Pi RPC stderr could not be mirrored to the Web UI server log: ${sanitizeError(error)}`,
702
+ });
590
703
  }
591
704
 
592
705
  start() {
593
706
  this.child = spawn(this.command, this.args, {
594
707
  cwd: this.cwd,
595
- env: process.env,
708
+ env: this.env,
596
709
  stdio: ["pipe", "pipe", "pipe"],
597
710
  windowsHide: true,
598
711
  });
@@ -611,8 +724,10 @@ class PiRpcProcess {
611
724
  this.attachJsonlReader(this.child.stdout, (line) => this.handleStdoutLine(line));
612
725
  this.attachTextReader(this.child.stderr, (text) => {
613
726
  if (text.length > 0) {
614
- process.stderr.write(text);
727
+ // Publish before attempting the optional terminal mirror so a closed
728
+ // stderr sink cannot hide Pi diagnostics from browser clients.
615
729
  this.emit({ type: "pi_stderr", text });
730
+ mirrorPiStderr(text, (error) => this.reportStderrMirrorFailure(error));
616
731
  }
617
732
  });
618
733
 
@@ -641,24 +756,56 @@ class PiRpcProcess {
641
756
  attachJsonlReader(stream, onLine) {
642
757
  const decoder = new StringDecoder("utf8");
643
758
  let buffer = "";
759
+ let bufferBytes = 0;
760
+ let discardingOversizedLine = false;
761
+
762
+ const emitOversizedLine = () => this.emit({
763
+ type: "pi_stdout_line_too_large",
764
+ error: `Discarded a Pi RPC JSONL line larger than ${PI_RPC_JSONL_LINE_MAX_BYTES} bytes`,
765
+ maxBytes: PI_RPC_JSONL_LINE_MAX_BYTES,
766
+ });
767
+ const consume = (chunk) => {
768
+ let input = chunk;
769
+ while (input.length > 0) {
770
+ if (discardingOversizedLine) {
771
+ const newlineIndex = input.indexOf("\n");
772
+ if (newlineIndex === -1) return;
773
+ discardingOversizedLine = false;
774
+ input = input.slice(newlineIndex + 1);
775
+ continue;
776
+ }
777
+
778
+ const newlineIndex = input.indexOf("\n");
779
+ const segment = newlineIndex === -1 ? input : input.slice(0, newlineIndex);
780
+ const segmentBytes = Buffer.byteLength(segment);
781
+ if (bufferBytes + segmentBytes > PI_RPC_JSONL_LINE_MAX_BYTES) {
782
+ buffer = "";
783
+ bufferBytes = 0;
784
+ emitOversizedLine();
785
+ if (newlineIndex === -1) {
786
+ discardingOversizedLine = true;
787
+ return;
788
+ }
789
+ input = input.slice(newlineIndex + 1);
790
+ continue;
791
+ }
644
792
 
645
- stream.on("data", (chunk) => {
646
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
647
- while (true) {
648
- const newlineIndex = buffer.indexOf("\n");
649
- if (newlineIndex === -1) break;
650
- let line = buffer.slice(0, newlineIndex);
651
- buffer = buffer.slice(newlineIndex + 1);
793
+ buffer += segment;
794
+ bufferBytes += segmentBytes;
795
+ if (newlineIndex === -1) return;
796
+ let line = buffer;
797
+ buffer = "";
798
+ bufferBytes = 0;
652
799
  if (line.endsWith("\r")) line = line.slice(0, -1);
653
800
  onLine(line);
801
+ input = input.slice(newlineIndex + 1);
654
802
  }
655
- });
803
+ };
656
804
 
805
+ stream.on("data", (chunk) => consume(typeof chunk === "string" ? chunk : decoder.write(chunk)));
657
806
  stream.on("end", () => {
658
- buffer += decoder.end();
659
- if (buffer.length > 0) {
660
- onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
661
- }
807
+ consume(decoder.end());
808
+ if (!discardingOversizedLine && buffer.length > 0) onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
662
809
  });
663
810
  }
664
811
 
@@ -1951,6 +2098,9 @@ async function restoreGitWorkflowGenerationProfile(tab) {
1951
2098
 
1952
2099
  async function startGitWorkflowGeneration(tab, body = {}) {
1953
2100
  if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
2101
+ // Browser state is untrusted. When it claims an approved content token,
2102
+ // verify the exact current index again at this server action boundary.
2103
+ await assertExpectedStagedContentHash(tab, body);
1954
2104
  const preferences = await readGitWorkflowPreferences();
1955
2105
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
1956
2106
 
@@ -4333,6 +4483,15 @@ let activeGitWorkflowProcess = null;
4333
4483
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
4334
4484
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
4335
4485
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
4486
+ // Must remain byte-for-byte aligned with pi-extension-aur-review/src/git.ts.
4487
+ const STAGED_CONTENT_HASH_DOMAIN = "firstpick/aur-review/staged-content/v1\0";
4488
+ const STAGED_CONTENT_HASH_TIMEOUT_MS = 10_000;
4489
+ const STAGED_CONTENT_HASH_OUTPUT_LIMIT = 4 * 1024 * 1024;
4490
+ const STAGED_CONTENT_HASH_ARGS = [
4491
+ "-c", "core.quotepath=false",
4492
+ "-c", "diff.external=",
4493
+ "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--no-renames", "--",
4494
+ ];
4336
4495
  const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified: 2, staged: 3, conflicted: 4 });
4337
4496
 
4338
4497
  async function getGitRoot(cwd) {
@@ -4359,6 +4518,103 @@ async function runGitReadCommand(root, args, options = {}) {
4359
4518
  return (await runGitReadCommandDetailed(root, args, options)).output;
4360
4519
  }
4361
4520
 
4521
+ /**
4522
+ * Read binary cached-diff bytes without decoding them. This is intentionally
4523
+ * separate from runCommand(), whose string buffering is appropriate for UI
4524
+ * output but would corrupt the staged-content approval token.
4525
+ */
4526
+ function runGitStagedContentHashCommand(root) {
4527
+ return new Promise((resolve, reject) => {
4528
+ const child = spawn("git", STAGED_CONTENT_HASH_ARGS, {
4529
+ cwd: root,
4530
+ stdio: ["ignore", "pipe", "pipe"],
4531
+ windowsHide: true,
4532
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", LC_ALL: "C" },
4533
+ });
4534
+ const stdout = [];
4535
+ const stderr = [];
4536
+ let stdoutBytes = 0;
4537
+ let stderrBytes = 0;
4538
+ let settled = false;
4539
+ const finish = (error, result) => {
4540
+ if (settled) return;
4541
+ settled = true;
4542
+ clearTimeout(timeout);
4543
+ if (error) reject(error);
4544
+ else resolve(result);
4545
+ };
4546
+ const stop = (message) => {
4547
+ try { child.kill("SIGKILL"); } catch { /* process already exited */ }
4548
+ finish(makeUserFacingError(message));
4549
+ };
4550
+ const timeout = setTimeout(() => stop(`git diff --cached timed out after ${STAGED_CONTENT_HASH_TIMEOUT_MS / 1000} seconds`), STAGED_CONTENT_HASH_TIMEOUT_MS);
4551
+ child.stdout.on("data", (chunk) => {
4552
+ const bytes = Buffer.from(chunk);
4553
+ stdoutBytes += bytes.length;
4554
+ if (stdoutBytes > STAGED_CONTENT_HASH_OUTPUT_LIMIT) {
4555
+ stop(`git diff --cached output exceeded the ${STAGED_CONTENT_HASH_OUTPUT_LIMIT / 1024 / 1024} MiB staged-content safety limit`);
4556
+ return;
4557
+ }
4558
+ stdout.push(bytes);
4559
+ });
4560
+ child.stderr.on("data", (chunk) => {
4561
+ const bytes = Buffer.from(chunk);
4562
+ stderrBytes += bytes.length;
4563
+ if (stderrBytes <= 64 * 1024) stderr.push(bytes);
4564
+ });
4565
+ child.on("error", (error) => finish(makeUserFacingError(formatCommandSpawnError("git", error))));
4566
+ child.on("close", (exitCode) => {
4567
+ if (exitCode !== 0) {
4568
+ const detail = Buffer.concat(stderr).toString("utf8").trim().slice(0, 1200);
4569
+ finish(makeUserFacingError(detail ? `git diff --cached failed: ${detail}` : `git diff --cached failed with exit code ${exitCode ?? "unknown"}`));
4570
+ return;
4571
+ }
4572
+ finish(null, Buffer.concat(stdout));
4573
+ });
4574
+ });
4575
+ }
4576
+
4577
+ function stagedContentHashFromDiff(stagedDiff) {
4578
+ return createHash("sha256").update(STAGED_CONTENT_HASH_DOMAIN).update(stagedDiff).digest("hex");
4579
+ }
4580
+
4581
+ async function readStagedContentHash(root) {
4582
+ // `git diff --cached` correctly compares the index to the empty tree when
4583
+ // HEAD is unborn, so no HEAD lookup is needed (or allowed) here.
4584
+ const stagedDiff = await runGitStagedContentHashCommand(root);
4585
+ return {
4586
+ stagedDiff,
4587
+ hasStagedChanges: stagedDiff.length > 0,
4588
+ stagedContentHash: stagedDiff.length > 0 ? stagedContentHashFromDiff(stagedDiff) : null,
4589
+ };
4590
+ }
4591
+
4592
+ /** Read-only same-tab digest of the exact staged content git can commit. */
4593
+ async function stagedContentHashForTab(tab) {
4594
+ const root = await getGitRoot(tab.cwd);
4595
+ const staged = await readStagedContentHash(root);
4596
+ return { root, hasStagedChanges: staged.hasStagedChanges, stagedContentHash: staged.stagedContentHash };
4597
+ }
4598
+
4599
+ function expectedStagedContentHashFromBody(body = {}) {
4600
+ const expected = body?.expectedStagedContentHash;
4601
+ if (expected === undefined) return ""; // Legacy Guided Git flow: no review was required.
4602
+ if (typeof expected !== "string" || !/^[a-f0-9]{64}$/i.test(expected)) {
4603
+ throw makeHttpError(400, "expectedStagedContentHash must be a SHA-256 hex digest");
4604
+ }
4605
+ return expected;
4606
+ }
4607
+
4608
+ async function assertExpectedStagedContentHash(tab, body = {}) {
4609
+ const expected = expectedStagedContentHashFromBody(body);
4610
+ if (!expected) return "";
4611
+ const current = await stagedContentHashForTab(tab);
4612
+ if (!current.hasStagedChanges || current.stagedContentHash !== expected) {
4613
+ throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before continuing.");
4614
+ }
4615
+ return expected;
4616
+ }
4617
+
4362
4618
  function gitBranchFromPorcelainStatus(statusText) {
4363
4619
  for (const line of String(statusText || "").split(/\r?\n/)) {
4364
4620
  if (!line.startsWith("# branch.head ")) continue;
@@ -5894,18 +6150,17 @@ async function readGitWorkflowMessageFilesForTransfer(root, messageCwd = root) {
5894
6150
  return files;
5895
6151
  }
5896
6152
 
5897
- async function snapshotGitWorkflowBranchState(root, cwd = root) {
6153
+ async function snapshotGitWorkflowBranchState(root, cwd = root, expectedStagedContentHash = "") {
5898
6154
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
5899
- const diffResult = await runGitWorkflowCommand(["diff", "--cached", "--binary", "--full-index"], {
5900
- cwd: root,
5901
- label: "git diff --cached --binary --full-index",
5902
- timeoutMs: 60 * 1000,
5903
- });
5904
- if (diffResult.exitCode !== 0 || diffResult.timedOut || diffResult.cancelled || diffResult.error) {
5905
- throw new Error((diffResult.stderr || diffResult.stdout || diffResult.error || "Unable to read staged changes for the PR worktree").trim());
6155
+ // Preserve raw patch bytes: string decoding would corrupt binary staged
6156
+ // changes before `git apply --index` can copy them to the PR worktree.
6157
+ const staged = await readStagedContentHash(root);
6158
+ if (expectedStagedContentHash && (!staged.hasStagedChanges || staged.stagedContentHash !== expectedStagedContentHash)) {
6159
+ throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before creating a PR worktree.");
5906
6160
  }
5907
6161
  return {
5908
- stagedPatch: diffResult.stdout || "",
6162
+ stagedPatch: staged.stagedDiff,
6163
+ stagedContentHash: staged.stagedContentHash,
5909
6164
  messageFiles: await readGitWorkflowMessageFilesForTransfer(root, messageCwd),
5910
6165
  };
5911
6166
  }
@@ -5913,10 +6168,10 @@ async function snapshotGitWorkflowBranchState(root, cwd = root) {
5913
6168
  async function applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath) {
5914
6169
  const copiedMessageFiles = [];
5915
6170
  let appliedStagedPatch = false;
5916
- const patchText = String(snapshot?.stagedPatch || "");
5917
- if (patchText.trim()) {
6171
+ const patchBytes = Buffer.isBuffer(snapshot?.stagedPatch) ? snapshot.stagedPatch : Buffer.alloc(0);
6172
+ if (patchBytes.length > 0) {
5918
6173
  const patchPath = path.join(tmpdir(), `pi-webui-staged-worktree-${process.pid}-${Date.now()}-${randomUUID()}.patch`);
5919
- await writeFile(patchPath, patchText, "utf8");
6174
+ await writeFile(patchPath, patchBytes);
5920
6175
  try {
5921
6176
  const applyResult = await runGitWorkflowCommand(["apply", "--index", "--whitespace=nowarn", patchPath], {
5922
6177
  cwd: worktreePath,
@@ -5962,7 +6217,8 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
5962
6217
  const root = await getGitRoot(tab.cwd);
5963
6218
  const branch = cleanGitBranchName(body.branch || body.branchName);
5964
6219
  await validateGitBranchName(root, branch);
5965
- const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd);
6220
+ const expectedStagedContentHash = expectedStagedContentHashFromBody(body);
6221
+ const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd, expectedStagedContentHash);
5966
6222
  let createdResult = null;
5967
6223
  try {
5968
6224
  createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
@@ -6167,6 +6423,7 @@ function gitWorkflowCommandPayload(result) {
6167
6423
  // guard are enforced at the router before dispatch — never dispatch on path
6168
6424
  // alone, or cross-origin GETs (image/script tags) could drive git mutations.
6169
6425
  const GIT_WORKFLOW_READONLY_PATHS = new Set([
6426
+ "/api/git-workflow/staged-content",
6170
6427
  "/api/git-workflow/message",
6171
6428
  "/api/git-workflow/default-commit-message",
6172
6429
  "/api/git-workflow/branch-name",
@@ -6194,6 +6451,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6194
6451
  const cwd = tab?.cwd || tabOrCwd || options.cwd;
6195
6452
  try {
6196
6453
  switch (pathname) {
6454
+ case "/api/git-workflow/staged-content":
6455
+ if (!tab) throw new Error("Staged-content lookup requires a Web UI tab");
6456
+ return { ok: true, data: await stagedContentHashForTab(tab) };
6197
6457
  case "/api/git-workflow/message":
6198
6458
  return { ok: true, data: await readGitWorkflowMessages(cwd) };
6199
6459
  case "/api/git-workflow/default-commit-message":
@@ -6245,6 +6505,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6245
6505
  case "/api/git-workflow/commit": {
6246
6506
  const variant = String(body.variant || "").trim();
6247
6507
  if (!["short", "long", "input"].includes(variant)) throw new Error("variant must be 'short', 'long', or 'input'");
6508
+ // Recheck here as well as in the browser. A staged index can change
6509
+ // between the browser's read-only check and this mutating request.
6510
+ await assertExpectedStagedContentHash(tab || { cwd }, body);
6248
6511
  if (variant === "input") {
6249
6512
  const root = await getGitRoot(cwd);
6250
6513
  const message = cleanGitCommitMessageInput(body.message);
@@ -6397,7 +6660,7 @@ async function readBundledThemes() {
6397
6660
  function normalizeStaticPath(urlPath) {
6398
6661
  if (urlPath === "/") return "index.html";
6399
6662
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
6400
- if (!["index.html", "app.js", "voice-conversation.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6663
+ if (!["index.html", "app.js", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6401
6664
  return name;
6402
6665
  }
6403
6666
 
@@ -6714,6 +6977,26 @@ try {
6714
6977
 
6715
6978
  process.env.PI_WEBUI_HOST = options.host;
6716
6979
  process.env.PI_WEBUI_PORT = String(options.port);
6980
+ const recoveryEndpointToken = String(process.env.PI_WEBUI_RECOVERY_TOKEN || "").trim() || `${randomUUID()}${randomUUID()}`;
6981
+
6982
+ function recoveryLoopbackUrl(bindHost = options.host) {
6983
+ const normalized = String(bindHost || "").trim().toLowerCase().replace(/^\[|\]$/g, "");
6984
+ if (normalized === "::" || normalized === "::1") return `http://[::1]:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6985
+ if (normalized === "localhost") return `http://localhost:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6986
+ if (normalized === "0.0.0.0" || normalized.startsWith("127.")) return `http://127.0.0.1:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6987
+ return "";
6988
+ }
6989
+
6990
+ function piRpcEnvironment() {
6991
+ const env = { ...process.env };
6992
+ const recoveryUrl = recoveryLoopbackUrl();
6993
+ if (recoveryUrl) {
6994
+ env.PI_WEBUI_RECOVERY_URL = recoveryUrl;
6995
+ env.PI_WEBUI_RECOVERY_TOKEN = recoveryEndpointToken;
6996
+ }
6997
+ return env;
6998
+ }
6999
+
6717
7000
  await configureDevDependencyResolution();
6718
7001
 
6719
7002
  const startupDelayMs = Number.parseInt(process.env.PI_WEBUI_START_DELAY_MS || "", 10);
@@ -6814,9 +7097,11 @@ async function workspacePackageRootForName(packageName) {
6814
7097
  return null;
6815
7098
  }
6816
7099
  for (const entry of entries) {
7100
+ // Workspace package directories use the pi-* convention. Confirm every
7101
+ // eligible sibling by its manifest name, never the folder prefix alone.
6817
7102
  if (!entry.isDirectory() || !entry.name.startsWith("pi-")) continue;
6818
7103
  const candidate = path.join(root, entry.name);
6819
- if ((await packageNameForResourcePath(path.join(candidate, "index.ts"))) === packageName) return candidate;
7104
+ if ((await packageNameForResourcePath(path.join(candidate, "package.json"))) === packageName) return candidate;
6820
7105
  }
6821
7106
  return null;
6822
7107
  }
@@ -7417,7 +7702,7 @@ async function flushCompactionQueue(tab, event = {}) {
7417
7702
  let startedPrompt = false;
7418
7703
  while (remaining.length) {
7419
7704
  const item = remaining[0];
7420
- const command = startedPrompt ? queuedStreamingCommand(item) : queuedPromptCommand(item);
7705
+ const command = startedPrompt ? queuedRetryCommand(item) : queuedPromptCommand(item);
7421
7706
  if (!startedPrompt) {
7422
7707
  const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
7423
7708
  if (pendingThinkingResponse?.success === false) throw new Error(pendingThinkingResponse.error || "failed to apply queued thinking level");
@@ -7755,7 +8040,7 @@ function attachRpcToTab(tab, rpc) {
7755
8040
  scopedEvent = { ...scopedEvent, tabActivity: tabActivitySnapshot(tab), pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length };
7756
8041
  recordEvent(scopedEvent);
7757
8042
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
7758
- if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
8043
+ if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
7759
8044
  if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
7760
8045
  });
7761
8046
  }
@@ -7772,7 +8057,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
7772
8057
  const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
7773
8058
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
7774
8059
  const piCommand = await resolvePiCommand(piArgs);
7775
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd });
8060
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
7776
8061
  const createdAt = new Date().toISOString();
7777
8062
  const tab = {
7778
8063
  id,
@@ -7884,6 +8169,79 @@ function webuiSubagentsData() {
7884
8169
  };
7885
8170
  }
7886
8171
 
8172
+ function normalizeWebuiSubagentTranscriptValue(value, maxLength = WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH) {
8173
+ return String(value ?? "").replace(/\r/g, "").slice(0, maxLength);
8174
+ }
8175
+
8176
+ function normalizeWebuiSubagentTranscriptLines(value) {
8177
+ return String(value ?? "").replace(/\r/g, "").split("\n").map((line) => line.slice(0, WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH));
8178
+ }
8179
+
8180
+ function normalizeWebuiSubagentTranscript(value) {
8181
+ const messages = [];
8182
+ let remainingParts = WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT;
8183
+ const rawMessages = Array.isArray(value) ? value : [];
8184
+ for (let messageIndex = rawMessages.length - 1; messageIndex >= 0 && remainingParts > 0; messageIndex -= 1) {
8185
+ const rawMessage = rawMessages[messageIndex];
8186
+ const role = rawMessage?.role;
8187
+ if (role !== "assistant" && role !== "toolResult") continue;
8188
+ const rawContent = Array.isArray(rawMessage.content) ? rawMessage.content : [{ type: "text", text: rawMessage.content }];
8189
+ const content = [];
8190
+ for (let partIndex = rawContent.length - 1; partIndex >= 0 && remainingParts > 0; partIndex -= 1) {
8191
+ const rawPart = rawContent[partIndex];
8192
+ if (role === "assistant" && rawPart?.type === "toolCall") {
8193
+ const name = normalizeWebuiSubagentText(rawPart.name || rawPart.toolName || rawPart.toolCall?.name, 120) || "tool";
8194
+ let argumentsText = "{}";
8195
+ try {
8196
+ const argumentsValue = rawPart.arguments ?? rawPart.args ?? rawPart.input ?? rawPart.toolCall?.arguments ?? {};
8197
+ argumentsText = normalizeWebuiSubagentTranscriptValue(typeof argumentsValue === "string" ? argumentsValue.replace(/\n/g, "\\n") : JSON.stringify(argumentsValue));
8198
+ } catch {
8199
+ // Keep the bounded placeholder when the helper received a cyclic value.
8200
+ }
8201
+ content.unshift({
8202
+ type: "toolCall",
8203
+ name,
8204
+ arguments: argumentsText,
8205
+ ...(normalizeWebuiSubagentText(rawPart.id || rawPart.toolCallId || rawPart.tool_call_id, 240) ? { id: normalizeWebuiSubagentText(rawPart.id || rawPart.toolCallId || rawPart.tool_call_id, 240) } : {}),
8206
+ });
8207
+ remainingParts -= 1;
8208
+ continue;
8209
+ }
8210
+ const type = role === "assistant" && rawPart?.type === "thinking" ? "thinking" : "text";
8211
+ if (rawPart?.type !== "text" && typeof rawPart !== "string" && type !== "thinking") continue;
8212
+ const rawText = typeof rawPart === "string"
8213
+ ? rawPart
8214
+ : type === "thinking" ? rawPart.thinking ?? rawPart.text ?? rawPart.content : rawPart.text ?? rawPart.content;
8215
+ if (typeof rawText !== "string") continue;
8216
+ const property = type === "thinking" ? "thinking" : "text";
8217
+ const lines = normalizeWebuiSubagentTranscriptLines(rawText);
8218
+ for (let lineIndex = lines.length - 1; lineIndex >= 0 && remainingParts > 0; lineIndex -= 1) {
8219
+ const line = lines[lineIndex];
8220
+ if (line.trim().toLowerCase() === "(no output)") continue;
8221
+ const previous = content[0];
8222
+ if (previous?.type === type) previous[property] = `${line}\n${previous[property]}`;
8223
+ else content.unshift({ type, [property]: line });
8224
+ remainingParts -= 1;
8225
+ }
8226
+ }
8227
+ if (!content.length) continue;
8228
+ const timestamp = Number.isFinite(rawMessage.timestamp)
8229
+ ? rawMessage.timestamp
8230
+ : normalizeWebuiSubagentText(rawMessage.timestamp, 128) || undefined;
8231
+ messages.unshift({
8232
+ role,
8233
+ ...(timestamp ? { timestamp } : {}),
8234
+ ...(role === "toolResult" ? {
8235
+ ...(normalizeWebuiSubagentText(rawMessage.toolCallId || rawMessage.tool_call_id, 240) ? { toolCallId: normalizeWebuiSubagentText(rawMessage.toolCallId || rawMessage.tool_call_id, 240) } : {}),
8236
+ ...(normalizeWebuiSubagentText(rawMessage.toolName || rawMessage.name, 120) ? { toolName: normalizeWebuiSubagentText(rawMessage.toolName || rawMessage.name, 120) } : {}),
8237
+ ...(rawMessage.isError === true ? { isError: true } : {}),
8238
+ } : {}),
8239
+ content,
8240
+ });
8241
+ }
8242
+ return messages;
8243
+ }
8244
+
7887
8245
  function normalizeWebuiSubagentOutput(value, selection) {
7888
8246
  if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
7889
8247
  const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
@@ -7895,6 +8253,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
7895
8253
  args: normalizeWebuiSubagentText(entry?.args, 500),
7896
8254
  endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
7897
8255
  })).filter((entry) => entry.tool);
8256
+ const transcript = normalizeWebuiSubagentTranscript(rawAgent.transcript);
7898
8257
  return {
7899
8258
  version: 1,
7900
8259
  runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
@@ -7917,6 +8276,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
7917
8276
  tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
7918
8277
  recentTools,
7919
8278
  recentOutput,
8279
+ transcript,
7920
8280
  error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
7921
8281
  },
7922
8282
  };
@@ -8481,6 +8841,15 @@ function broadcastTabEvent(tab, event) {
8481
8841
  for (const client of tab.sseClients) sendSse(client, event);
8482
8842
  }
8483
8843
 
8844
+ function broadcastServerEvent(event) {
8845
+ recordEvent(event);
8846
+ const clients = new Set();
8847
+ for (const tab of tabs.values()) {
8848
+ for (const client of tab.sseClients) clients.add(client);
8849
+ }
8850
+ for (const client of clients) sendSse(client, event);
8851
+ }
8852
+
8484
8853
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
8485
8854
  if (!tab) return false;
8486
8855
  const rawTitle = maxLength ? truncateTabTitle(title, maxLength) : String(title || "").replace(/\s+/g, " ").trim();
@@ -8554,7 +8923,7 @@ async function updateTabCwd(id, cwd) {
8554
8923
  clearExtensionWidgets(tab);
8555
8924
  clearWebuiSubagents(tab);
8556
8925
  resetNaturalConversationMode(tab);
8557
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8926
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8558
8927
  attachRpcToTab(tab, rpc);
8559
8928
  rpc.start();
8560
8929
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
@@ -8594,7 +8963,7 @@ async function restartTabRpc(tab, reason = "reload") {
8594
8963
  clearExtensionWidgets(tab);
8595
8964
  clearWebuiSubagents(tab);
8596
8965
  resetNaturalConversationMode(tab);
8597
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8966
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8598
8967
  attachRpcToTab(tab, rpc);
8599
8968
  rpc.start();
8600
8969
 
@@ -9809,6 +10178,88 @@ async function getFileContentData(tab, requestedPath = "") {
9809
10178
  };
9810
10179
  }
9811
10180
 
10181
+ function aurReviewReportPathSegments(value = "") {
10182
+ const requested = String(value || "").trim();
10183
+ if (!requested || requested.length > 1024 || requested.includes("\0")) throw makeHttpError(400, "Report path must be a non-empty repo-root-relative path");
10184
+ if (path.isAbsolute(requested) || path.win32.isAbsolute(requested) || requested.includes("\\")) {
10185
+ throw makeHttpError(400, "Report path must be a repo-root-relative path");
10186
+ }
10187
+ const segments = requested.split("/");
10188
+ if (segments.some((segment) => !segment || segment === "." || segment === "..")) {
10189
+ throw makeHttpError(400, "Report path cannot contain traversal segments");
10190
+ }
10191
+ return segments;
10192
+ }
10193
+
10194
+ async function canonicalGitRootForTab(tab) {
10195
+ const root = await getGitRoot(tab.cwd);
10196
+ try {
10197
+ return await realpath(root);
10198
+ } catch {
10199
+ throw makeHttpError(404, "Git repository root is no longer accessible");
10200
+ }
10201
+ }
10202
+
10203
+ async function readBoundedAurReviewReport(targetPath) {
10204
+ const handle = await open(targetPath, "r");
10205
+ try {
10206
+ const info = await handle.stat();
10207
+ if (!info.isFile()) throw makeHttpError(400, "Report path is not a regular file");
10208
+ if (info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `Report is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
10209
+ const chunks = [];
10210
+ let total = 0;
10211
+ while (true) {
10212
+ const remaining = FILE_VIEWER_MAX_BYTES + 1 - total;
10213
+ if (remaining <= 0) throw makeHttpError(413, `Report is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
10214
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
10215
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, total);
10216
+ if (bytesRead === 0) break;
10217
+ chunks.push(chunk.subarray(0, bytesRead));
10218
+ total += bytesRead;
10219
+ }
10220
+ return { buffer: Buffer.concat(chunks, total), info };
10221
+ } finally {
10222
+ await handle.close().catch(() => {});
10223
+ }
10224
+ }
10225
+
10226
+ /** Read-only AUR-review report access rooted at the tab's canonical Git root. */
10227
+ async function getAurReviewReportContentData(tab, { path: requestedPath = "", repoRoot = "" } = {}) {
10228
+ if (typeof repoRoot !== "string" || !repoRoot || repoRoot.includes("\0")) {
10229
+ throw makeHttpError(400, "repoRoot is required for an AUR review report");
10230
+ }
10231
+ const root = await canonicalGitRootForTab(tab);
10232
+ if (repoRoot !== root) throw makeHttpError(403, "Report repoRoot does not match this tab's canonical Git root");
10233
+ const segments = aurReviewReportPathSegments(requestedPath);
10234
+ let targetPath = root;
10235
+ let info;
10236
+ for (const [index, segment] of segments.entries()) {
10237
+ targetPath = path.join(targetPath, segment);
10238
+ try {
10239
+ info = await lstat(targetPath);
10240
+ } catch (error) {
10241
+ throw makeHttpError(error?.code === "ENOENT" ? 404 : 400, `Report path not found: ${segments.join("/")}`);
10242
+ }
10243
+ if (info.isSymbolicLink()) throw makeHttpError(403, "Report path cannot contain symlinks");
10244
+ if (index < segments.length - 1 && !info.isDirectory()) throw makeHttpError(400, "Report path contains a non-directory component");
10245
+ }
10246
+ if (!info?.isFile()) throw makeHttpError(400, "Report path is not a regular file");
10247
+ const realTarget = await realpath(targetPath).catch(() => "");
10248
+ if (!realTarget || !pathInside(root, realTarget)) throw makeHttpError(403, "Resolved report path escapes the canonical Git root");
10249
+ const opened = await readBoundedAurReviewReport(targetPath);
10250
+ assertTextFileBuffer(opened.buffer);
10251
+ return {
10252
+ root,
10253
+ path: segments.join("/"),
10254
+ name: path.basename(targetPath),
10255
+ content: opened.buffer.toString("utf8"),
10256
+ size: opened.buffer.length,
10257
+ mtimeMs: opened.info.mtimeMs,
10258
+ extension: path.extname(targetPath).toLowerCase(),
10259
+ language: fileViewerLanguage(targetPath),
10260
+ };
10261
+ }
10262
+
9812
10263
  async function saveFileContentData(tab, body = {}) {
9813
10264
  if (typeof body.content !== "string") throw makeHttpError(400, "File content must be a string");
9814
10265
  if (body.content.includes("\0")) throw makeHttpError(400, "File content cannot contain null bytes");
@@ -10639,6 +11090,68 @@ async function closeTab(id) {
10639
11090
  return tab;
10640
11091
  }
10641
11092
 
11093
+ async function discardTab(tab) {
11094
+ if (!tab || !tabs.has(tab.id)) return;
11095
+ tab.rpcUnsubscribe?.();
11096
+ rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
11097
+ stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
11098
+ tab.rpc.stop();
11099
+ tabs.delete(tab.id);
11100
+ }
11101
+
11102
+ function recoveryText(value, field, maxChars) {
11103
+ const text = typeof value === "string" ? value.trim() : "";
11104
+ if (!text) throw makeHttpError(400, `${field} is required`);
11105
+ if (text.length > maxChars) throw makeHttpError(413, `${field} is too large`);
11106
+ if (/\0/u.test(text)) throw makeHttpError(400, `${field} contains invalid characters`);
11107
+ return text;
11108
+ }
11109
+
11110
+ function requireRecoveryEndpointAuthorization(req) {
11111
+ requireLocalhostRoute(req, RECOVERY_ENDPOINT_PATH);
11112
+ const match = String(req.headers.authorization || "").match(/^Bearer\s+(.+)$/iu);
11113
+ if (!match || !safeTimingEqual(match[1].trim(), recoveryEndpointToken)) {
11114
+ throw makeHttpError(401, "Invalid recovery endpoint credential");
11115
+ }
11116
+ }
11117
+
11118
+ async function openPlanRecovery(body = {}) {
11119
+ if (body.mode !== "plan-only") throw makeHttpError(400, "Recovery mode must be plan-only");
11120
+ if (!body.model || typeof body.model !== "object" || Array.isArray(body.model)) throw makeHttpError(400, "model is required");
11121
+ const prompt = recoveryText(body.prompt, "prompt", RECOVERY_PROMPT_MAX_CHARS);
11122
+ const cwd = recoveryText(body.cwd, "cwd", 4096);
11123
+ const provider = recoveryText(body.model.provider, "model.provider", 160);
11124
+ const modelId = recoveryText(body.model.id, "model.id", 320);
11125
+ const tab = await createTab({
11126
+ title: RECOVERY_TITLE,
11127
+ titleSource: "explicit",
11128
+ conversationStarted: true,
11129
+ cwd,
11130
+ });
11131
+
11132
+ try {
11133
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider, modelId });
11134
+ if (modelResponse.success === false) throw makeHttpError(409, modelResponse.error || `Recovery model is unavailable: ${provider}/${modelId}`);
11135
+ markTabWorking(tab);
11136
+ const promptResponse = await tab.rpc.send({ type: "prompt", message: prompt }, PROMPT_REQUEST_TIMEOUT_MS);
11137
+ if (promptResponse.success === false) throw makeHttpError(409, promptResponse.error || "Recovery prompt was rejected");
11138
+ const event = {
11139
+ type: "webui_recovery_opened",
11140
+ requestId: tab.id,
11141
+ recoveryTabId: tab.id,
11142
+ recoveryTabTitle: tab.title,
11143
+ cwd: tab.cwd,
11144
+ model: { provider, id: modelId },
11145
+ };
11146
+ broadcastServerEvent(event);
11147
+ return { requestId: tab.id, tab: tabMeta(tab), tabs: listTabs() };
11148
+ } catch (error) {
11149
+ markTabIdle(tab);
11150
+ await discardTab(tab);
11151
+ throw error;
11152
+ }
11153
+ }
11154
+
10642
11155
  async function closeTabs(ids) {
10643
11156
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
10644
11157
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
@@ -11050,6 +11563,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
11050
11563
  const data = {
11051
11564
  online: true,
11052
11565
  webuiVersion: packageJson.version,
11566
+ piVersion: String(piPackageJson.version || ""),
11053
11567
  webuiDev: webuiDevServer,
11054
11568
  webuiMode: webuiDevServer ? "dev" : "production",
11055
11569
  webuiPid: process.pid,
@@ -11100,6 +11614,13 @@ const server = createServer(async (req, res) => {
11100
11614
  return;
11101
11615
  }
11102
11616
 
11617
+ if (url.pathname === RECOVERY_ENDPOINT_PATH && req.method === "POST") {
11618
+ requireRecoveryEndpointAuthorization(req);
11619
+ const result = await openPlanRecovery(await readJsonBody(req, { limitBytes: RECOVERY_BODY_LIMIT_BYTES }));
11620
+ sendJson(res, 201, { ok: true, requestId: result.requestId, data: result });
11621
+ return;
11622
+ }
11623
+
11103
11624
  if (shouldChallengeRemoteAuth(req, url)) {
11104
11625
  sendRemoteAuthRequired(req, res, url);
11105
11626
  return;
@@ -11182,6 +11703,7 @@ const server = createServer(async (req, res) => {
11182
11703
  sendSse(res, {
11183
11704
  type: "webui_connected",
11184
11705
  version: packageJson.version,
11706
+ piVersion: String(piPackageJson.version || ""),
11185
11707
  webuiDev: webuiDevServer,
11186
11708
  webuiMode: webuiDevServer ? "dev" : "production",
11187
11709
  tabId: tab.id,
@@ -11209,6 +11731,7 @@ const server = createServer(async (req, res) => {
11209
11731
  sendJson(res, 200, {
11210
11732
  ok: true,
11211
11733
  webuiVersion: status.webuiVersion,
11734
+ piVersion: status.piVersion,
11212
11735
  webuiDev: status.webuiDev,
11213
11736
  webuiMode: status.webuiMode,
11214
11737
  webuiPid: status.webuiPid,
@@ -11222,6 +11745,11 @@ const server = createServer(async (req, res) => {
11222
11745
  return;
11223
11746
  }
11224
11747
 
11748
+ if (url.pathname === "/api/pi-release-notes" && req.method === "GET") {
11749
+ sendJson(res, 200, { ok: true, data: await installedPiReleaseNotes() }, { "cache-control": "private, no-store" });
11750
+ return;
11751
+ }
11752
+
11225
11753
  if (url.pathname === "/api/webui-status" && req.method === "GET") {
11226
11754
  const detailed = ["1", "true", "yes", "detailed"].includes(String(url.searchParams.get("detailed") || "").toLowerCase());
11227
11755
  const parsedEventLimit = Number.parseInt(url.searchParams.get("events") || "40", 10);
@@ -11514,6 +12042,18 @@ const server = createServer(async (req, res) => {
11514
12042
  return;
11515
12043
  }
11516
12044
 
12045
+ if (url.pathname === "/api/aur-review/report-content" && req.method === "GET") {
12046
+ const tab = getRequestedTab(req, url);
12047
+ sendJson(res, 200, {
12048
+ ok: true,
12049
+ data: await getAurReviewReportContentData(tab, {
12050
+ path: url.searchParams.get("path") || "",
12051
+ repoRoot: url.searchParams.get("repoRoot") || "",
12052
+ }),
12053
+ });
12054
+ return;
12055
+ }
12056
+
11517
12057
  if (url.pathname === "/api/files/content" && req.method === "GET") {
11518
12058
  const tab = getRequestedTab(req, url);
11519
12059
  sendJson(res, 200, { ok: true, data: await getFileContentData(tab, url.searchParams.get("path") || "") });