@firstpick/pi-package-webui 0.8.3 → 0.8.4

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
@@ -15,6 +15,11 @@ import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendi
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
16
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
17
  import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
18
+ import {
19
+ readSessionSummaryPreferences,
20
+ supportedSessionSummaryThinkingLevels,
21
+ writeSessionSummaryPreferences,
22
+ } from "../lib/session-summary-preferences.mjs";
18
23
  import {
19
24
  deleteWebuiWorkspace,
20
25
  getWebuiWorkspace,
@@ -41,6 +46,11 @@ import {
41
46
  } from "../lib/git-command-errors.mjs";
42
47
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
43
48
  import { ComponentUpdateState, validateComponentUpdateRequest } from "../lib/component-update-state.mjs";
49
+ import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
50
+ import {
51
+ OptionalFeatureAuditCoordinator,
52
+ OptionalFeatureMigrationStore,
53
+ } from "../lib/optional-feature-migration.mjs";
44
54
  import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
45
55
  import {
46
56
  GIT_WORKFLOW_DEFAULT_VARIANTS,
@@ -130,6 +140,7 @@ const require = createRequire(import.meta.url);
130
140
  const packageRoot = path.resolve(__dirname, "..");
131
141
  const publicDir = path.join(packageRoot, "public");
132
142
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
143
+ const sessionSummaryExtensionPath = path.join(packageRoot, "session-summary.ts");
133
144
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
134
145
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
135
146
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
@@ -188,6 +199,16 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
188
199
  const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
189
200
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
190
201
  const BODY_LIMIT_BYTES = 1024 * 1024;
202
+ const SESSION_SUMMARY_REQUEST_MAX_BYTES = 32 * 1024;
203
+ const SESSION_SUMMARY_RPC_TYPE = "firstpick:session-summary-rpc";
204
+ const SESSION_SUMMARY_DISPLAY_TYPE = "firstpick:session-summary-display";
205
+ const SESSION_SUMMARY_PROTOCOL_VERSION = 1;
206
+ const SESSION_SUMMARY_TITLE_MAX_CHARS = 44;
207
+ const SESSION_SUMMARY_MARKDOWN_MAX_CHARS = 16 * 1024;
208
+ const SESSION_SUMMARY_PROMPT_MAX_CHARS = 8 * 1024;
209
+ const SESSION_SUMMARY_FAILURE_MAX_CHARS = 512;
210
+ const SESSION_SUMMARY_GENERATE_TIMEOUT_MS = 105 * 1000;
211
+ const SESSION_SUMMARY_KINDS = new Set(["setup", "state", "generating", "success", "failure", "title"]);
191
212
  const RECOVERY_ENDPOINT_PATH = "/api/recovery/plan";
192
213
  const RECOVERY_BODY_LIMIT_BYTES = 256 * 1024;
193
214
  const RECOVERY_PROMPT_MAX_CHARS = 200_000;
@@ -376,38 +397,13 @@ function parseSlashCommand(message) {
376
397
  return parseNativeSlashCommand(message, NATIVE_SLASH_COMMAND_NAMES);
377
398
  }
378
399
  const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
379
- const OPTIONAL_FEATURE_PACKAGES = new Map([
380
- ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete"],
381
- ["fishUserBash", "@firstpick/pi-extension-fish-user-bash"],
382
- ["btwCommand", "@firstpick/pi-extension-btw"],
383
- ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
384
- ["releaseNpm", "@firstpick/pi-extension-release-npm"],
385
- ["releaseAur", "@firstpick/pi-extension-release-aur"],
386
- ["aurReview", "@firstpick/pi-extension-aur-review"],
387
- ["workflows", "@firstpick/pi-extension-workflows"],
388
- ["safetyGuard", "@firstpick/pi-extension-safety-guard"],
389
- ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills"],
390
- ["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
391
- ["tuiToolsCommand", "@firstpick/pi-extension-tools"],
392
- ["remoteWebui", "@firstpick/pi-package-remote-webui"],
393
- ["questionnaire", "@firstpick/pi-package-questionnaire"],
394
- ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
395
- ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
396
- ["statsCommand", "@firstpick/pi-extension-stats"],
397
- ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
398
- ["themeBundle", "@firstpick/pi-themes-bundle"],
399
- ]);
400
- const WEBUI_CONTROLLED_PACKAGES = new Set([
401
- WEBUI_PACKAGE,
402
- ...[...OPTIONAL_FEATURE_PACKAGES.entries()]
403
- .filter(([featureId]) => featureId !== NATURAL_CONVERSATION_FEATURE_ID)
404
- .map(([, packageName]) => packageName),
405
- ]);
406
- const UPDATE_PACKAGE_NAMES = [...new Set([
407
- ...CORE_UPDATE_PACKAGE_NAMES,
408
- ...WEBUI_CONTROLLED_PACKAGES,
409
- ...OPTIONAL_FEATURE_PACKAGES.values(),
410
- ])].sort();
400
+ const OPTIONAL_FEATURE_PACKAGES = new Map(OPTIONAL_FEATURE_CATALOG.map(({ featureId, packageName }) => [featureId, packageName]));
401
+ const OPTIONAL_FEATURE_PACKAGE_NAMES = new Set(OPTIONAL_FEATURE_PACKAGES.values());
402
+ const WEBUI_RESOURCE_EXCLUDED_PACKAGES = new Set([WEBUI_PACKAGE]);
403
+ let optionalFeatureMigrationStore;
404
+ let optionalFeatureAuditCoordinator;
405
+ let optionalFeatureStartupReady = false;
406
+ const UPDATE_PACKAGE_NAMES = [...CORE_UPDATE_PACKAGE_NAMES].sort();
411
407
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
412
408
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
413
409
  // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
@@ -439,6 +435,8 @@ Options:
439
435
  --remote-auth Enable startup PIN authentication for non-local clients
440
436
  --no-remote-auth Disable startup PIN authentication
441
437
  --output-mode <mode> Web UI output default: normal or compact-v1
438
+ --migrate-optional-features Migrate audit-selected legacy optional features
439
+ --migration-dry-run Print the startup migration plan without package mutation
442
440
  -h, --help Show this help
443
441
  -v, --version Print version
444
442
 
@@ -488,6 +486,8 @@ function parseArgs(argv) {
488
486
  remoteAuthExplicit: process.env.PI_WEBUI_REMOTE_AUTH !== undefined,
489
487
  outputMode: undefined,
490
488
  envOutputMode: process.env.PI_WEBUI_OUTPUT_MODE === undefined ? undefined : requiredOutputMode(process.env.PI_WEBUI_OUTPUT_MODE, "PI_WEBUI_OUTPUT_MODE"),
489
+ migrateOptionalFeatures: false,
490
+ migrationDryRun: false,
491
491
  piArgs: [],
492
492
  help: false,
493
493
  version: false,
@@ -547,6 +547,14 @@ function parseArgs(argv) {
547
547
  i++;
548
548
  continue;
549
549
  }
550
+ if (arg === "--migrate-optional-features") {
551
+ options.migrateOptionalFeatures = true;
552
+ continue;
553
+ }
554
+ if (arg === "--migration-dry-run") {
555
+ options.migrationDryRun = true;
556
+ continue;
557
+ }
550
558
  if (arg === "--remote-auth") {
551
559
  options.remoteAuth = true;
552
560
  options.remoteAuthExplicit = true;
@@ -1889,38 +1897,11 @@ function declaredDependencySpec(pkg, packageName) {
1889
1897
  );
1890
1898
  }
1891
1899
 
1892
- async function installRootDeclaresPackage(root, packageName) {
1893
- const pkg = await readJsonFileIfExists(path.join(root, "package.json"));
1894
- return declaredDependencySpec(pkg, packageName) !== undefined;
1895
- }
1896
-
1897
- async function installRootContainsPackage(root, packageName) {
1898
- return directoryExists(packageNodeModulesPath(path.join(root, "node_modules"), packageName));
1899
- }
1900
-
1901
1900
  function configuredAgentNpmRoot() {
1902
1901
  const root = process.env.PI_CODING_AGENT_DIR ? path.resolve(expandUserPath(process.env.PI_CODING_AGENT_DIR)) : agentDir;
1903
1902
  return path.join(root, "npm");
1904
1903
  }
1905
1904
 
1906
- async function optionalDependencyInstallRoot() {
1907
- const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
1908
- if (configuredRoot) return path.resolve(expandUserPath(configuredRoot));
1909
-
1910
- const installRoot = nodeModulesParentForPackageRoot(packageRoot);
1911
- if (await installRootDeclaresPackage(installRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(installRoot, "@firstpick/pi-package-webui")) return installRoot;
1912
-
1913
- const agentNpmRoot = configuredAgentNpmRoot();
1914
- if (installRoot !== agentNpmRoot && (await installRootDeclaresPackage(agentNpmRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(agentNpmRoot, "@firstpick/pi-package-webui"))) return agentNpmRoot;
1915
-
1916
- if (webuiDevServer) return installRoot;
1917
-
1918
- throw makeHttpError(
1919
- 500,
1920
- `Could not determine a safe optional feature install root. Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi package root.`,
1921
- );
1922
- }
1923
-
1924
1905
  function minimumPackageVersionFromSpec(spec) {
1925
1906
  const match = String(spec || "").match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/);
1926
1907
  return match?.[0] || "";
@@ -1984,33 +1965,124 @@ async function resolveInstalledPackageSubpath(packageName, subpath = "") {
1984
1965
  }
1985
1966
  }
1986
1967
 
1987
- function optionalFeatureDeclaredSpec(packageName) {
1988
- return declaredDependencySpec(packageJson, packageName) || "";
1968
+ function npmPackageNameFromPiSource(source) {
1969
+ const spec = String(source || "").trim();
1970
+ if (!spec.startsWith("npm:")) return "";
1971
+ const npmSpec = spec.slice("npm:".length);
1972
+ if (!npmSpec) return "";
1973
+ if (npmSpec.startsWith("@")) {
1974
+ const slashIndex = npmSpec.indexOf("/");
1975
+ if (slashIndex < 2) return "";
1976
+ const versionIndex = npmSpec.indexOf("@", slashIndex);
1977
+ return versionIndex === -1 ? npmSpec : npmSpec.slice(0, versionIndex);
1978
+ }
1979
+ const versionIndex = npmSpec.indexOf("@");
1980
+ return versionIndex === -1 ? npmSpec : npmSpec.slice(0, versionIndex);
1981
+ }
1982
+
1983
+ async function configuredOptionalFeaturePackages(packageName, cwd = options.cwd) {
1984
+ const settingsManager = SettingsManager.create(cwd, agentDir);
1985
+ const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
1986
+ const matches = [];
1987
+ for (const configuredPackage of packageManager.listConfiguredPackages()) {
1988
+ if (npmPackageNameFromPiSource(configuredPackage.source) === packageName) {
1989
+ matches.push(configuredPackage);
1990
+ continue;
1991
+ }
1992
+ const manifest = configuredPackage.installedPath
1993
+ ? await readJsonFileIfExists(path.join(configuredPackage.installedPath, "package.json"))
1994
+ : null;
1995
+ if (manifest?.name === packageName) matches.push(configuredPackage);
1996
+ }
1997
+ return matches;
1998
+ }
1999
+
2000
+ async function topLevelOptionalFeatureResourceIndex(cwd = options.cwd) {
2001
+ const settingsManager = SettingsManager.create(cwd, agentDir);
2002
+ const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
2003
+ const resolved = await packageManager.resolve(async () => "skip");
2004
+ const resourcesByPackage = new Map();
2005
+ for (const resourceType of ["extensions", "skills", "prompts", "themes"]) {
2006
+ for (const resource of resolved[resourceType] || []) {
2007
+ if (!resource.enabled || resource.metadata?.origin === "package") continue;
2008
+ let ownershipPath = resource.path;
2009
+ try {
2010
+ ownershipPath = await realpath(resource.path);
2011
+ } catch {
2012
+ // Keep the reported path when the resource disappears during status collection.
2013
+ }
2014
+ const packageName = await packageNameForResourcePath(ownershipPath);
2015
+ if (!packageName) continue;
2016
+ const resourcePaths = resourcesByPackage.get(packageName) || [];
2017
+ resourcePaths.push(resource.path);
2018
+ resourcesByPackage.set(packageName, resourcePaths);
2019
+ }
2020
+ }
2021
+ return resourcesByPackage;
2022
+ }
2023
+
2024
+ async function topLevelOptionalFeatureResources(packageName, cwd = options.cwd, resourceIndex) {
2025
+ const resourcesByPackage = resourceIndex || await topLevelOptionalFeatureResourceIndex(cwd);
2026
+ return [...new Set(resourcesByPackage.get(packageName) || [])];
1989
2027
  }
1990
2028
 
1991
- async function optionalFeaturePackageStatus(featureId) {
1992
- const packageName = OPTIONAL_FEATURE_PACKAGES.get(featureId);
1993
- if (!packageName) throw makeHttpError(400, `Unknown optional feature: ${featureId}`);
1994
- const declaredSpec = optionalFeatureDeclaredSpec(packageName);
1995
- const installedRoot = await resolveInstalledPackageRoot(packageName);
2029
+ async function installedOptionalFeatureRoot(packageName, configuredPackages) {
2030
+ const discoveredRoot = await resolveInstalledPackageRoot(packageName);
2031
+ const candidates = [discoveredRoot, ...configuredPackages.map(({ installedPath }) => installedPath)].filter(Boolean);
2032
+ for (const candidate of candidates) {
2033
+ const manifest = await readJsonFileIfExists(path.join(candidate, "package.json"));
2034
+ if (manifest?.name === packageName) return candidate;
2035
+ }
2036
+ return null;
2037
+ }
2038
+
2039
+ async function optionalFeaturePackageStatus(featureId, cwd = options.cwd, topLevelResourceIndex) {
2040
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
2041
+ if (!feature) throw makeHttpError(400, `Unknown optional feature: ${featureId}`);
2042
+ const { packageName, expectedSpec } = feature;
2043
+ const [configuredPackages, topLevelResources] = await Promise.all([
2044
+ configuredOptionalFeaturePackages(packageName, cwd),
2045
+ topLevelOptionalFeatureResources(packageName, cwd, topLevelResourceIndex),
2046
+ ]);
2047
+ const installedRoot = await installedOptionalFeatureRoot(packageName, configuredPackages);
1996
2048
  const manifest = installedRoot ? await readJsonFileIfExists(path.join(installedRoot, "package.json")) : null;
1997
2049
  const installedVersion = typeof manifest?.version === "string" ? manifest.version : "";
1998
- const updateAvailable = !!(installedVersion && packageVersionBelowSpec(installedVersion, declaredSpec));
2050
+ const installed = !!installedRoot;
2051
+ const configured = configuredPackages.length > 0;
2052
+ const locallyConfigured = topLevelResources.length > 0;
2053
+ const legacyRoot = path.join(packageRoot, "node_modules", ...packageName.split("/"));
2054
+ const legacyManifest = await readJsonFileIfExists(path.join(legacyRoot, "package.json"));
2055
+ const legacyEvidence = legacyManifest?.name === packageName;
2056
+ const disabled = configuredPackages.length > 0 && configuredPackages.every((entry) => entry.enabled === false);
2057
+ const resourceConflict = configured && locallyConfigured;
2058
+ const ready = installed && (configured || locallyConfigured) && !resourceConflict;
2059
+ const updateAvailable = !!(installedVersion && packageVersionBelowSpec(installedVersion, expectedSpec));
1999
2060
  return {
2000
2061
  featureId,
2001
2062
  packageName,
2002
- declaredSpec,
2003
- installed: !!installedRoot,
2063
+ expectedSpec,
2064
+ declaredSpec: expectedSpec,
2065
+ installed,
2066
+ configured,
2067
+ locallyConfigured,
2068
+ resourceConflict,
2069
+ ready,
2004
2070
  installedVersion,
2005
2071
  installedRoot,
2072
+ topLevelResources,
2073
+ legacyEvidence,
2074
+ disabled,
2006
2075
  updateAvailable,
2007
- updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${declaredSpec})` : "",
2076
+ updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${expectedSpec})` : "",
2008
2077
  };
2009
2078
  }
2010
2079
 
2011
- async function optionalFeaturePackageStatuses() {
2080
+ async function optionalFeaturePackageStatuses(cwd = options.cwd) {
2012
2081
  const features = [];
2013
- for (const featureId of OPTIONAL_FEATURE_PACKAGES.keys()) features.push(await optionalFeaturePackageStatus(featureId));
2082
+ const topLevelResourceIndex = await topLevelOptionalFeatureResourceIndex(cwd);
2083
+ for (const { featureId } of OPTIONAL_FEATURE_CATALOG) {
2084
+ features.push(await optionalFeaturePackageStatus(featureId, cwd, topLevelResourceIndex));
2085
+ }
2014
2086
  return { features };
2015
2087
  }
2016
2088
 
@@ -2023,28 +2095,28 @@ function optionalFeatureInstallOutputTail(result, maxLength = 4000) {
2023
2095
  function optionalFeatureInstallFailureKind(result, message = "") {
2024
2096
  const combined = `${message}\n${result?.error || ""}\n${result?.stderr || ""}\n${result?.stdout || ""}`;
2025
2097
  if (result?.timedOut) return "timeout";
2026
- if (/\b(?:ENOENT|command not found|not recognized|spawn\s+\S+\s+ENOENT)\b/i.test(combined)) return "npm-not-found";
2098
+ if (/\b(?:ENOENT|command not found|not recognized|spawn\s+\S+\s+ENOENT)\b/i.test(combined)) return "pi-not-found";
2027
2099
  if (/\b(?:EACCES|EPERM|permission denied|access denied)\b/i.test(combined)) return "permission";
2028
2100
  if (/\b(?:EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT|network timeout|registry\.npmjs\.org|fetch failed)\b/i.test(combined)) return "network";
2029
- return "npm-exit";
2101
+ return "pi-exit";
2030
2102
  }
2031
2103
 
2032
- function optionalFeatureInstallFailureHint(kind, { command, installRoot } = {}) {
2104
+ function optionalFeatureInstallFailureHint(kind, { command } = {}) {
2033
2105
  switch (kind) {
2034
- case "install-root":
2035
- return `Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi/Web UI npm package root, then retry.`;
2036
- case "npm-not-found":
2037
- return "npm could not be started. Install npm or set PI_WEBUI_NPM_BIN to an absolute npm-compatible executable path.";
2106
+ case "pi-not-found":
2107
+ return "The selected Pi CLI could not be started. Check --pi or PI_WEBUI_PI_BIN, then restart the Web UI.";
2038
2108
  case "permission":
2039
- return `The Web UI process cannot write to ${installRoot || "the selected npm prefix"}. Retry from the owning user or use ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} with a writable package root.`;
2109
+ return "Pi could not update its user package root or settings. Retry as the owning user or run the copied command manually.";
2040
2110
  case "network":
2041
- return "npm could not reach the registry reliably. Check network/proxy/registry settings, then retry or run the copied command manually.";
2111
+ return "Pi could not reach the npm registry reliably. Check network/proxy/registry settings, then retry or run the copied command manually.";
2042
2112
  case "timeout":
2043
- return "npm did not finish within 5 minutes. Check for a stuck package manager, lock contention, or slow network, then retry manually.";
2113
+ return "Pi did not finish within 5 minutes. Check for a stuck package manager, lock contention, or slow network, then retry manually.";
2114
+ case "local-resource-conflict":
2115
+ return "This companion is already enabled as a top-level Pi resource. Keep that local resource, or disable/remove its extensions/skills/prompts/themes alias before registering the npm package.";
2044
2116
  case "status-check":
2045
- return "npm finished, but Web UI could not verify the package status. Reload the Web UI and recheck Optional features.";
2117
+ return "Pi finished, but Web UI could not verify both installation and registration. Reload the Web UI and recheck Optional features.";
2046
2118
  default:
2047
- return command ? "Run the copied npm command manually on the Web UI host to see full package-manager diagnostics." : "Check the activity log and npm output, then retry.";
2119
+ return command ? "Run the copied Pi command manually on the Web UI host to see full diagnostics." : "Check the activity log and Pi output, then retry.";
2048
2120
  }
2049
2121
  }
2050
2122
 
@@ -2065,27 +2137,26 @@ function makeOptionalFeatureInstallError(statusCode, message, details = {}) {
2065
2137
  return error;
2066
2138
  }
2067
2139
 
2068
- async function installOptionalFeaturePackage(featureId) {
2069
- const beforeStatus = await optionalFeaturePackageStatus(featureId);
2140
+ async function installOptionalFeaturePackage(featureId, cwd = options.cwd) {
2141
+ const beforeStatus = await optionalFeaturePackageStatus(featureId, cwd);
2070
2142
  const packageName = beforeStatus.packageName;
2071
-
2072
- let installRoot;
2073
- try {
2074
- installRoot = await optionalDependencyInstallRoot();
2075
- } catch (error) {
2076
- const message = formatCliError(error);
2077
- throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2078
- kind: "install-root",
2143
+ const source = `npm:${packageName}`;
2144
+ if (beforeStatus.locallyConfigured) {
2145
+ const message = beforeStatus.resourceConflict
2146
+ ? `${packageName} is configured both as a Pi package and as a top-level resource; installing it again would preserve the duplicate-load conflict`
2147
+ : `${packageName} is already enabled as a top-level Pi resource; installing the npm package would load it twice`;
2148
+ throw makeOptionalFeatureInstallError(409, message, {
2149
+ kind: "local-resource-conflict",
2079
2150
  featureId,
2080
2151
  packageName,
2081
- hint: optionalFeatureInstallFailureHint("install-root"),
2152
+ command: `pi install ${source}`,
2153
+ hint: optionalFeatureInstallFailureHint("local-resource-conflict"),
2082
2154
  });
2083
2155
  }
2084
-
2085
- const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, packageName]);
2086
- const command = npmCommand.displayCommand;
2087
- const result = await runCommand(npmCommand.command, npmCommand.args, {
2088
- cwd: installRoot,
2156
+ const piCommand = await resolvePiCommand(["install", source]);
2157
+ const command = piCommand.displayCommand;
2158
+ const result = await runCommand(piCommand.command, piCommand.args, {
2159
+ cwd,
2089
2160
  timeoutMs: 5 * 60 * 1000,
2090
2161
  maxOutputLength: 80000,
2091
2162
  });
@@ -2101,40 +2172,167 @@ async function installOptionalFeaturePackage(featureId) {
2101
2172
  kind,
2102
2173
  featureId,
2103
2174
  packageName,
2104
- installRoot,
2105
2175
  command,
2106
2176
  exitCode: result.exitCode,
2107
2177
  timedOut: result.timedOut,
2108
2178
  outputTail: optionalFeatureInstallOutputTail(result),
2109
2179
  });
2110
2180
  }
2181
+
2111
2182
  let afterStatus;
2112
2183
  try {
2113
- afterStatus = await optionalFeaturePackageStatus(featureId);
2184
+ afterStatus = await optionalFeaturePackageStatus(featureId, cwd);
2185
+ if (!afterStatus.ready) {
2186
+ throw new Error(`Pi did not leave ${packageName} both installed and registered`);
2187
+ }
2114
2188
  } catch (error) {
2115
2189
  const message = `Optional feature install finished, but status verification failed: ${formatCliError(error)}`;
2116
2190
  throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2117
2191
  kind: "status-check",
2118
2192
  featureId,
2119
2193
  packageName,
2120
- installRoot,
2121
2194
  command,
2122
2195
  outputTail: optionalFeatureInstallOutputTail(result),
2123
2196
  });
2124
2197
  }
2125
- const operation = beforeStatus.installed ? "Updated" : "Installed";
2198
+
2199
+ const operation = beforeStatus.ready ? "Updated" : beforeStatus.installed ? "Registered" : "Installed";
2126
2200
  return {
2127
2201
  featureId,
2128
2202
  packageName,
2129
- installRoot,
2203
+ source,
2130
2204
  command,
2131
2205
  stdout: result.stdout,
2132
2206
  stderr: result.stderr,
2133
2207
  status: afterStatus,
2134
- message: `${operation} optional feature package ${packageName}${afterStatus.installedVersion ? ` to ${afterStatus.installedVersion}` : ""}. Reload the active Pi tab to load new resources.`,
2208
+ message: `${operation} optional feature package ${packageName}${afterStatus.installedVersion ? ` at ${afterStatus.installedVersion}` : ""} with Pi. Reload the active Pi tab to load new resources.`,
2209
+ };
2210
+ }
2211
+
2212
+ function validateOptionalFeatureBatch(featureIds) {
2213
+ if (!Array.isArray(featureIds)) throw makeHttpError(400, "featureIds must be an array");
2214
+ if (featureIds.length > OPTIONAL_FEATURE_CATALOG.length) {
2215
+ throw makeHttpError(400, `featureIds must contain at most ${OPTIONAL_FEATURE_CATALOG.length} entries`);
2216
+ }
2217
+ const deduplicated = [];
2218
+ const seen = new Set();
2219
+ for (const value of featureIds) {
2220
+ if (typeof value !== "string" || !OPTIONAL_FEATURE_BY_ID.has(value)) {
2221
+ throw makeHttpError(400, `Unknown optional feature: ${String(value || "")}`);
2222
+ }
2223
+ if (seen.has(value)) continue;
2224
+ seen.add(value);
2225
+ deduplicated.push(value);
2226
+ }
2227
+ return deduplicated;
2228
+ }
2229
+
2230
+ async function installOptionalFeaturePackages(featureIds, cwd = options.cwd) {
2231
+ const requestedFeatureIds = validateOptionalFeatureBatch(featureIds);
2232
+ const results = [];
2233
+ const startedAtMs = Date.now();
2234
+ const startedAt = new Date(startedAtMs).toISOString();
2235
+ const migration = optionalFeatureAuditCoordinator.current().progress?.migration === true;
2236
+ let index = 0;
2237
+ for (const featureId of requestedFeatureIds) {
2238
+ const packageName = OPTIONAL_FEATURE_BY_ID.get(featureId)?.packageName || "";
2239
+ optionalFeatureAuditCoordinator.setProgress({
2240
+ phase: "migrating",
2241
+ migration,
2242
+ startedAt,
2243
+ elapsedMs: Date.now() - startedAtMs,
2244
+ currentFeatureId: featureId,
2245
+ currentPackageName: packageName,
2246
+ index: index + 1,
2247
+ total: requestedFeatureIds.length,
2248
+ completed: index,
2249
+ remaining: requestedFeatureIds.length - index,
2250
+ results: results.map(optionalFeatureProgressResult),
2251
+ });
2252
+ try {
2253
+ results.push({ ok: true, featureId, data: await installOptionalFeaturePackage(featureId, cwd) });
2254
+ } catch (error) {
2255
+ results.push({
2256
+ ok: false,
2257
+ featureId,
2258
+ packageName,
2259
+ error: formatCliError(error),
2260
+ optionalFeatureInstall: error?.optionalFeatureInstall || null,
2261
+ });
2262
+ }
2263
+ index++;
2264
+ }
2265
+ const succeeded = results.filter((result) => result.ok).length;
2266
+ return {
2267
+ featureIds: requestedFeatureIds,
2268
+ results,
2269
+ total: results.length,
2270
+ succeeded,
2271
+ failed: results.length - succeeded,
2135
2272
  };
2136
2273
  }
2137
2274
 
2275
+ function optionalFeatureProgressResult(result) {
2276
+ return {
2277
+ featureId: result.featureId,
2278
+ packageName: result.packageName || result.data?.packageName || "",
2279
+ ok: result.ok,
2280
+ kind: result.optionalFeatureInstall?.kind || "",
2281
+ message: result.ok ? result.data?.message || "Installed and verified" : "Installation failed; see the localhost response for details",
2282
+ };
2283
+ }
2284
+
2285
+ async function runOptionalFeatureBatchMutation({ revision, featureIds, cwd = options.cwd, migration = false, tab = null, install = null }) {
2286
+ return optionalFeatureAuditCoordinator.runMutation(revision, async () => {
2287
+ optionalFeatureAuditCoordinator.setProgress({ phase: "migrating", migration, startedAt: new Date().toISOString(), completed: 0, remaining: Array.isArray(featureIds) ? featureIds.length : 0, total: Array.isArray(featureIds) ? featureIds.length : 0, results: [] });
2288
+ const batch = install ? await install() : await installOptionalFeaturePackages(featureIds, cwd);
2289
+ if (migration && batch.failed === 0) await optionalFeatureMigrationStore.completeMigration();
2290
+ await optionalFeatureAuditCoordinator.recheck({ reason: migration ? "post-migration" : "post-install" });
2291
+ const restart = { autoRestarted: false, restartDeferred: false };
2292
+ if (batch.failed === 0 && batch.total > 0 && tab) {
2293
+ const busy = tab.activity?.isWorking === true
2294
+ || pendingExtensionUiRequests(tab).length > 0
2295
+ || (tab.browserPromptRequests?.size || 0) > 0
2296
+ || (tab.bashQueue?.length || 0) > 0
2297
+ || (tab.compactionQueue?.length || 0) > 0;
2298
+ if (busy) {
2299
+ restart.restartDeferred = true;
2300
+ } else {
2301
+ try {
2302
+ await restartTabRpc(tab, "optional-feature-migration");
2303
+ restart.autoRestarted = true;
2304
+ } catch (error) {
2305
+ restart.restartDeferred = true;
2306
+ restart.reason = error?.statusCode === 409 ? "tab-busy" : "restart-failed";
2307
+ }
2308
+ }
2309
+ broadcastTabEvent(tab, {
2310
+ type: restart.autoRestarted ? "webui_optional_feature_restart_completed" : "webui_optional_feature_restart_deferred",
2311
+ tabId: tab.id,
2312
+ tabTitle: tab.title,
2313
+ ...restart,
2314
+ });
2315
+ }
2316
+ batch.restart = restart;
2317
+ optionalFeatureAuditCoordinator.setProgress({
2318
+ phase: batch.failed ? "partial" : "complete",
2319
+ migration,
2320
+ completedAt: new Date().toISOString(),
2321
+ currentFeatureId: null,
2322
+ currentPackageName: null,
2323
+ index: batch.total,
2324
+ total: batch.total,
2325
+ completed: batch.total,
2326
+ remaining: 0,
2327
+ succeeded: batch.succeeded,
2328
+ failed: batch.failed,
2329
+ results: batch.results.map(optionalFeatureProgressResult),
2330
+ ...restart,
2331
+ });
2332
+ return batch;
2333
+ });
2334
+ }
2335
+
2138
2336
  function displayPath(cwd) {
2139
2337
  const normalized = cwd.replace(/\\/g, "/");
2140
2338
  const home = (process.env.USERPROFILE || process.env.HOME || "").replace(/\\/g, "/");
@@ -2292,6 +2490,15 @@ function requireWorkflowPolicyJsonRequest(req) {
2292
2490
  }
2293
2491
  }
2294
2492
 
2493
+ function requireSessionSummaryJsonRequest(req) {
2494
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
2495
+ if (contentType !== "application/json") throw makeHttpError(415, "Session summary changes require Content-Type: application/json.");
2496
+ const fetchSite = String(req.headers["sec-fetch-site"] || "").trim().toLowerCase();
2497
+ if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") {
2498
+ throw makeHttpError(403, "Cross-origin session summary changes are blocked.");
2499
+ }
2500
+ }
2501
+
2295
2502
  function workflowPolicySaveBody(body) {
2296
2503
  if (!body || typeof body !== "object" || Array.isArray(body)) {
2297
2504
  throw makeHttpError(400, "Workflow policy save body must be an object with only policy and expectedRevision.");
@@ -2557,6 +2764,172 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2557
2764
  return gitWorkflowPreferencesData(tab);
2558
2765
  }
2559
2766
 
2767
+ function sessionSummaryModelKey(model) {
2768
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2769
+ }
2770
+
2771
+ async function availableSessionSummaryModels(tab) {
2772
+ const models = await availableGitWorkflowModels(tab);
2773
+ return models.map((model) => ({
2774
+ provider: model.provider,
2775
+ id: model.id,
2776
+ ...(model.name ? { name: String(model.name).slice(0, 240) } : {}),
2777
+ reasoning: model.reasoning === true,
2778
+ ...(model.thinkingLevelMap && typeof model.thinkingLevelMap === "object" ? { thinkingLevelMap: model.thinkingLevelMap } : {}),
2779
+ }));
2780
+ }
2781
+
2782
+ function publicSessionSummaryPreferences(value) {
2783
+ return {
2784
+ version: 1,
2785
+ configured: value?.configured === true,
2786
+ enabled: value?.enabled === true,
2787
+ model: {
2788
+ provider: String(value?.model?.provider || ""),
2789
+ modelId: String(value?.model?.modelId || ""),
2790
+ thinkingLevel: String(value?.model?.thinkingLevel || "off"),
2791
+ },
2792
+ prompts: {
2793
+ title: String(value?.prompts?.title || "").slice(0, SESSION_SUMMARY_PROMPT_MAX_CHARS),
2794
+ summary: String(value?.prompts?.summary || "").slice(0, SESSION_SUMMARY_PROMPT_MAX_CHARS),
2795
+ },
2796
+ input: { scope: "text-and-tool-names" },
2797
+ context: { injectLatest: value?.context?.injectLatest === true },
2798
+ title: {
2799
+ enabled: value?.title?.enabled !== false,
2800
+ minSettledTurns: Number.isInteger(value?.title?.minSettledTurns) ? value.title.minSettledTurns : 3,
2801
+ },
2802
+ };
2803
+ }
2804
+
2805
+ async function sessionSummaryPreferencesData(tab) {
2806
+ const [storedPreferences, models] = await Promise.all([
2807
+ readSessionSummaryPreferences(),
2808
+ availableSessionSummaryModels(tab),
2809
+ ]);
2810
+ return {
2811
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2812
+ preferences: publicSessionSummaryPreferences(storedPreferences),
2813
+ models,
2814
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [sessionSummaryModelKey(model), supportedSessionSummaryThinkingLevels(model)])),
2815
+ disclosure: {
2816
+ scope: "Active-branch user text, final assistant text, and tool names only. Thinking, images, tool arguments/results, credentials, and prior summary messages are excluded.",
2817
+ cost: "Automatic generation makes one request to the selected model after each eligible settled refresh. There is no provider fallback or automatic provider retry.",
2818
+ persistence: "Preferences and generated output are stored locally. Main-agent context injection is off unless explicitly enabled.",
2819
+ },
2820
+ summary: publicSessionSummaryState(tab),
2821
+ };
2822
+ }
2823
+
2824
+ function requiredSessionSummaryObject(value, label, allowedKeys) {
2825
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw makeHttpError(400, `${label} must be an object`);
2826
+ const unexpected = Object.keys(value).filter((key) => !allowedKeys.includes(key));
2827
+ if (unexpected.length) throw makeHttpError(400, `${label} contains unsupported field${unexpected.length === 1 ? "" : "s"}: ${unexpected.join(", ")}`);
2828
+ return value;
2829
+ }
2830
+
2831
+ function requiredSessionSummaryBoolean(value, label) {
2832
+ if (typeof value !== "boolean") throw makeHttpError(400, `${label} must be true or false`);
2833
+ return value;
2834
+ }
2835
+
2836
+ function requiredSessionSummaryPrompt(value, label) {
2837
+ if (typeof value !== "string") throw makeHttpError(400, `${label} must be a string`);
2838
+ const prompt = value.trim();
2839
+ if (!prompt) throw makeHttpError(400, `${label} must not be empty`);
2840
+ if (prompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS) throw makeHttpError(400, `${label} must not exceed 8 KiB`);
2841
+ return prompt;
2842
+ }
2843
+
2844
+ async function saveSessionSummaryPreferencesData(tab, body = {}) {
2845
+ requiredSessionSummaryObject(body, "request", ["confirmed", "preferences", "tab"]);
2846
+ if (body.confirmed !== true) throw makeHttpError(409, "Session summary setup requires explicit privacy and cost confirmation (confirmed: true).");
2847
+ const submitted = requiredSessionSummaryObject(body.preferences, "preferences", ["enabled", "model", "prompts", "input", "context", "title"]);
2848
+ const submittedModel = requiredSessionSummaryObject(submitted.model, "preferences.model", ["provider", "modelId", "thinkingLevel"]);
2849
+ const submittedPrompts = requiredSessionSummaryObject(submitted.prompts, "preferences.prompts", ["title", "summary"]);
2850
+ const submittedInput = requiredSessionSummaryObject(submitted.input, "preferences.input", ["scope"]);
2851
+ const submittedContext = requiredSessionSummaryObject(submitted.context, "preferences.context", ["injectLatest"]);
2852
+ const submittedTitle = requiredSessionSummaryObject(submitted.title, "preferences.title", ["enabled", "minSettledTurns"]);
2853
+ const provider = String(submittedModel.provider || "").trim();
2854
+ const modelId = String(submittedModel.modelId || "").trim();
2855
+ const thinkingLevel = String(submittedModel.thinkingLevel || "").trim();
2856
+ if (!provider || provider.length > 160 || !modelId || modelId.length > 512) throw makeHttpError(400, "Select an available session summary model");
2857
+ const models = await availableSessionSummaryModels(tab);
2858
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
2859
+ if (!model) throw makeHttpError(400, `Selected session summary model is not currently available: ${provider}/${modelId}`);
2860
+ const supportedLevels = supportedSessionSummaryThinkingLevels(model);
2861
+ if (!supportedLevels.includes(thinkingLevel)) throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${thinkingLevel}`);
2862
+ if (submittedInput.scope !== "text-and-tool-names") throw makeHttpError(400, "input.scope must be text-and-tool-names");
2863
+ const minSettledTurns = Number(submittedTitle.minSettledTurns);
2864
+ if (!Number.isInteger(minSettledTurns) || minSettledTurns < 1 || minSettledTurns > 20) throw makeHttpError(400, "title.minSettledTurns must be an integer from 1 to 20");
2865
+
2866
+ const saved = await writeSessionSummaryPreferences({
2867
+ configured: true,
2868
+ enabled: requiredSessionSummaryBoolean(submitted.enabled, "enabled"),
2869
+ model: { provider, modelId, thinkingLevel },
2870
+ prompts: {
2871
+ title: requiredSessionSummaryPrompt(submittedPrompts.title, "prompts.title"),
2872
+ summary: requiredSessionSummaryPrompt(submittedPrompts.summary, "prompts.summary"),
2873
+ },
2874
+ input: { scope: "text-and-tool-names" },
2875
+ context: { injectLatest: requiredSessionSummaryBoolean(submittedContext.injectLatest, "context.injectLatest") },
2876
+ title: {
2877
+ enabled: requiredSessionSummaryBoolean(submittedTitle.enabled, "title.enabled"),
2878
+ minSettledTurns,
2879
+ },
2880
+ });
2881
+ tab.sessionSummary = {
2882
+ ...(tab.sessionSummary || {}),
2883
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2884
+ status: tab.sessionSummary?.status || "idle",
2885
+ configured: true,
2886
+ enabled: saved.enabled === true,
2887
+ durable: tab.sessionSummary?.durable === true,
2888
+ updatedAt: new Date().toISOString(),
2889
+ };
2890
+ broadcastSessionSummaryState(tab, "setup");
2891
+ return sessionSummaryPreferencesData(tab);
2892
+ }
2893
+
2894
+ async function triggerSessionSummary(tab, { refresh = false } = {}) {
2895
+ const preferences = await readSessionSummaryPreferences();
2896
+ if (!preferences.configured) throw makeHttpError(409, "Session summary setup must be confirmed before generation.");
2897
+ const commands = await safeRpcData(tab, { type: "get_commands" }, STATUS_RPC_TIMEOUT_MS);
2898
+ const available = Array.isArray(commands.data?.commands) && commands.data.commands.some((command) => String(command?.name || "").replace(/:\d+$/, "") === "summary");
2899
+ if (!commands.ok || !available) throw makeHttpError(409, "The /summary extension command is not loaded in this Pi tab. Reload the tab and retry.");
2900
+ tab.sessionSummary = {
2901
+ ...(tab.sessionSummary || {}),
2902
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2903
+ status: "generating",
2904
+ configured: true,
2905
+ message: "",
2906
+ updatedAt: new Date().toISOString(),
2907
+ };
2908
+ broadcastSessionSummaryState(tab, "generating");
2909
+ try {
2910
+ const response = await tab.rpc.send(
2911
+ { type: "prompt", message: refresh ? "/summary refresh" : "/summary" },
2912
+ SESSION_SUMMARY_GENERATE_TIMEOUT_MS,
2913
+ );
2914
+ if (response.success === false) throw makeHttpError(400, response.error || "Session summary generation failed");
2915
+ return { requested: true, refresh: refresh === true, summary: publicSessionSummaryState(tab), tab: tabMeta(tab) };
2916
+ } catch (error) {
2917
+ const message = (sanitizeError(error) || "Session summary generation failed")
2918
+ .replace(/[\r\n]+/g, " ")
2919
+ .slice(0, SESSION_SUMMARY_FAILURE_MAX_CHARS)
2920
+ .trim();
2921
+ tab.sessionSummary = {
2922
+ ...(tab.sessionSummary || {}),
2923
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2924
+ status: "failure",
2925
+ message: message || "Session summary generation failed",
2926
+ updatedAt: new Date().toISOString(),
2927
+ };
2928
+ broadcastSessionSummaryState(tab, "failure");
2929
+ throw error;
2930
+ }
2931
+ }
2932
+
2560
2933
  function gitWorkflowGenerationPrompt(kind, preferences) {
2561
2934
  switch (kind) {
2562
2935
  case "commit":
@@ -8469,7 +8842,7 @@ function parseNodeModulesPackageRef(manifestEntry) {
8469
8842
 
8470
8843
  async function resolveStartedWebuiManifestResource(manifestEntry) {
8471
8844
  const nodeModulesRef = parseNodeModulesPackageRef(manifestEntry);
8472
- if (nodeModulesRef && WEBUI_CONTROLLED_PACKAGES.has(nodeModulesRef.packageName)) {
8845
+ if (nodeModulesRef && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(nodeModulesRef.packageName)) {
8473
8846
  const installedCandidate = await resolveInstalledPackageSubpath(nodeModulesRef.packageName, nodeModulesRef.subpath);
8474
8847
  if (installedCandidate) return installedCandidate;
8475
8848
  }
@@ -8518,10 +8891,15 @@ async function resolvedNormalPiResourcesForTab(cwd) {
8518
8891
  async function normalPiResourcePathsForTab(resolved, resourceType) {
8519
8892
  if (piArgsDisableResourceDiscovery(resourceType)) return [];
8520
8893
  const resourcePaths = [];
8894
+ const auditExcludedPackages = optionalFeatureAuditCoordinator?.excludedPackageNames?.() || new Set();
8895
+ const coreOnly = optionalFeatureAuditCoordinator?.current?.().phase === "checking" || optionalFeatureAuditCoordinator?.current?.().phase === "degraded";
8521
8896
  for (const resource of resolved[resourceType] || []) {
8522
8897
  if (!resource.enabled) continue;
8523
8898
  const packageName = await packageNameForResourcePath(resource.path);
8524
- if (packageName && WEBUI_CONTROLLED_PACKAGES.has(packageName)) continue;
8899
+ if (packageName && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(packageName)) continue;
8900
+ if (packageName && auditExcludedPackages.has(packageName)) {
8901
+ if (coreOnly || resource.metadata?.origin !== "package") continue;
8902
+ }
8525
8903
  resourcePaths.push(resource.path);
8526
8904
  }
8527
8905
  return resourcePaths;
@@ -8546,6 +8924,11 @@ async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
8546
8924
  await appendCuratedResourceArgs(args, normalResources, "prompts", "--prompt-template");
8547
8925
  await appendCuratedResourceArgs(args, normalResources, "themes", "--theme");
8548
8926
 
8927
+ // The package manifest is resolved above, but keep session-summary explicit:
8928
+ // curated child discovery intentionally excludes package-owned resources in
8929
+ // some installations. Avoid a duplicate when the manifest path was retained.
8930
+ if (!args.includes(sessionSummaryExtensionPath)) args.push("--extension", sessionSummaryExtensionPath);
8931
+
8549
8932
  // Load a browser-safe RPC helper into every Web UI tab. It exposes hidden
8550
8933
  // extension commands for Web UI-native /tools and /skills selectors without
8551
8934
  // depending on TUI-only extension UIs.
@@ -8935,6 +9318,133 @@ function clearExtensionWidgets(tab) {
8935
9318
  tab?.extensionWidgets?.clear();
8936
9319
  }
8937
9320
 
9321
+ function normalizedSessionSummaryTitle(value) {
9322
+ if (typeof value !== "string" || value.length > SESSION_SUMMARY_TITLE_MAX_CHARS) return "";
9323
+ const title = value.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
9324
+ return title.length <= SESSION_SUMMARY_TITLE_MAX_CHARS ? title : "";
9325
+ }
9326
+
9327
+ function normalizedSessionSummaryRpcDetails(value) {
9328
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.version !== SESSION_SUMMARY_PROTOCOL_VERSION) return null;
9329
+ const kind = String(value.kind || "");
9330
+ if (!SESSION_SUMMARY_KINDS.has(kind)) return null;
9331
+ const details = { version: SESSION_SUMMARY_PROTOCOL_VERSION, kind };
9332
+ if (value.sessionId !== undefined) {
9333
+ if (typeof value.sessionId !== "string" || value.sessionId.length > 128) return null;
9334
+ details.sessionId = value.sessionId;
9335
+ }
9336
+ if (value.title !== undefined) {
9337
+ const title = normalizedSessionSummaryTitle(value.title);
9338
+ if (!title) return null;
9339
+ details.title = title;
9340
+ }
9341
+ if (value.summaryMarkdown !== undefined) {
9342
+ if (typeof value.summaryMarkdown !== "string" || !value.summaryMarkdown.trim() || value.summaryMarkdown.length > SESSION_SUMMARY_MARKDOWN_MAX_CHARS) return null;
9343
+ details.summaryMarkdown = value.summaryMarkdown.trim();
9344
+ }
9345
+ if (value.message !== undefined) {
9346
+ if (typeof value.message !== "string" || value.message.length > SESSION_SUMMARY_FAILURE_MAX_CHARS) return null;
9347
+ details.message = value.message.replace(/[\r\n]+/g, " ").trim();
9348
+ }
9349
+ for (const key of ["configured", "enabled", "durable"]) {
9350
+ if (value[key] !== undefined) {
9351
+ if (typeof value[key] !== "boolean") return null;
9352
+ details[key] = value[key];
9353
+ }
9354
+ }
9355
+ if ((kind === "success" && !details.summaryMarkdown) || (kind === "failure" && !details.message) || (kind === "title" && !details.title)) return null;
9356
+ return details;
9357
+ }
9358
+
9359
+ function publicSessionSummaryState(tab) {
9360
+ const value = tab?.sessionSummary;
9361
+ if (!value) return null;
9362
+ return {
9363
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9364
+ status: value.status || "idle",
9365
+ configured: value.configured === true,
9366
+ enabled: value.enabled === true,
9367
+ durable: value.durable === true,
9368
+ ...(value.sessionId ? { sessionId: value.sessionId } : {}),
9369
+ ...(value.title ? { title: value.title } : {}),
9370
+ ...(value.summaryMarkdown ? { summaryMarkdown: value.summaryMarkdown } : {}),
9371
+ ...(value.message ? { message: value.message } : {}),
9372
+ updatedAt: value.updatedAt || new Date(0).toISOString(),
9373
+ };
9374
+ }
9375
+
9376
+ function broadcastSessionSummaryState(tab, kind) {
9377
+ broadcastTabEvent(tab, {
9378
+ type: "webui_session_summary",
9379
+ kind,
9380
+ tabId: tab.id,
9381
+ tabTitle: tab.title,
9382
+ summary: publicSessionSummaryState(tab),
9383
+ });
9384
+ }
9385
+
9386
+ function applySessionSummaryRpcDetails(tab, details) {
9387
+ const previous = tab.sessionSummary?.sessionId && details.sessionId && tab.sessionSummary.sessionId !== details.sessionId
9388
+ ? null
9389
+ : tab.sessionSummary;
9390
+ const next = {
9391
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9392
+ status: previous?.status || "idle",
9393
+ configured: previous?.configured === true,
9394
+ enabled: previous?.enabled === true,
9395
+ durable: previous?.durable === true,
9396
+ sessionId: details.sessionId || previous?.sessionId || "",
9397
+ title: previous?.title || "",
9398
+ summaryMarkdown: previous?.summaryMarkdown || "",
9399
+ message: "",
9400
+ updatedAt: new Date().toISOString(),
9401
+ };
9402
+ if (details.configured !== undefined) next.configured = details.configured;
9403
+ if (details.enabled !== undefined) next.enabled = details.enabled;
9404
+ if (details.durable !== undefined) next.durable = details.durable;
9405
+ if (details.kind === "state") {
9406
+ next.status = details.summaryMarkdown ? "success" : "idle";
9407
+ next.title = details.title || "";
9408
+ next.summaryMarkdown = details.summaryMarkdown || "";
9409
+ } else if (details.kind === "setup") {
9410
+ next.status = "idle";
9411
+ } else if (details.kind === "generating") {
9412
+ next.status = "generating";
9413
+ } else if (details.kind === "success") {
9414
+ next.status = "success";
9415
+ next.title = details.title || next.title;
9416
+ next.summaryMarkdown = details.summaryMarkdown;
9417
+ } else if (details.kind === "failure") {
9418
+ next.status = "failure";
9419
+ next.message = details.message;
9420
+ } else if (details.kind === "title") {
9421
+ next.title = details.title;
9422
+ if (tab.titleSource === "default" || tab.titleSource === "auto") {
9423
+ renameTab(tab, details.title, { source: "auto", maxLength: SESSION_SUMMARY_TITLE_MAX_CHARS });
9424
+ }
9425
+ }
9426
+ tab.sessionSummary = next;
9427
+ broadcastSessionSummaryState(tab, details.kind);
9428
+ }
9429
+
9430
+ function consumeSessionSummaryRpcEvent(tab, event) {
9431
+ const message = event?.message;
9432
+ if ((event?.type !== "message_start" && event?.type !== "message_end") || message?.role !== "custom") return false;
9433
+ if (message.customType === SESSION_SUMMARY_DISPLAY_TYPE) return true;
9434
+ if (message.customType !== SESSION_SUMMARY_RPC_TYPE) return false;
9435
+ if (event.type === "message_end") {
9436
+ const details = normalizedSessionSummaryRpcDetails(message.details);
9437
+ if (details) applySessionSummaryRpcDetails(tab, details);
9438
+ }
9439
+ return true;
9440
+ }
9441
+
9442
+ function filterSessionSummaryTranscriptMessages(messages) {
9443
+ return (Array.isArray(messages) ? messages : []).filter((message) => !(
9444
+ message?.role === "custom" && (message.customType === SESSION_SUMMARY_RPC_TYPE || message.customType === SESSION_SUMMARY_DISPLAY_TYPE)
9445
+ ));
9446
+ }
9447
+
8938
9448
  function clearWebuiSubagents(tab) {
8939
9449
  if (tab) tab.webuiSubagents = null;
8940
9450
  }
@@ -9806,7 +10316,7 @@ function attachRpcToTab(tab, rpc) {
9806
10316
  tab.rpc = rpc;
9807
10317
  tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
9808
10318
  const event = tab.thinkingStreamRecovery.ingest(rawEvent);
9809
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
10319
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event) || consumeSessionSummaryRpcEvent(tab, event)) return;
9810
10320
  updateTabActivityFromEvent(tab, event);
9811
10321
  let scopedEvent = eventForTabClients(tab, event);
9812
10322
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
@@ -9852,6 +10362,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9852
10362
  pendingExtensionUiRequests: new Map(),
9853
10363
  extensionStatuses: new Map(),
9854
10364
  extensionWidgets: new Map(),
10365
+ sessionSummary: null,
9855
10366
  webuiSubagents: null,
9856
10367
  subagentDisplayTitle: undefined,
9857
10368
  subagentDisplayTitlePromise: undefined,
@@ -10010,6 +10521,7 @@ function tabMeta(tab) {
10010
10521
  activity: tabActivitySnapshot(tab),
10011
10522
  appRunner: publicAppRunnerState(tab.appRunner),
10012
10523
  conversationMode: naturalConversationModeSnapshot(tab),
10524
+ sessionSummary: publicSessionSummaryState(tab),
10013
10525
  };
10014
10526
  }
10015
10527
 
@@ -10622,6 +11134,7 @@ function packageNodeModulesPath(nodeModulesRoot, packageName) {
10622
11134
 
10623
11135
  function isWebuiOrPiPackageName(packageName) {
10624
11136
  const name = String(packageName || "").trim();
11137
+ if (OPTIONAL_FEATURE_PACKAGE_NAMES.has(name)) return false;
10625
11138
  return UPDATE_PACKAGE_NAMES.includes(name)
10626
11139
  || /^@firstpick\/pi(?:-|$)/.test(name)
10627
11140
  || /^@earendil-works\/pi(?:-|$)/.test(name)
@@ -10938,8 +11451,18 @@ function componentUpdateSuccessMessage(target) {
10938
11451
  return "Web UI update completed. Restart the Web UI to use the update.";
10939
11452
  }
10940
11453
 
11454
+ async function persistOptionalFeaturePendingUpgrade() {
11455
+ optionalFeatureAuditCoordinator.assertIdle();
11456
+ const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-update" });
11457
+ const featureIds = snapshot.features
11458
+ .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11459
+ .map(({ featureId }) => featureId);
11460
+ await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11461
+ }
11462
+
10941
11463
  async function runComponentUpdate(target) {
10942
11464
  try {
11465
+ if (target === "webui") await persistOptionalFeaturePendingUpgrade();
10943
11466
  const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
10944
11467
  if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
10945
11468
  const command = updateTasks.map(updateTaskDisplay).join(" && ");
@@ -10973,6 +11496,7 @@ async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
10973
11496
  piUpdateInProgress = true;
10974
11497
  let restartPrepared = false;
10975
11498
  try {
11499
+ if (all) await persistOptionalFeaturePendingUpgrade();
10976
11500
  const restorableTabs = await restorableTabsForRestart();
10977
11501
  const updateTasks = await resolveUpdateTasks({ all });
10978
11502
  if (!updateTasks.length) throw makeHttpError(500, "No Pi update command could be resolved.");
@@ -11278,7 +11802,10 @@ async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
11278
11802
  try {
11279
11803
  const response = rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11280
11804
  if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
11281
- response.data = { ...response.data, messages: tab.thinkingStreamRecovery.applyToMessages(response.data.messages) };
11805
+ response.data = {
11806
+ ...response.data,
11807
+ messages: filterSessionSummaryTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages)),
11808
+ };
11282
11809
  }
11283
11810
  return response;
11284
11811
  } catch (error) {
@@ -13601,12 +14128,16 @@ const serverStartedAt = new Date().toISOString();
13601
14128
  const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
13602
14129
  let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
13603
14130
  let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
13604
- rpcSupervisor = await initializeRpcSupervisor();
13605
- rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
13606
- installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
13607
- const initialTabs = await createInitialTabs();
13608
- await finishRpcSupervisorStartup(initialTabs);
13609
- const initialTab = initialTabs[0];
14131
+ optionalFeatureMigrationStore = new OptionalFeatureMigrationStore({
14132
+ filePath: process.env.PI_WEBUI_OPTIONAL_FEATURE_MIGRATION_FILE || path.join(agentDir, "webui", "optional-feature-migration.json"),
14133
+ });
14134
+ optionalFeatureAuditCoordinator = new OptionalFeatureAuditCoordinator({
14135
+ catalog: OPTIONAL_FEATURE_CATALOG,
14136
+ collectStatuses: async () => (await optionalFeaturePackageStatuses(options.cwd)).features,
14137
+ store: optionalFeatureMigrationStore,
14138
+ webuiVersion: packageJson.version,
14139
+ onEvent: (event) => broadcastServerEvent(event),
14140
+ });
13610
14141
  let currentHost = options.host;
13611
14142
  let networkRebindInProgress = false;
13612
14143
  let networkRebindTargetHost = null;
@@ -14250,6 +14781,30 @@ const server = createServer(async (req, res) => {
14250
14781
  return;
14251
14782
  }
14252
14783
 
14784
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "GET") {
14785
+ const tab = getRequestedTab(req, url);
14786
+ sendJson(res, 200, { ok: true, data: await sessionSummaryPreferencesData(tab) }, { "cache-control": "private, no-store" });
14787
+ return;
14788
+ }
14789
+
14790
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "PUT") {
14791
+ requireSessionSummaryJsonRequest(req);
14792
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14793
+ const tab = getRequestedTab(req, url, body);
14794
+ sendJson(res, 200, { ok: true, data: await saveSessionSummaryPreferencesData(tab, body) }, { "cache-control": "private, no-store" });
14795
+ return;
14796
+ }
14797
+
14798
+ if (url.pathname === "/api/session-summary/generate" && req.method === "POST") {
14799
+ requireSessionSummaryJsonRequest(req);
14800
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14801
+ requiredSessionSummaryObject(body, "request", ["refresh", "tab"]);
14802
+ if (body.refresh !== undefined && typeof body.refresh !== "boolean") throw makeHttpError(400, "refresh must be true or false");
14803
+ const tab = getRequestedTab(req, url, body);
14804
+ sendJson(res, 200, { ok: true, data: await triggerSessionSummary(tab, { refresh: body.refresh === true }) }, { "cache-control": "private, no-store" });
14805
+ return;
14806
+ }
14807
+
14253
14808
  if (url.pathname === "/api/workflow-policy" && req.method === "GET") {
14254
14809
  requireLocalhost(req, "Workflow policy setup is only allowed from localhost.");
14255
14810
  try {
@@ -14439,6 +14994,7 @@ const server = createServer(async (req, res) => {
14439
14994
  }
14440
14995
 
14441
14996
  if (url.pathname === "/api/tabs" && req.method === "POST") {
14997
+ if (!optionalFeatureStartupReady) throw makeHttpError(503, "Optional feature startup audit is still checking; retry after /api/health is ready");
14442
14998
  const body = await readJsonBody(req);
14443
14999
  const tab = await createTab({ title: body.title, cwd: body.cwd });
14444
15000
  sendJson(res, 201, { ok: true, data: { tab: tabMeta(tab), tabs: listTabs() } });
@@ -14533,6 +15089,16 @@ const server = createServer(async (req, res) => {
14533
15089
  }
14534
15090
  replayExtensionStatuses(tab, client);
14535
15091
  replayExtensionWidgets(tab, client);
15092
+ if (tab.sessionSummary) {
15093
+ sendSseToClient(client, {
15094
+ type: "webui_session_summary",
15095
+ kind: "replay",
15096
+ tabId: tab.id,
15097
+ tabTitle: tab.title,
15098
+ summary: publicSessionSummaryState(tab),
15099
+ replayed: true,
15100
+ });
15101
+ }
14536
15102
  replayPendingExtensionUiRequests(tab, client);
14537
15103
  const keepAlive = setInterval(() => writeSseFrame(client, ": keepalive\n\n"), 15000);
14538
15104
  req.on("close", () => {
@@ -14544,8 +15110,9 @@ const server = createServer(async (req, res) => {
14544
15110
 
14545
15111
  if (url.pathname === "/api/health" && req.method === "GET") {
14546
15112
  const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
14547
- sendJson(res, 200, {
14548
- ok: true,
15113
+ sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
15114
+ ok: optionalFeatureStartupReady,
15115
+ startupPhase: optionalFeatureAuditCoordinator.current().phase,
14549
15116
  webuiVersion: status.webuiVersion,
14550
15117
  piVersion: status.piVersion,
14551
15118
  webuiDev: status.webuiDev,
@@ -15087,7 +15654,7 @@ const server = createServer(async (req, res) => {
15087
15654
  }
15088
15655
 
15089
15656
  if (url.pathname === "/api/optional-features" && req.method === "GET") {
15090
- sendJson(res, 200, { ok: true, data: await optionalFeaturePackageStatuses() });
15657
+ sendJson(res, 200, { ok: true, data: optionalFeatureAuditCoordinator.current() });
15091
15658
  return;
15092
15659
  }
15093
15660
 
@@ -15096,7 +15663,48 @@ const server = createServer(async (req, res) => {
15096
15663
  const body = await readJsonBody(req);
15097
15664
  const tab = getRequestedTab(req, url, body);
15098
15665
  ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15099
- const data = await installOptionalFeaturePackage(String(body.featureId || ""));
15666
+ const revision = optionalFeatureAuditCoordinator.current().revision;
15667
+ const data = await optionalFeatureAuditCoordinator.runMutation(revision, async () => {
15668
+ try {
15669
+ return await installOptionalFeaturePackage(String(body.featureId || ""), tab.cwd);
15670
+ } finally {
15671
+ await optionalFeatureAuditCoordinator.recheck({ reason: "post-install" });
15672
+ }
15673
+ });
15674
+ sendJson(res, 200, { ok: true, data });
15675
+ return;
15676
+ }
15677
+
15678
+ if (url.pathname === "/api/optional-feature-install-batch" && req.method === "POST") {
15679
+ requireLocalhost(req, "Installing optional Web UI features is only allowed from localhost");
15680
+ const body = await readJsonBody(req);
15681
+ const tab = getRequestedTab(req, url, body);
15682
+ ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15683
+ const data = await runOptionalFeatureBatchMutation({
15684
+ revision: body.revision,
15685
+ featureIds: body.featureIds,
15686
+ cwd: tab.cwd,
15687
+ migration: body.migration === true,
15688
+ tab,
15689
+ install: () => installOptionalFeaturePackages(body.featureIds, tab.cwd),
15690
+ });
15691
+ sendJson(res, 200, { ok: true, data });
15692
+ return;
15693
+ }
15694
+
15695
+ if (url.pathname === "/api/optional-feature-migration/recheck" && req.method === "POST") {
15696
+ requireLocalhostRoute(req, url.pathname);
15697
+ await readJsonBody(req);
15698
+ optionalFeatureAuditCoordinator.assertIdle();
15699
+ const data = await optionalFeatureAuditCoordinator.recheck({ reason: "manual" });
15700
+ sendJson(res, 200, { ok: true, data });
15701
+ return;
15702
+ }
15703
+
15704
+ if (url.pathname === "/api/optional-feature-migration/dismiss" && req.method === "POST") {
15705
+ requireLocalhostRoute(req, url.pathname);
15706
+ const body = await readJsonBody(req);
15707
+ const data = await optionalFeatureAuditCoordinator.dismiss(body.revision);
15100
15708
  sendJson(res, 200, { ok: true, data });
15101
15709
  return;
15102
15710
  }
@@ -15584,18 +16192,49 @@ function sweepWebuiTempArtifacts() {
15584
16192
  sweepWebuiTempArtifacts();
15585
16193
  setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
15586
16194
 
15587
- server.listen(options.port, currentHost, () => {
15588
- const urlHost = formatUrlHost(currentHost);
15589
- console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
15590
- console.log(`Working directory: ${options.cwd}`);
15591
- if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
15592
- else console.log("Pi RPC: waiting for CWD selection in the Web UI");
15593
- if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
15594
- if (!isLocalHost(currentHost)) {
15595
- console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
15596
- }
16195
+ await new Promise((resolve, reject) => {
16196
+ const onError = (error) => {
16197
+ server.off("listening", onListening);
16198
+ reject(error);
16199
+ };
16200
+ const onListening = () => {
16201
+ server.off("error", onError);
16202
+ resolve();
16203
+ };
16204
+ server.once("error", onError);
16205
+ server.once("listening", onListening);
16206
+ server.listen(options.port, currentHost);
15597
16207
  });
15598
16208
 
16209
+ const urlHost = formatUrlHost(currentHost);
16210
+ console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
16211
+ console.log(`Working directory: ${options.cwd}`);
16212
+ if (!isLocalHost(currentHost)) {
16213
+ console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
16214
+ }
16215
+
16216
+ const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
16217
+ if (options.migrationDryRun) {
16218
+ console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);
16219
+ } else if (options.migrateOptionalFeatures) {
16220
+ const featureIds = startupAudit.features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId);
16221
+ if (featureIds.length) {
16222
+ const result = await runOptionalFeatureBatchMutation({ revision: startupAudit.revision, featureIds, cwd: options.cwd, migration: true });
16223
+ console.log(`Optional feature migration: ${result.succeeded} succeeded, ${result.failed} failed.`);
16224
+ }
16225
+ }
16226
+
16227
+ rpcSupervisor = await initializeRpcSupervisor();
16228
+ rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
16229
+ installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
16230
+ const initialTabs = await createInitialTabs();
16231
+ await finishRpcSupervisorStartup(initialTabs);
16232
+ const initialTab = initialTabs[0] || null;
16233
+ optionalFeatureStartupReady = true;
16234
+ if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
16235
+ else console.log("Pi RPC: waiting for CWD selection in the Web UI");
16236
+ if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
16237
+
15599
16238
  let shutdownInProgress = false;
15600
16239
 
15601
16240
  async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {}) {