@firstpick/pi-package-webui 0.6.7 → 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/bin/pi-webui.mjs CHANGED
@@ -11,8 +11,10 @@ import { StringDecoder } from "node:string_decoder";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { promisify } from "node:util";
13
13
  import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
14
- import { AuthStorage, SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
14
+ import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
+ import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
+ import { nativeExportDownloadPayload } from "../lib/native-export-payload.mjs";
16
18
  import {
17
19
  collectOpenSessionFiles,
18
20
  deleteSessionFile,
@@ -21,7 +23,14 @@ import {
21
23
  validateSessionDelete,
22
24
  } from "../lib/session-actions.mjs";
23
25
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
26
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
27
+ import {
28
+ classifyGitPathFailure,
29
+ findWindowsReservedGitPath,
30
+ windowsReservedGitPathFailure,
31
+ } from "../lib/git-command-errors.mjs";
24
32
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
33
+ import { resolveNpmCommandInvocation } from "../lib/npm-command.mjs";
25
34
  import {
26
35
  GIT_WORKFLOW_DEFAULT_VARIANTS,
27
36
  GIT_WORKFLOW_DELIVERY_MODES,
@@ -76,7 +85,8 @@ const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROO
76
85
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
77
86
  let piPackageJson = {};
78
87
  try {
79
- 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");
80
90
  piPackageJson = JSON.parse(await readFile(piPackageJsonPath, "utf8"));
81
91
  } catch {
82
92
  piPackageJson = {};
@@ -101,16 +111,18 @@ const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
101
111
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
102
112
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
103
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";
104
116
  const NPM_REGISTRY_URL = (process.env.PI_WEBUI_NPM_REGISTRY_URL || "https://registry.npmjs.org").replace(/\/+$/, "");
105
117
  const UPDATE_STATUS_CACHE_MS = 10 * 60 * 1000;
106
118
  const UPDATE_STATUS_TIMEOUT_MS = 10 * 1000;
119
+ const PI_RELEASE_NOTES_MAX_CHARS = 250_000;
107
120
  const PI_UPDATE_TIMEOUT_MS = 15 * 60 * 1000;
108
121
  const PI_UPDATE_OUTPUT_MAX_CHARS = 120_000;
109
122
  const CORE_UPDATE_PACKAGE_NAMES = [PI_CODING_AGENT_PACKAGE, WEBUI_PACKAGE];
110
123
  const PACKAGE_UPDATE_TIMEOUT_MS = 15 * 60 * 1000;
111
124
  const PACKAGE_UPDATE_OUTPUT_MAX_CHARS = 120_000;
112
125
  const CODEX_USAGE_TIMEOUT_MS = 15 * 1000;
113
- const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
114
126
  const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
115
127
  const OPENAI_CODEX_USAGE_ENDPOINT = process.env.PI_WEBUI_CODEX_USAGE_URL || "https://chatgpt.com/backend-api/wham/usage";
116
128
  const CLAUDE_USAGE_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_WEBUI_CLAUDE_USAGE_TIMEOUT_MS || "30000", 10) || 30000);
@@ -118,6 +130,10 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
118
130
  const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
119
131
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
120
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";
121
137
  const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
122
138
  const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
123
139
  const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
@@ -569,12 +585,62 @@ async function fetchJsonWithTimeout(url, { timeoutMs = UPDATE_STATUS_TIMEOUT_MS,
569
585
  return response.json();
570
586
  }
571
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
+
572
637
  class PiRpcProcess {
573
- constructor({ command, args, displayCommand, cwd }) {
638
+ constructor({ command, args, displayCommand, cwd, env = process.env }) {
574
639
  this.command = command;
575
640
  this.args = args;
576
641
  this.displayCommand = displayCommand;
577
642
  this.cwd = cwd;
643
+ this.env = env;
578
644
  this.child = undefined;
579
645
  this.pending = new Map();
580
646
  this.listeners = new Set();
@@ -584,7 +650,7 @@ class PiRpcProcess {
584
650
  start() {
585
651
  this.child = spawn(this.command, this.args, {
586
652
  cwd: this.cwd,
587
- env: process.env,
653
+ env: this.env,
588
654
  stdio: ["pipe", "pipe", "pipe"],
589
655
  windowsHide: true,
590
656
  });
@@ -1610,10 +1676,9 @@ async function installOptionalFeaturePackage(featureId) {
1610
1676
  });
1611
1677
  }
1612
1678
 
1613
- const npmCommand = process.env.PI_WEBUI_NPM_BIN || "npm";
1614
- const args = ["install", "--prefix", installRoot, packageName];
1615
- const command = formatCommandForDisplay(npmCommand, args);
1616
- const result = await runCommand(npmCommand, args, {
1679
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, packageName]);
1680
+ const command = npmCommand.displayCommand;
1681
+ const result = await runCommand(npmCommand.command, npmCommand.args, {
1617
1682
  cwd: installRoot,
1618
1683
  timeoutMs: 5 * 60 * 1000,
1619
1684
  maxOutputLength: 80000,
@@ -1777,6 +1842,65 @@ async function saveRemoteAuthPreference(enabled) {
1777
1842
  return persistedRemoteAuthEnabled;
1778
1843
  }
1779
1844
 
1845
+ let safetyGuardConfigModulePromise;
1846
+
1847
+ async function safetyGuardConfigModule() {
1848
+ if (!safetyGuardConfigModulePromise) {
1849
+ safetyGuardConfigModulePromise = (async () => {
1850
+ const specifiers = [
1851
+ "@firstpick/pi-extension-safety-guard/src/config.mjs",
1852
+ new URL("../../pi-extension-safety-guard/src/config.mjs", import.meta.url).href,
1853
+ ];
1854
+ const failures = [];
1855
+ for (const specifier of specifiers) {
1856
+ try {
1857
+ return await import(specifier);
1858
+ } catch (error) {
1859
+ failures.push(error instanceof Error ? error.message : String(error));
1860
+ }
1861
+ }
1862
+ throw makeHttpError(503, `Safety guard setup support is unavailable. Update @firstpick/pi-extension-safety-guard and restart Web UI. ${failures.at(-1) || ""}`.trim());
1863
+ })().catch((error) => {
1864
+ safetyGuardConfigModulePromise = undefined;
1865
+ throw error;
1866
+ });
1867
+ }
1868
+ return safetyGuardConfigModulePromise;
1869
+ }
1870
+
1871
+ async function safetyGuardConfigData() {
1872
+ const settingsModule = await safetyGuardConfigModule();
1873
+ const config = settingsModule.readSafetyGuardConfig();
1874
+ return {
1875
+ config,
1876
+ defaults: settingsModule.defaultSafetyGuardConfig(),
1877
+ categories: [...settingsModule.SAFETY_GUARD_CATEGORIES],
1878
+ contextLines: {
1879
+ min: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MIN,
1880
+ max: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MAX,
1881
+ },
1882
+ version: settingsModule.SAFETY_GUARD_CONFIG_VERSION,
1883
+ path: settingsModule.safetyGuardConfigFile(),
1884
+ };
1885
+ }
1886
+
1887
+ async function saveSafetyGuardConfigData(body = {}) {
1888
+ const settingsModule = await safetyGuardConfigModule();
1889
+ const submitted = body.config && typeof body.config === "object" ? body.config : body;
1890
+ try {
1891
+ settingsModule.assertSafetyGuardConfigPatch(submitted);
1892
+ } catch (error) {
1893
+ throw makeHttpError(400, error instanceof Error ? error.message : String(error));
1894
+ }
1895
+
1896
+ try {
1897
+ const config = settingsModule.writeSafetyGuardConfig(submitted);
1898
+ return { ...(await safetyGuardConfigData()), config };
1899
+ } catch (error) {
1900
+ throw makeHttpError(500, error instanceof Error ? error.message : String(error));
1901
+ }
1902
+ }
1903
+
1780
1904
  function gitWorkflowModelKey(model) {
1781
1905
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1782
1906
  }
@@ -2970,18 +3094,7 @@ function scheduleAppRunnerBroadcast(tab) {
2970
3094
 
2971
3095
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
2972
3096
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2973
- try {
2974
- if (process.platform !== "win32" && run.pid) process.kill(-run.pid, signal);
2975
- else run.child.kill(signal);
2976
- return true;
2977
- } catch {
2978
- try {
2979
- run.child.kill(signal);
2980
- return true;
2981
- } catch {
2982
- return false;
2983
- }
2984
- }
3097
+ return terminateProcessTree(run.child, signal);
2985
3098
  }
2986
3099
 
2987
3100
  function appRunnerStdinWritable(run) {
@@ -2991,7 +3104,10 @@ function appRunnerStdinWritable(run) {
2991
3104
 
2992
3105
  function interruptAppRunnerChild(run) {
2993
3106
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2994
- if (appRunnerStdinWritable(run) && (run.executionMode === "pty" || process.platform === "win32")) {
3107
+ // Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
3108
+ // complete tree there so npm/bash wrappers cannot leave orphaned servers.
3109
+ if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
3110
+ if (appRunnerStdinWritable(run) && run.executionMode === "pty") {
2995
3111
  try {
2996
3112
  run.child.stdin.write("\x03", "utf8");
2997
3113
  return true;
@@ -3117,14 +3233,15 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
3117
3233
  const run = tab?.appRunner;
3118
3234
  if (!run || run.status !== "running") return false;
3119
3235
  run.stopping = true;
3120
- appendAppRunnerLine(run, `# ${reason}; sending ${force ? "SIGKILL" : "Ctrl+C"}`);
3236
+ const action = process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3237
+ appendAppRunnerLine(run, `# ${reason}; ${action}`);
3121
3238
  if (force) terminateAppRunnerChild(run, "SIGKILL");
3122
3239
  else interruptAppRunnerChild(run);
3123
3240
  if (!force) {
3124
3241
  clearTimeout(run.stopTimer);
3125
3242
  run.stopTimer = setTimeout(() => {
3126
3243
  if (run.status === "running") {
3127
- appendAppRunnerLine(run, "# app runner did not stop after Ctrl+C; sending SIGKILL");
3244
+ appendAppRunnerLine(run, "# app runner did not stop within the grace period; forcing process-tree termination");
3128
3245
  terminateAppRunnerChild(run, "SIGKILL");
3129
3246
  scheduleAppRunnerBroadcast(tab);
3130
3247
  }
@@ -3382,38 +3499,24 @@ function normalizeCodexUsagePayload(rawPayload) {
3382
3499
  }
3383
3500
 
3384
3501
  async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3385
- const authStorage = AuthStorage.create();
3386
- const stored = authStorage.get(OPENAI_CODEX_PROVIDER_ID);
3387
- const storedExpires = numericValue(stored?.expires);
3388
- const shouldRefresh = stored?.type === "oauth" && (forceRefresh || storedExpires === undefined || Date.now() + CODEX_TOKEN_REFRESH_SKEW_MS >= storedExpires);
3389
- let accessToken;
3390
- let refreshed = false;
3391
-
3392
- if (shouldRefresh) {
3393
- try {
3394
- const refreshResult = await authStorage.refreshOAuthTokenWithLock(OPENAI_CODEX_PROVIDER_ID);
3395
- if (refreshResult?.apiKey) {
3396
- accessToken = refreshResult.apiKey;
3397
- refreshed = forceRefresh || refreshResult.newCredentials?.access !== stored?.access;
3398
- }
3399
- } catch (error) {
3400
- if (forceRefresh || !storedExpires || Date.now() >= storedExpires) {
3401
- throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
3402
- }
3403
- console.warn(`OpenAI Codex token refresh warning: ${sanitizeError(error)}`);
3404
- }
3502
+ const { modelRuntime } = await authContext();
3503
+ let resolved;
3504
+ try {
3505
+ resolved = await resolveCodexUsageAuth(modelRuntime, OPENAI_CODEX_PROVIDER_ID, { forceRefresh });
3506
+ } catch {
3507
+ // Client-facing auth failures must not include provider stack traces,
3508
+ // refresh tokens, or raw upstream error details.
3509
+ throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
3405
3510
  }
3406
3511
 
3512
+ const accessToken = resolved.accessToken;
3407
3513
  if (!accessToken) {
3408
- accessToken = await authStorage.getApiKey(OPENAI_CODEX_PROVIDER_ID, { includeFallback: false });
3409
- }
3410
- if (!accessToken) {
3411
- const status = authStorage.getAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3514
+ const status = modelRuntime.getProviderAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3412
3515
  if (status.configured) throw makeHttpError(401, "OpenAI Codex OAuth token is expired or unavailable. Run /login to refresh credentials.");
3413
3516
  throw makeHttpError(401, "OpenAI Codex OAuth is not configured. Run /login and choose ChatGPT Plus/Pro (Codex Subscription).");
3414
3517
  }
3415
3518
 
3416
- const latest = authStorage.get(OPENAI_CODEX_PROVIDER_ID) || stored || {};
3519
+ const latest = resolved.credential || {};
3417
3520
  const accountId = latest.accountId || codexAccountIdFromAccessToken(accessToken);
3418
3521
  if (!accountId) {
3419
3522
  throw makeHttpError(401, "OpenAI Codex account id is unavailable. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) again.");
@@ -3422,7 +3525,7 @@ async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3422
3525
  return {
3423
3526
  accessToken,
3424
3527
  accountId,
3425
- refreshed,
3528
+ refreshed: resolved.refreshed,
3426
3529
  source: latest.type === "oauth" ? "stored-oauth" : "api-key",
3427
3530
  expiresAt: numericValue(latest.expires) ? new Date(numericValue(latest.expires)).toISOString() : undefined,
3428
3531
  };
@@ -3468,7 +3571,7 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
3468
3571
  try {
3469
3572
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3470
3573
  } catch (error) {
3471
- if (error?.openaiStatus === 401 && !credentials.refreshed) {
3574
+ if (error?.openaiStatus === 401) {
3472
3575
  credentials = await getOpenAICodexUsageCredentials({ forceRefresh: true });
3473
3576
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3474
3577
  } else {
@@ -4635,15 +4738,30 @@ async function runGitMutationCommand(args, options = {}) {
4635
4738
  function gitMutationPayload(result) {
4636
4739
  const payload = gitWorkflowCommandPayload(result);
4637
4740
  if (!payload.ok) {
4741
+ let pathFailure = null;
4638
4742
  if (isGitLockFailure(result)) {
4639
4743
  payload.code = "REPO_BUSY";
4640
4744
  payload.hint = "Another git process is using this repository. Retry once it finishes.";
4745
+ } else {
4746
+ pathFailure = classifyGitPathFailure(result);
4747
+ if (pathFailure) Object.assign(payload, pathFailure);
4641
4748
  }
4642
- payload.error = String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4749
+ payload.error = pathFailure?.error || String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4643
4750
  }
4644
4751
  return payload;
4645
4752
  }
4646
4753
 
4754
+ async function gitAddAllPayload(cwd) {
4755
+ await getGitRoot(cwd);
4756
+ if (platform() === "win32") {
4757
+ const untrackedText = await runGitReadCommand(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
4758
+ const invalidPath = findWindowsReservedGitPath(untrackedText);
4759
+ const pathFailure = windowsReservedGitPathFailure(invalidPath);
4760
+ if (pathFailure) return { ok: false, ...pathFailure };
4761
+ }
4762
+ return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
4763
+ }
4764
+
4647
4765
  async function runGuardedGitMutation(args, options = {}) {
4648
4766
  try {
4649
4767
  return gitMutationPayload(await runGitMutationCommand(args, options));
@@ -4875,6 +4993,72 @@ async function readGitOperationSnapshot(cwd) {
4875
4993
  };
4876
4994
  }
4877
4995
 
4996
+ function gitConflictResolutionAgentPrompt(operation) {
4997
+ const conflicts = (operation.conflicts || []).map((conflict) => `- ${conflict.status || "UU"} ${JSON.stringify(String(conflict.path || ""))}`);
4998
+ const summary = operation.summary || {};
4999
+ return [
5000
+ `Resolve the current Git ${operation.operation} conflicts in this working tree.`,
5001
+ "",
5002
+ `Repository root: ${JSON.stringify(String(operation.root || ""))}`,
5003
+ `Branch: ${operation.branch || "detached or unknown"}`,
5004
+ `Working tree: ${summary.staged || 0} staged, ${summary.unstaged || 0} unstaged, ${conflicts.length} conflicted`,
5005
+ "Conflicted files:",
5006
+ ...conflicts,
5007
+ "",
5008
+ "Requirements:",
5009
+ "- Inspect git status plus the staged, unstaged, and unmerged diffs before editing.",
5010
+ "- Resolve only the currently unmerged files and preserve the intended changes from both sides.",
5011
+ "- Stage each resolved file with git add.",
5012
+ `- Do not continue, skip, abort, commit, reset, or push the ${operation.operation}.`,
5013
+ "- Verify git diff --name-only --diff-filter=U is empty, then report what you resolved and any uncertainty.",
5014
+ ].join("\n");
5015
+ }
5016
+
5017
+ async function openGitConflictResolutionAgentTab(sourceTab) {
5018
+ const operation = await readGitOperationSnapshot(sourceTab.cwd);
5019
+ if (!operation.operation || operation.operation === "bisect") throw makeHttpError(409, "No conflict-resolution Git operation is in progress");
5020
+ if (!operation.conflicts?.length) throw makeHttpError(409, "No unmerged files remain to send to an agent");
5021
+
5022
+ const targetTab = await createTab({
5023
+ title: `Resolve ${operation.operation} conflicts`,
5024
+ titleSource: "explicit",
5025
+ conversationStarted: true,
5026
+ cwd: operation.root,
5027
+ });
5028
+ const command = { type: "prompt", message: gitConflictResolutionAgentPrompt(operation) };
5029
+ markTabWorking(targetTab);
5030
+ let response;
5031
+ try {
5032
+ response = await targetTab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
5033
+ } catch (error) {
5034
+ markTabIdle(targetTab);
5035
+ throw error;
5036
+ }
5037
+ if (response.success === false) {
5038
+ markTabIdle(targetTab);
5039
+ throw makeHttpError(502, response.error || "The conflict-resolution agent rejected the handoff prompt");
5040
+ }
5041
+ recordEvent({
5042
+ type: "webui_git_conflict_agent_started",
5043
+ sourceTabId: sourceTab.id,
5044
+ tabId: targetTab.id,
5045
+ cwd: operation.root,
5046
+ operation: operation.operation,
5047
+ conflicts: operation.conflicts.length,
5048
+ });
5049
+ return {
5050
+ sourceTabId: sourceTab.id,
5051
+ tab: tabMeta(targetTab),
5052
+ tabs: listTabs(),
5053
+ operation: {
5054
+ operation: operation.operation,
5055
+ root: operation.root,
5056
+ branch: operation.branch,
5057
+ conflicts: operation.conflicts.map(({ path: conflictPath, status }) => ({ path: conflictPath, status })),
5058
+ },
5059
+ };
5060
+ }
5061
+
4878
5062
  async function gitOperationStageFile(cwd, body = {}) {
4879
5063
  const root = await getGitRoot(cwd);
4880
5064
  const kind = await detectGitOperationKind(root);
@@ -6111,8 +6295,7 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6111
6295
  return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
6112
6296
  }
6113
6297
  case "/api/git-workflow/add":
6114
- await getGitRoot(cwd);
6115
- return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
6298
+ return gitAddAllPayload(cwd);
6116
6299
  case "/api/git-workflow/branch": {
6117
6300
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
6118
6301
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -6589,6 +6772,26 @@ try {
6589
6772
 
6590
6773
  process.env.PI_WEBUI_HOST = options.host;
6591
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
+
6592
6795
  await configureDevDependencyResolution();
6593
6796
 
6594
6797
  const startupDelayMs = Number.parseInt(process.env.PI_WEBUI_START_DELAY_MS || "", 10);
@@ -7647,7 +7850,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
7647
7850
  const piArgs = await buildPiArgsForTab(tabIndex, tabTitle, tabCwd);
7648
7851
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
7649
7852
  const piCommand = await resolvePiCommand(piArgs);
7650
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd });
7853
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tabCwd, env: piRpcEnvironment() });
7651
7854
  const createdAt = new Date().toISOString();
7652
7855
  const tab = {
7653
7856
  id,
@@ -8105,17 +8308,23 @@ function packageInstallSpecs(packageNames) {
8105
8308
  return packageNames.map((packageName) => `${packageName}@latest`);
8106
8309
  }
8107
8310
 
8108
- function npmCommandName() {
8109
- return process.env.PI_WEBUI_NPM_BIN || "npm";
8311
+ function resolvedNpmCommand(args) {
8312
+ const invocation = resolveNpmCommandInvocation(args);
8313
+ return {
8314
+ command: invocation.command,
8315
+ args: invocation.args,
8316
+ displayCommand: formatCommandForDisplay(invocation.displayCommand, invocation.displayArgs),
8317
+ };
8110
8318
  }
8111
8319
 
8112
8320
  function npmPrefixUpdateTask(label, installRoot, packageNames) {
8113
8321
  if (!packageNames.length) return null;
8114
- const npmCommand = npmCommandName();
8322
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)]);
8115
8323
  return {
8116
8324
  label,
8117
- command: npmCommand,
8118
- args: ["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)],
8325
+ command: npmCommand.command,
8326
+ args: npmCommand.args,
8327
+ displayCommand: npmCommand.displayCommand,
8119
8328
  cwd: installRoot,
8120
8329
  };
8121
8330
  }
@@ -8170,8 +8379,8 @@ async function projectPackageRootUpdateTasks() {
8170
8379
  }
8171
8380
 
8172
8381
  async function npmGlobalNodeModulesRoot() {
8173
- const npmCommand = npmCommandName();
8174
- const result = await runCommand(npmCommand, ["root", "-g"], { timeoutMs: 5000, maxOutputLength: 8000 });
8382
+ const npmCommand = resolvedNpmCommand(["root", "-g"]);
8383
+ const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
8175
8384
  if (result.exitCode !== 0 || result.timedOut || result.error) return null;
8176
8385
  return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
8177
8386
  }
@@ -8180,11 +8389,12 @@ async function npmGlobalPackageRootUpdateTask() {
8180
8389
  const nodeModulesRoot = await npmGlobalNodeModulesRoot();
8181
8390
  const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
8182
8391
  if (!packages.length) return null;
8183
- const npmCommand = npmCommandName();
8392
+ const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)]);
8184
8393
  return {
8185
8394
  label: "global npm package root",
8186
- command: npmCommand,
8187
- args: ["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)],
8395
+ command: npmCommand.command,
8396
+ args: npmCommand.args,
8397
+ displayCommand: npmCommand.displayCommand,
8188
8398
  cwd: nodeModulesRoot ? path.dirname(nodeModulesRoot) : process.cwd(),
8189
8399
  };
8190
8400
  }
@@ -8349,6 +8559,15 @@ function broadcastTabEvent(tab, event) {
8349
8559
  for (const client of tab.sseClients) sendSse(client, event);
8350
8560
  }
8351
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
+
8352
8571
  function renameTab(tab, title, { source = "explicit", maxLength, unique = source === "auto" } = {}) {
8353
8572
  if (!tab) return false;
8354
8573
  const rawTitle = maxLength ? truncateTabTitle(title, maxLength) : String(title || "").replace(/\s+/g, " ").trim();
@@ -8422,7 +8641,7 @@ async function updateTabCwd(id, cwd) {
8422
8641
  clearExtensionWidgets(tab);
8423
8642
  clearWebuiSubagents(tab);
8424
8643
  resetNaturalConversationMode(tab);
8425
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8644
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8426
8645
  attachRpcToTab(tab, rpc);
8427
8646
  rpc.start();
8428
8647
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
@@ -8462,7 +8681,7 @@ async function restartTabRpc(tab, reason = "reload") {
8462
8681
  clearExtensionWidgets(tab);
8463
8682
  clearWebuiSubagents(tab);
8464
8683
  resetNaturalConversationMode(tab);
8465
- const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
8684
+ const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
8466
8685
  attachRpcToTab(tab, rpc);
8467
8686
  rpc.start();
8468
8687
 
@@ -8590,8 +8809,46 @@ async function sendWebuiHelperCommand(tab, action, payload = {}, timeoutMs = WEB
8590
8809
  }
8591
8810
  }
8592
8811
 
8593
- async function getToolConfigData(tab) {
8594
- return sendWebuiHelperCommand(tab, "tools-state");
8812
+ function requireResourceScope(value) {
8813
+ const scope = String(value || "session").trim().toLowerCase();
8814
+ if (scope !== "session" && scope !== "global") throw makeHttpError(400, "Resource scope must be session or global");
8815
+ return scope;
8816
+ }
8817
+
8818
+ function selectedResourceNames(body, enabledKey, disabledKey, resources, label) {
8819
+ const allNames = new Set((resources || []).map((resource) => String(resource.name || "").trim()).filter(Boolean));
8820
+ if (Array.isArray(body?.[enabledKey])) {
8821
+ return [...new Set(body[enabledKey].map((name) => String(name || "").trim()).filter((name) => allNames.has(name)))];
8822
+ }
8823
+ if (Array.isArray(body?.[disabledKey])) {
8824
+ const disabled = new Set(body[disabledKey].map((name) => String(name || "").trim()));
8825
+ return [...allNames].filter((name) => !disabled.has(name));
8826
+ }
8827
+ throw makeHttpError(400, `${label} update requires ${enabledKey} or ${disabledKey}`);
8828
+ }
8829
+
8830
+ function preserveUnavailableGlobalNames(selectedNames, resources, previousNames) {
8831
+ if (!Array.isArray(previousNames)) return selectedNames;
8832
+ const available = new Set((resources || []).map((resource) => resource.name));
8833
+ return [...new Set([...selectedNames, ...previousNames.filter((name) => !available.has(name))])];
8834
+ }
8835
+
8836
+ function globalResourcePayload(key, resources, configuredNames) {
8837
+ const configured = Array.isArray(configuredNames);
8838
+ const enabled = new Set(configured ? configuredNames : resources.filter((resource) => resource.enabled !== false).map((resource) => resource.name));
8839
+ return {
8840
+ scope: "global",
8841
+ configured,
8842
+ [key]: resources.map((resource) => ({ ...resource, enabled: enabled.has(resource.name) })),
8843
+ };
8844
+ }
8845
+
8846
+ async function getToolConfigData(tab, requestedScope = "session") {
8847
+ const scope = requireResourceScope(requestedScope);
8848
+ const runtime = await sendWebuiHelperCommand(tab, "tools-state");
8849
+ if (scope === "session") return { ...runtime, scope };
8850
+ const defaults = (await readWebuiSettings()).resourceDefaults.tools.enabledTools;
8851
+ return globalResourcePayload("tools", runtime.tools || [], defaults);
8595
8852
  }
8596
8853
 
8597
8854
  let packageManagerModulePromise;
@@ -8784,88 +9041,56 @@ async function saveSkillFileData(tab, body = {}) {
8784
9041
  };
8785
9042
  }
8786
9043
 
8787
- function getResourcePatternForSkill(tab, skill) {
8788
- const info = skill.sourceInfo || {};
8789
- const baseDir = info.baseDir || (info.scope === "project" ? path.join(tab?.cwd || options.cwd, ".pi") : agentDir);
8790
- return path.relative(baseDir, skill.filePath);
8791
- }
8792
-
8793
9044
  async function setToolConfigData(tab, body) {
8794
- return sendWebuiHelperCommand(tab, "tools-set", {
8795
- enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
8796
- disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
8797
- });
8798
- }
9045
+ const scope = requireResourceScope(body?.scope);
9046
+ if (scope === "session") {
9047
+ return {
9048
+ ...(await sendWebuiHelperCommand(tab, "tools-set", {
9049
+ enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
9050
+ disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
9051
+ })),
9052
+ scope,
9053
+ };
9054
+ }
8799
9055
 
8800
- async function getSkillConfigDataFromRuntime(tab) {
8801
- return sendWebuiHelperCommand(tab, "skills-state");
9056
+ const runtime = await sendWebuiHelperCommand(tab, "tools-state");
9057
+ const currentSettings = await readWebuiSettings();
9058
+ const selectedTools = selectedResourceNames(body, "enabledTools", "disabledTools", runtime.tools, "Tool");
9059
+ const enabledTools = preserveUnavailableGlobalNames(selectedTools, runtime.tools, currentSettings.resourceDefaults.tools.enabledTools);
9060
+ await writeWebuiSettings({ resourceDefaults: { tools: { enabledTools } } });
9061
+ return globalResourcePayload("tools", runtime.tools || [], enabledTools);
8802
9062
  }
8803
9063
 
8804
- function desiredSkillEnabledFromBody(skillName, body) {
8805
- if (Array.isArray(body.enabledSkills)) return body.enabledSkills.map(String).includes(skillName);
8806
- if (Array.isArray(body.disabledSkills)) return !body.disabledSkills.map(String).includes(skillName);
8807
- throw makeHttpError(400, "Skill update requires enabledSkills or disabledSkills");
9064
+ async function getSkillConfigData(tab, requestedScope = "session") {
9065
+ const scope = requireResourceScope(requestedScope);
9066
+ const runtime = await getSkillConfigDataFromRuntime(tab);
9067
+ if (scope === "session") return { ...runtime, scope };
9068
+ const defaults = (await readWebuiSettings()).resourceDefaults.skills.enabledSkills;
9069
+ return globalResourcePayload("skills", runtime.skills || [], defaults);
8808
9070
  }
8809
9071
 
8810
- function updatePatternListForResource(current, pattern, enabled) {
8811
- const updated = (current || []).filter((item) => {
8812
- const text = String(item || "");
8813
- const stripped = text.startsWith("!") || text.startsWith("+") || text.startsWith("-") ? text.slice(1) : text;
8814
- return stripped !== pattern;
8815
- });
8816
- updated.push(`${enabled ? "+" : "-"}${pattern}`);
8817
- return updated;
8818
- }
8819
-
8820
- function setSkillPathsForScope(settingsManager, scope, updated) {
8821
- if (scope === "project") settingsManager.setProjectSkillPaths(updated);
8822
- else settingsManager.setSkillPaths(updated);
8823
- }
8824
-
8825
- function toggleConfiguredSkill(tab, settingsManager, skill, enabled) {
8826
- const info = skill.sourceInfo || {};
8827
- const scope = info.scope === "project" ? "project" : "user";
8828
- if (info.origin === "package") {
8829
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8830
- const packages = [...(settings.packages || [])];
8831
- const packageIndex = packages.findIndex((item) => (typeof item === "string" ? item : item?.source) === info.source);
8832
- if (packageIndex < 0) return false;
8833
- let packageEntry = packages[packageIndex];
8834
- if (typeof packageEntry === "string") {
8835
- packageEntry = { source: packageEntry };
8836
- packages[packageIndex] = packageEntry;
8837
- }
8838
- const pattern = path.relative(info.baseDir || path.dirname(skill.filePath), skill.filePath);
8839
- packageEntry.skills = updatePatternListForResource(packageEntry.skills || [], pattern, enabled);
8840
- if (scope === "project") settingsManager.setProjectPackages(packages);
8841
- else settingsManager.setPackages(packages);
8842
- return true;
8843
- }
8844
-
8845
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8846
- const pattern = getResourcePatternForSkill(tab, skill);
8847
- setSkillPathsForScope(settingsManager, scope, updatePatternListForResource(settings.skills || [], pattern, enabled));
8848
- return true;
9072
+ async function getSkillConfigDataFromRuntime(tab) {
9073
+ return sendWebuiHelperCommand(tab, "skills-state");
8849
9074
  }
8850
9075
 
8851
9076
  async function setSkillConfigData(tab, body) {
8852
- const { skills, settingsManager } = await resolveSkillResources(tab);
8853
- let configChanged = false;
8854
- for (const skill of skills) {
8855
- const desiredEnabled = desiredSkillEnabledFromBody(skill.name, body);
8856
- if (skill.configEnabled !== desiredEnabled && toggleConfiguredSkill(tab, settingsManager, skill, desiredEnabled)) configChanged = true;
8857
- }
8858
-
8859
- const runtimeOnly = skills.length === 0;
8860
- if (runtimeOnly) {
8861
- await sendWebuiHelperCommand(tab, "skills-set", {
8862
- enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
8863
- disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
8864
- });
9077
+ const scope = requireResourceScope(body?.scope);
9078
+ if (scope === "session") {
9079
+ return {
9080
+ ...(await sendWebuiHelperCommand(tab, "skills-set", {
9081
+ enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
9082
+ disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
9083
+ })),
9084
+ scope,
9085
+ };
8865
9086
  }
8866
9087
 
8867
- const activeTab = configChanged ? await restartTabRpc(tab, "skills-config") : tab;
8868
- return getMergedSkillConfigData(activeTab);
9088
+ const runtime = await getSkillConfigDataFromRuntime(tab);
9089
+ const currentSettings = await readWebuiSettings();
9090
+ const selectedSkills = selectedResourceNames(body, "enabledSkills", "disabledSkills", runtime.skills, "Skill");
9091
+ const enabledSkills = preserveUnavailableGlobalNames(selectedSkills, runtime.skills, currentSettings.resourceDefaults.skills.enabledSkills);
9092
+ await writeWebuiSettings({ resourceDefaults: { skills: { enabledSkills } } });
9093
+ return globalResourcePayload("skills", runtime.skills || [], enabledSkills);
8869
9094
  }
8870
9095
 
8871
9096
  function settingsManagerForTab(tab) {
@@ -10159,7 +10384,12 @@ async function switchTabSession(tab, sessionPath) {
10159
10384
  let authContextCache;
10160
10385
 
10161
10386
  function authContext() {
10162
- if (!authContextCache) authContextCache = createAuthContext();
10387
+ if (!authContextCache) {
10388
+ authContextCache = createAuthContext().catch((error) => {
10389
+ authContextCache = undefined;
10390
+ throw error;
10391
+ });
10392
+ }
10163
10393
  return authContextCache;
10164
10394
  }
10165
10395
 
@@ -10192,13 +10422,13 @@ async function deleteSessionData(tab, body) {
10192
10422
  };
10193
10423
  }
10194
10424
 
10195
- function getAuthProvidersData() {
10196
- return authProvidersPayload(authContext().modelRegistry);
10425
+ async function getAuthProvidersData() {
10426
+ return authProvidersPayload((await authContext()).modelRuntime);
10197
10427
  }
10198
10428
 
10199
- function logoutAuthProviderData(body) {
10429
+ async function logoutAuthProviderData(body) {
10200
10430
  if (body.confirmed !== true) throw makeHttpError(409, "Logout requires explicit confirmation (confirmed: true).");
10201
- return logoutStoredProvider(authContext().modelRegistry, body.provider || body.providerId);
10431
+ return logoutStoredProvider((await authContext()).modelRuntime, body.provider || body.providerId);
10202
10432
  }
10203
10433
 
10204
10434
  async function navigateSessionTree(tab, body) {
@@ -10274,14 +10504,12 @@ async function handleNativeExportCommand(tab, args, req) {
10274
10504
  fileName: `${nativeExportBaseName(tab, state)}.html`,
10275
10505
  contentType: MIME_TYPES.get(".html"),
10276
10506
  });
10277
- return respondNative("export", {
10278
- status: "succeeded",
10279
- level: "info",
10280
- message: `Exported current session to HTML.\nDownload: ${download.fileName}\nOpen it in your browser when prompted.\nOpen URL: ${download.openUrl || download.url}\nDownload URL: ${download.url}\nLink expires: ${download.expiresAt}`,
10507
+ return respondNative("export", nativeExportDownloadPayload({
10508
+ localRequest: isLocalRequest(req),
10509
+ exportedPath,
10281
10510
  download,
10282
- result: response.data,
10283
- refresh: ["state"],
10284
- });
10511
+ responseData: response.data,
10512
+ }));
10285
10513
  }
10286
10514
 
10287
10515
  if (!isLocalRequest(req)) {
@@ -10498,6 +10726,68 @@ async function closeTab(id) {
10498
10726
  return tab;
10499
10727
  }
10500
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
+
10501
10791
  async function closeTabs(ids) {
10502
10792
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
10503
10793
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
@@ -10909,6 +11199,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
10909
11199
  const data = {
10910
11200
  online: true,
10911
11201
  webuiVersion: packageJson.version,
11202
+ piVersion: String(piPackageJson.version || ""),
10912
11203
  webuiDev: webuiDevServer,
10913
11204
  webuiMode: webuiDevServer ? "dev" : "production",
10914
11205
  webuiPid: process.pid,
@@ -10959,6 +11250,13 @@ const server = createServer(async (req, res) => {
10959
11250
  return;
10960
11251
  }
10961
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
+
10962
11260
  if (shouldChallengeRemoteAuth(req, url)) {
10963
11261
  sendRemoteAuthRequired(req, res, url);
10964
11262
  return;
@@ -11041,6 +11339,7 @@ const server = createServer(async (req, res) => {
11041
11339
  sendSse(res, {
11042
11340
  type: "webui_connected",
11043
11341
  version: packageJson.version,
11342
+ piVersion: String(piPackageJson.version || ""),
11044
11343
  webuiDev: webuiDevServer,
11045
11344
  webuiMode: webuiDevServer ? "dev" : "production",
11046
11345
  tabId: tab.id,
@@ -11068,6 +11367,7 @@ const server = createServer(async (req, res) => {
11068
11367
  sendJson(res, 200, {
11069
11368
  ok: true,
11070
11369
  webuiVersion: status.webuiVersion,
11370
+ piVersion: status.piVersion,
11071
11371
  webuiDev: status.webuiDev,
11072
11372
  webuiMode: status.webuiMode,
11073
11373
  webuiPid: status.webuiPid,
@@ -11081,6 +11381,11 @@ const server = createServer(async (req, res) => {
11081
11381
  return;
11082
11382
  }
11083
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
+
11084
11389
  if (url.pathname === "/api/webui-status" && req.method === "GET") {
11085
11390
  const detailed = ["1", "true", "yes", "detailed"].includes(String(url.searchParams.get("detailed") || "").toLowerCase());
11086
11391
  const parsedEventLimit = Number.parseInt(url.searchParams.get("events") || "40", 10);
@@ -11482,14 +11787,14 @@ const server = createServer(async (req, res) => {
11482
11787
  }
11483
11788
 
11484
11789
  if (url.pathname === "/api/auth-providers" && req.method === "GET") {
11485
- sendJson(res, 200, { ok: true, data: getAuthProvidersData() });
11790
+ sendJson(res, 200, { ok: true, data: await getAuthProvidersData() });
11486
11791
  return;
11487
11792
  }
11488
11793
 
11489
11794
  if (url.pathname === "/api/auth-logout" && req.method === "POST") {
11490
11795
  requireLocalhostRoute(req, url.pathname);
11491
11796
  const body = await readJsonBody(req);
11492
- sendJson(res, 200, { ok: true, data: logoutAuthProviderData(body) });
11797
+ sendJson(res, 200, { ok: true, data: await logoutAuthProviderData(body) });
11493
11798
  return;
11494
11799
  }
11495
11800
 
@@ -11575,7 +11880,7 @@ const server = createServer(async (req, res) => {
11575
11880
 
11576
11881
  if (url.pathname === "/api/tools" && req.method === "GET") {
11577
11882
  const tab = getRequestedTab(req, url);
11578
- sendJson(res, 200, { ok: true, data: await getToolConfigData(tab) });
11883
+ sendJson(res, 200, { ok: true, data: await getToolConfigData(tab, url.searchParams.get("scope")) });
11579
11884
  return;
11580
11885
  }
11581
11886
 
@@ -11589,7 +11894,7 @@ const server = createServer(async (req, res) => {
11589
11894
 
11590
11895
  if (url.pathname === "/api/skills" && req.method === "GET") {
11591
11896
  const tab = getRequestedTab(req, url);
11592
- sendJson(res, 200, { ok: true, data: await getMergedSkillConfigData(tab) });
11897
+ sendJson(res, 200, { ok: true, data: await getSkillConfigData(tab, url.searchParams.get("scope")) });
11593
11898
  return;
11594
11899
  }
11595
11900
 
@@ -11616,6 +11921,20 @@ const server = createServer(async (req, res) => {
11616
11921
  return;
11617
11922
  }
11618
11923
 
11924
+ if (url.pathname === "/api/safety-guard/config" && req.method === "GET") {
11925
+ getRequestedTab(req, url);
11926
+ sendJson(res, 200, { ok: true, data: await safetyGuardConfigData() });
11927
+ return;
11928
+ }
11929
+
11930
+ if (url.pathname === "/api/safety-guard/config" && req.method === "POST") {
11931
+ const body = await readJsonBody(req);
11932
+ const tab = getRequestedTab(req, url, body);
11933
+ ensureNaturalConversationRouteAllowed(tab, "safety guard setup changes are blocked");
11934
+ sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(body) });
11935
+ return;
11936
+ }
11937
+
11619
11938
  if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11620
11939
  const tab = getRequestedTab(req, url);
11621
11940
  sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
@@ -11856,6 +12175,7 @@ const server = createServer(async (req, res) => {
11856
12175
  "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11857
12176
  "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11858
12177
  "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
12178
+ "/api/git-operation/resolve-with-agent": (_cwd, _body, tab) => openGitConflictResolutionAgentTab(tab),
11859
12179
  "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11860
12180
  "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11861
12181
  "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
@@ -11874,7 +12194,7 @@ const server = createServer(async (req, res) => {
11874
12194
  const tab = getRequestedTab(req, url, body);
11875
12195
  ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11876
12196
  try {
11877
- const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
12197
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body, tab);
11878
12198
  sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11879
12199
  } catch (error) {
11880
12200
  gitActionError(error);