@firstpick/pi-package-webui 0.6.8 → 0.6.9

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/README.md CHANGED
@@ -122,6 +122,7 @@ Environment variables:
122
122
  - `PI_WEBUI_HOST` and `PI_WEBUI_PORT` set the default bind address.
123
123
  - `PI_WEBUI_PI_BIN=/path/to/pi` selects the Pi executable when `--pi` is not passed.
124
124
  - `PI_WEBUI_REMOTE_AUTH=1` starts with Remote PIN authentication enabled.
125
+ - Pi Web UI automatically injects a loopback `PI_WEBUI_RECOVERY_URL` and a bearer `PI_WEBUI_RECOVERY_TOKEN` into spawned Pi RPC processes. The authenticated endpoint can only create a separate plan-only recovery tab; keep any manually supplied token private.
125
126
  - `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` overrides persisted Web UI settings such as Remote PIN auth, guided Git preferences, and global Tools/Skills defaults.
126
127
  - `PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT=/path/to/package-root` overrides the npm prefix used for optional companion installs.
127
128
  - `PI_WEBUI_FAST_PICKS_FILE=/path/to/paths.json` overrides saved cwd fast-pick storage.
package/bin/pi-webui.mjs CHANGED
@@ -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;
@@ -577,12 +585,62 @@ async function fetchJsonWithTimeout(url, { timeoutMs = UPDATE_STATUS_TIMEOUT_MS,
577
585
  return response.json();
578
586
  }
579
587
 
588
+ function installedPiRelease() {
589
+ const version = String(piPackageJson.version || "").trim().replace(/^v/i, "");
590
+ if (!parsePackageVersion(version)) throw makeHttpError(503, "The installed Pi version could not be determined");
591
+ const tagName = `v${version}`;
592
+ return {
593
+ version,
594
+ tagName,
595
+ apiUrl: `${PI_RELEASES_API_BASE_URL}/${encodeURIComponent(tagName)}`,
596
+ pageUrl: `${PI_RELEASES_PAGE_BASE_URL}/${encodeURIComponent(tagName)}`,
597
+ };
598
+ }
599
+
600
+ let piReleaseNotesCache = null;
601
+
602
+ async function installedPiReleaseNotes() {
603
+ const release = installedPiRelease();
604
+ if (piReleaseNotesCache?.tagName === release.tagName) return piReleaseNotesCache;
605
+ if (process.env.PI_OFFLINE) throw makeHttpError(503, "Pi release notes are unavailable while PI_OFFLINE is set");
606
+
607
+ let data;
608
+ try {
609
+ data = await fetchJsonWithTimeout(release.apiUrl, {
610
+ headers: {
611
+ "User-Agent": `pi-webui/${packageJson.version} pi/${release.version}`,
612
+ accept: "application/vnd.github+json",
613
+ "X-GitHub-Api-Version": "2022-11-28",
614
+ },
615
+ });
616
+ } catch (error) {
617
+ throw makeHttpError(502, `Could not fetch Pi ${release.tagName} release notes from GitHub: ${sanitizeError(error)}`);
618
+ }
619
+
620
+ const responseTag = typeof data?.tag_name === "string" ? data.tag_name.trim() : "";
621
+ if (responseTag && responseTag !== release.tagName) {
622
+ throw makeHttpError(502, `GitHub returned release ${responseTag} instead of ${release.tagName}`);
623
+ }
624
+ const fullBody = typeof data?.body === "string" ? data.body.trim() : "";
625
+ piReleaseNotesCache = {
626
+ version: release.version,
627
+ tagName: release.tagName,
628
+ title: truncateLongText(typeof data?.name === "string" ? data.name.trim() : "", 240) || `Pi ${release.tagName}`,
629
+ body: truncateLongText(fullBody, PI_RELEASE_NOTES_MAX_CHARS),
630
+ truncated: fullBody.length > PI_RELEASE_NOTES_MAX_CHARS,
631
+ publishedAt: typeof data?.published_at === "string" ? data.published_at : "",
632
+ url: release.pageUrl,
633
+ };
634
+ return piReleaseNotesCache;
635
+ }
636
+
580
637
  class PiRpcProcess {
581
- constructor({ command, args, displayCommand, cwd }) {
638
+ constructor({ command, args, displayCommand, cwd, env = process.env }) {
582
639
  this.command = command;
583
640
  this.args = args;
584
641
  this.displayCommand = displayCommand;
585
642
  this.cwd = cwd;
643
+ this.env = env;
586
644
  this.child = undefined;
587
645
  this.pending = new Map();
588
646
  this.listeners = new Set();
@@ -592,7 +650,7 @@ class PiRpcProcess {
592
650
  start() {
593
651
  this.child = spawn(this.command, this.args, {
594
652
  cwd: this.cwd,
595
- env: process.env,
653
+ env: this.env,
596
654
  stdio: ["pipe", "pipe", "pipe"],
597
655
  windowsHide: true,
598
656
  });
@@ -6714,6 +6772,26 @@ try {
6714
6772
 
6715
6773
  process.env.PI_WEBUI_HOST = options.host;
6716
6774
  process.env.PI_WEBUI_PORT = String(options.port);
6775
+ const recoveryEndpointToken = String(process.env.PI_WEBUI_RECOVERY_TOKEN || "").trim() || `${randomUUID()}${randomUUID()}`;
6776
+
6777
+ function recoveryLoopbackUrl(bindHost = options.host) {
6778
+ const normalized = String(bindHost || "").trim().toLowerCase().replace(/^\[|\]$/g, "");
6779
+ if (normalized === "::" || normalized === "::1") return `http://[::1]:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6780
+ if (normalized === "localhost") return `http://localhost:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6781
+ if (normalized === "0.0.0.0" || normalized.startsWith("127.")) return `http://127.0.0.1:${options.port}${RECOVERY_ENDPOINT_PATH}`;
6782
+ return "";
6783
+ }
6784
+
6785
+ function piRpcEnvironment() {
6786
+ const env = { ...process.env };
6787
+ const recoveryUrl = recoveryLoopbackUrl();
6788
+ if (recoveryUrl) {
6789
+ env.PI_WEBUI_RECOVERY_URL = recoveryUrl;
6790
+ env.PI_WEBUI_RECOVERY_TOKEN = recoveryEndpointToken;
6791
+ }
6792
+ return env;
6793
+ }
6794
+
6717
6795
  await configureDevDependencyResolution();
6718
6796
 
6719
6797
  const startupDelayMs = Number.parseInt(process.env.PI_WEBUI_START_DELAY_MS || "", 10);
@@ -7772,7 +7850,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
7772
7850
  const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
7773
7851
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
7774
7852
  const piCommand = await resolvePiCommand(piArgs);
7775
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd });
7853
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
7776
7854
  const createdAt = new Date().toISOString();
7777
7855
  const tab = {
7778
7856
  id,
@@ -8481,6 +8559,15 @@ function broadcastTabEvent(tab, event) {
8481
8559
  for (const client of tab.sseClients) sendSse(client, event);
8482
8560
  }
8483
8561
 
8562
+ function broadcastServerEvent(event) {
8563
+ recordEvent(event);
8564
+ const clients = new Set();
8565
+ for (const tab of tabs.values()) {
8566
+ for (const client of tab.sseClients) clients.add(client);
8567
+ }
8568
+ for (const client of clients) sendSse(client, event);
8569
+ }
8570
+
8484
8571
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
8485
8572
  if (!tab) return false;
8486
8573
  const rawTitle = maxLength ? truncateTabTitle(title, maxLength) : String(title || "").replace(/\s+/g, " ").trim();
@@ -8554,7 +8641,7 @@ async function updateTabCwd(id, cwd) {
8554
8641
  clearExtensionWidgets(tab);
8555
8642
  clearWebuiSubagents(tab);
8556
8643
  resetNaturalConversationMode(tab);
8557
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8644
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8558
8645
  attachRpcToTab(tab, rpc);
8559
8646
  rpc.start();
8560
8647
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
@@ -8594,7 +8681,7 @@ async function restartTabRpc(tab, reason = "reload") {
8594
8681
  clearExtensionWidgets(tab);
8595
8682
  clearWebuiSubagents(tab);
8596
8683
  resetNaturalConversationMode(tab);
8597
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8684
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8598
8685
  attachRpcToTab(tab, rpc);
8599
8686
  rpc.start();
8600
8687
 
@@ -10639,6 +10726,68 @@ async function closeTab(id) {
10639
10726
  return tab;
10640
10727
  }
10641
10728
 
10729
+ async function discardTab(tab) {
10730
+ if (!tab || !tabs.has(tab.id)) return;
10731
+ tab.rpcUnsubscribe?.();
10732
+ rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
10733
+ stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
10734
+ tab.rpc.stop();
10735
+ tabs.delete(tab.id);
10736
+ }
10737
+
10738
+ function recoveryText(value, field, maxChars) {
10739
+ const text = typeof value === "string" ? value.trim() : "";
10740
+ if (!text) throw makeHttpError(400, `${field} is required`);
10741
+ if (text.length > maxChars) throw makeHttpError(413, `${field} is too large`);
10742
+ if (/\0/u.test(text)) throw makeHttpError(400, `${field} contains invalid characters`);
10743
+ return text;
10744
+ }
10745
+
10746
+ function requireRecoveryEndpointAuthorization(req) {
10747
+ requireLocalhostRoute(req, RECOVERY_ENDPOINT_PATH);
10748
+ const match = String(req.headers.authorization || "").match(/^Bearer\s+(.+)$/iu);
10749
+ if (!match || !safeTimingEqual(match[1].trim(), recoveryEndpointToken)) {
10750
+ throw makeHttpError(401, "Invalid recovery endpoint credential");
10751
+ }
10752
+ }
10753
+
10754
+ async function openPlanRecovery(body = {}) {
10755
+ if (body.mode !== "plan-only") throw makeHttpError(400, "Recovery mode must be plan-only");
10756
+ if (!body.model || typeof body.model !== "object" || Array.isArray(body.model)) throw makeHttpError(400, "model is required");
10757
+ const prompt = recoveryText(body.prompt, "prompt", RECOVERY_PROMPT_MAX_CHARS);
10758
+ const cwd = recoveryText(body.cwd, "cwd", 4096);
10759
+ const provider = recoveryText(body.model.provider, "model.provider", 160);
10760
+ const modelId = recoveryText(body.model.id, "model.id", 320);
10761
+ const tab = await createTab({
10762
+ title: RECOVERY_TITLE,
10763
+ titleSource: "explicit",
10764
+ conversationStarted: true,
10765
+ cwd,
10766
+ });
10767
+
10768
+ try {
10769
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider, modelId });
10770
+ if (modelResponse.success === false) throw makeHttpError(409, modelResponse.error || `Recovery model is unavailable: ${provider}/${modelId}`);
10771
+ markTabWorking(tab);
10772
+ const promptResponse = await tab.rpc.send({ type: "prompt", message: prompt }, PROMPT_REQUEST_TIMEOUT_MS);
10773
+ if (promptResponse.success === false) throw makeHttpError(409, promptResponse.error || "Recovery prompt was rejected");
10774
+ const event = {
10775
+ type: "webui_recovery_opened",
10776
+ requestId: tab.id,
10777
+ recoveryTabId: tab.id,
10778
+ recoveryTabTitle: tab.title,
10779
+ cwd: tab.cwd,
10780
+ model: { provider, id: modelId },
10781
+ };
10782
+ broadcastServerEvent(event);
10783
+ return { requestId: tab.id, tab: tabMeta(tab), tabs: listTabs() };
10784
+ } catch (error) {
10785
+ markTabIdle(tab);
10786
+ await discardTab(tab);
10787
+ throw error;
10788
+ }
10789
+ }
10790
+
10642
10791
  async function closeTabs(ids) {
10643
10792
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
10644
10793
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
@@ -11050,6 +11199,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
11050
11199
  const data = {
11051
11200
  online: true,
11052
11201
  webuiVersion: packageJson.version,
11202
+ piVersion: String(piPackageJson.version || ""),
11053
11203
  webuiDev: webuiDevServer,
11054
11204
  webuiMode: webuiDevServer ? "dev" : "production",
11055
11205
  webuiPid: process.pid,
@@ -11100,6 +11250,13 @@ const server = createServer(async (req, res) => {
11100
11250
  return;
11101
11251
  }
11102
11252
 
11253
+ if (url.pathname === RECOVERY_ENDPOINT_PATH && req.method === "POST") {
11254
+ requireRecoveryEndpointAuthorization(req);
11255
+ const result = await openPlanRecovery(await readJsonBody(req, { limitBytes: RECOVERY_BODY_LIMIT_BYTES }));
11256
+ sendJson(res, 201, { ok: true, requestId: result.requestId, data: result });
11257
+ return;
11258
+ }
11259
+
11103
11260
  if (shouldChallengeRemoteAuth(req, url)) {
11104
11261
  sendRemoteAuthRequired(req, res, url);
11105
11262
  return;
@@ -11182,6 +11339,7 @@ const server = createServer(async (req, res) => {
11182
11339
  sendSse(res, {
11183
11340
  type: "webui_connected",
11184
11341
  version: packageJson.version,
11342
+ piVersion: String(piPackageJson.version || ""),
11185
11343
  webuiDev: webuiDevServer,
11186
11344
  webuiMode: webuiDevServer ? "dev" : "production",
11187
11345
  tabId: tab.id,
@@ -11209,6 +11367,7 @@ const server = createServer(async (req, res) => {
11209
11367
  sendJson(res, 200, {
11210
11368
  ok: true,
11211
11369
  webuiVersion: status.webuiVersion,
11370
+ piVersion: status.piVersion,
11212
11371
  webuiDev: status.webuiDev,
11213
11372
  webuiMode: status.webuiMode,
11214
11373
  webuiPid: status.webuiPid,
@@ -11222,6 +11381,11 @@ const server = createServer(async (req, res) => {
11222
11381
  return;
11223
11382
  }
11224
11383
 
11384
+ if (url.pathname === "/api/pi-release-notes" && req.method === "GET") {
11385
+ sendJson(res, 200, { ok: true, data: await installedPiReleaseNotes() }, { "cache-control": "private, no-store" });
11386
+ return;
11387
+ }
11388
+
11225
11389
  if (url.pathname === "/api/webui-status" && req.method === "GET") {
11226
11390
  const detailed = ["1", "true", "yes", "detailed"].includes(String(url.searchParams.get("detailed") || "").toLowerCase());
11227
11391
  const parsedEventLimit = Number.parseInt(url.searchParams.get("events") || "40", 10);
@@ -13,6 +13,7 @@ export const LOCALHOST_ONLY_POST_ROUTES = new Map([
13
13
  ["/api/network/open", "Opening to the network is only allowed from localhost"],
14
14
  ["/api/network/close", "Closing network access is only allowed from localhost"],
15
15
  ["/api/remote-auth/settings", "Remote PIN authentication settings are only allowed from localhost"],
16
+ ["/api/recovery/plan", "Opening recovery plans is only allowed from localhost"],
16
17
  ["/api/restart", "Restart is only allowed from localhost"],
17
18
  ["/api/update", "Updating Pi from the Web UI is only allowed from localhost"],
18
19
  ["/api/shutdown", "Shutdown is only allowed from localhost"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.6.8",
3
+ "version": "0.6.9",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
@@ -55,22 +55,22 @@
55
55
  "test": "node tests/run-all.mjs"
56
56
  },
57
57
  "dependencies": {
58
- "@earendil-works/pi-coding-agent": "^0.80.6",
58
+ "@earendil-works/pi-coding-agent": "^0.80.9",
59
59
  "mermaid": "^11.15.0"
60
60
  },
61
61
  "optionalDependencies": {
62
62
  "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
63
- "@firstpick/pi-extension-btw": "^0.1.2",
63
+ "@firstpick/pi-extension-btw": "^0.1.3",
64
64
  "@firstpick/pi-extension-fish-user-bash": "^0.2.1",
65
- "@firstpick/pi-extension-git-footer-status": "^0.3.8",
65
+ "@firstpick/pi-extension-git-footer-status": "^0.4.0",
66
66
  "@firstpick/pi-extension-release-aur": "^0.1.7",
67
- "@firstpick/pi-extension-release-npm": "^0.4.0",
68
- "@firstpick/pi-extension-safety-guard": "^0.2.3",
67
+ "@firstpick/pi-extension-release-npm": "^0.4.1",
68
+ "@firstpick/pi-extension-safety-guard": "^0.2.5",
69
69
  "@firstpick/pi-extension-setup-skills": "^0.1.8",
70
70
  "@firstpick/pi-extension-stats": "^0.2.8",
71
- "@firstpick/pi-extension-todo-progress": "^0.2.7",
71
+ "@firstpick/pi-extension-todo-progress": "^0.2.8",
72
72
  "@firstpick/pi-extension-tools": "^0.1.6",
73
- "@firstpick/pi-extension-workflows": "^0.1.2",
73
+ "@firstpick/pi-extension-workflows": "^0.1.3",
74
74
  "@firstpick/pi-package-remote-webui": "^0.1.5",
75
75
  "@firstpick/pi-prompts-git-pr": "^0.1.3",
76
76
  "@firstpick/pi-themes-bundle": "^0.1.4"