@firstpick/pi-package-webui 0.8.5 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -584
- package/bin/pi-webui-launcher.mjs +22 -0
- package/bin/pi-webui-update-supervisor.mjs +86 -0
- package/bin/pi-webui.mjs +933 -554
- package/index.ts +16 -6
- package/lib/component-update-state.mjs +21 -0
- package/lib/git-workflow-preferences.mjs +20 -2
- package/lib/optional-feature-catalog.mjs +1 -0
- package/lib/sampling-parameter-capabilities.mjs +160 -0
- package/lib/session-summary-core.mjs +4 -3
- package/lib/session-summary-preferences.mjs +16 -1
- package/lib/subagent-launch-slots.mjs +14 -2
- package/lib/trust-boundaries.mjs +16 -0
- package/lib/update/executor.mjs +99 -0
- package/lib/update/journal.mjs +175 -0
- package/lib/update/owners.mjs +70 -0
- package/lib/update/plan.mjs +134 -0
- package/lib/update/resolver.mjs +168 -0
- package/lib/update/supervisor.mjs +238 -0
- package/lib/update/verify.mjs +52 -0
- package/lib/update-commands.mjs +25 -13
- package/lib/webui-workspaces.mjs +17 -1
- package/lib/workspace-session-summaries.mjs +400 -0
- package/package.json +4 -4
- package/public/app.js +2487 -349
- package/public/index.html +200 -51
- package/public/middle-button-drag-scroll.mjs +154 -0
- package/public/sampling-parameter-controls.mjs +361 -0
- package/public/service-worker.js +5 -1
- package/public/stream-output-controller.mjs +327 -0
- package/public/styles.css +666 -71
- package/public/theme-contract.mjs +244 -0
- package/session-summary.ts +164 -4
- package/tests/aur-review-widget-static.test.mjs +2 -1
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
- package/tests/browser/interaction-continuity.spec.mjs +2 -2
- package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
- package/tests/browser/sampling-tooltip.spec.mjs +228 -0
- package/tests/browser/session-summary.spec.mjs +131 -3
- package/tests/browser/stream-output-isolation.spec.mjs +510 -0
- package/tests/browser/update-reconnect.spec.mjs +92 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
- package/tests/common-options-submenus-markup-static.test.mjs +152 -0
- package/tests/component-update-api-static.test.mjs +22 -61
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +13 -237
- package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
- package/tests/fast-mode-client-static.test.mjs +3 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
- package/tests/fixtures/fake-pi.mjs +269 -2
- package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
- package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
- package/tests/git-footer-context-menu-static.test.mjs +58 -0
- package/tests/git-workflow-preferences.test.mjs +7 -1
- package/tests/guided-git-aur-review.test.mjs +4 -3
- package/tests/http-endpoints-harness.test.mjs +274 -23
- package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
- package/tests/middle-button-drag-scroll.test.mjs +170 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +5 -6
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +85 -50
- package/tests/native-parity.test.mjs +1 -1
- package/tests/open-issue-wizard-static.test.mjs +2 -3
- package/tests/optional-feature-migration-frontend.test.mjs +9 -5
- package/tests/persistent-ui-layout-static.test.mjs +13 -2
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +43 -0
- package/tests/rpc-supervisor-host.test.mjs +11 -2
- package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
- package/tests/safety-guard-auto-review-static.test.mjs +34 -0
- package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
- package/tests/sampling-parameter-capabilities.test.mjs +167 -0
- package/tests/sampling-parameter-controls.test.mjs +241 -0
- package/tests/session-sampling-helper.test.mjs +228 -0
- package/tests/session-sampling-http.test.mjs +168 -0
- package/tests/session-sampling-ui-static.test.mjs +370 -0
- package/tests/session-summary-core.test.mjs +205 -10
- package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
- package/tests/side-panel-section-reorder-static.test.mjs +3 -3
- package/tests/staged-content-hash-contract.test.mjs +52 -11
- package/tests/stream-lifecycle-core.test.mjs +134 -0
- package/tests/stream-output-controller.test.mjs +252 -0
- package/tests/stream-output-isolation-static.test.mjs +89 -0
- package/tests/streaming-ui-coupling.test.mjs +50 -0
- package/tests/subagent-gate-visibility.test.mjs +1 -1
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagent-launch-slots.test.mjs +18 -1
- package/tests/theme-contract.test.mjs +104 -0
- package/tests/theme-customizer-static.test.mjs +82 -0
- package/tests/theme-scheme-mode.test.mjs +15 -0
- package/tests/ui-layout-settings.test.mjs +18 -1
- package/tests/update-api-harness.test.mjs +111 -0
- package/tests/update-commands.test.mjs +15 -45
- package/tests/update-executor-process-tree-harness.test.mjs +22 -0
- package/tests/update-journal-harness.test.mjs +59 -0
- package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
- package/tests/update-owners.test.mjs +27 -0
- package/tests/update-plan.test.mjs +58 -0
- package/tests/update-resolver.test.mjs +56 -0
- package/tests/update-supervisor-harness.test.mjs +57 -0
- package/tests/update-tab-restore-harness.test.mjs +24 -0
- package/tests/update-verify.test.mjs +31 -0
- package/tests/workspace-files-live-updates-static.test.mjs +13 -4
- package/tests/workspace-session-summaries.test.mjs +288 -0
- package/webui-rpc-helper.mjs +119 -0
package/bin/pi-webui.mjs
CHANGED
|
@@ -12,6 +12,14 @@ 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
14
|
import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import {
|
|
16
|
+
ThemeContractError,
|
|
17
|
+
canonicalizeTheme,
|
|
18
|
+
normalizeThemeFileName,
|
|
19
|
+
serializeTheme,
|
|
20
|
+
themeNameFromFileName,
|
|
21
|
+
validateTheme,
|
|
22
|
+
} from "../public/theme-contract.mjs";
|
|
15
23
|
import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
|
|
16
24
|
import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
|
|
17
25
|
import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
|
|
@@ -44,14 +52,19 @@ import {
|
|
|
44
52
|
findWindowsReservedGitPath,
|
|
45
53
|
windowsReservedGitPathFailure,
|
|
46
54
|
} from "../lib/git-command-errors.mjs";
|
|
47
|
-
import {
|
|
48
|
-
import {
|
|
55
|
+
import { ComponentUpdateState, sanitizeComponentUpdateError, validateComponentUpdateRequest, validateUpdateApplyRequest, validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
|
|
56
|
+
import { resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity } from "../lib/update/resolver.mjs";
|
|
57
|
+
import { createUpdatePlan, assertPlanIdentity, assertUpdatePlanDigest } from "../lib/update/plan.mjs";
|
|
58
|
+
import { executeCommand, executePlanTargets } from "../lib/update/executor.mjs";
|
|
59
|
+
import { verifyTargetResult } from "../lib/update/verify.mjs";
|
|
60
|
+
import { acquireInstallLock, createUpdateJournal, readUpdateJournal, reconcileInterruptedUpdates, releaseInstallLock, transferInstallLock, transitionUpdateJournal } from "../lib/update/journal.mjs";
|
|
61
|
+
import { collectManagedRuntimes, createRestoreFile, listenWithRetry, managedRuntimePaths, probeCandidateRuntime, readRestoreFileOnce, readRuntimePointer, rollbackRuntimePointer, sweepRestoreFiles } from "../lib/update/supervisor.mjs";
|
|
49
62
|
import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
|
|
50
63
|
import {
|
|
51
64
|
OptionalFeatureAuditCoordinator,
|
|
52
65
|
OptionalFeatureMigrationStore,
|
|
53
66
|
} from "../lib/optional-feature-migration.mjs";
|
|
54
|
-
import {
|
|
67
|
+
import { resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
|
|
55
68
|
import {
|
|
56
69
|
GIT_WORKFLOW_DEFAULT_VARIANTS,
|
|
57
70
|
GIT_WORKFLOW_DELIVERY_MODES,
|
|
@@ -105,6 +118,7 @@ import {
|
|
|
105
118
|
evaluateDispatchTrustGuards,
|
|
106
119
|
guardsForNativeCommand,
|
|
107
120
|
isLocalRequest,
|
|
121
|
+
projectTrustDecision,
|
|
108
122
|
remoteShellTrustWarning,
|
|
109
123
|
requireLocalhost,
|
|
110
124
|
requireLocalhostRoute,
|
|
@@ -166,6 +180,7 @@ const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(p
|
|
|
166
180
|
const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
|
|
167
181
|
const WEBUI_HELPER_COMMAND = "webui-helper";
|
|
168
182
|
const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
|
|
183
|
+
const SAMPLING_PARAMS_HTTP_MAX_BYTES = 20 * 1024;
|
|
169
184
|
const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
|
|
170
185
|
const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
|
|
171
186
|
const WEBUI_SUBAGENT_RUN_LIMIT = 128;
|
|
@@ -199,6 +214,7 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
|
|
|
199
214
|
const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
|
|
200
215
|
const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
|
|
201
216
|
const BODY_LIMIT_BYTES = 1024 * 1024;
|
|
217
|
+
const CUSTOM_THEME_BODY_LIMIT_BYTES = 256 * 1024;
|
|
202
218
|
const SESSION_SUMMARY_REQUEST_MAX_BYTES = 32 * 1024;
|
|
203
219
|
const SESSION_SUMMARY_RPC_TYPE = "firstpick:session-summary-rpc";
|
|
204
220
|
const SESSION_SUMMARY_DISPLAY_TYPE = "firstpick:session-summary-display";
|
|
@@ -271,7 +287,9 @@ const PATH_SUGGESTION_QUERY_LIMIT = 512;
|
|
|
271
287
|
const PATH_SUGGESTION_SCAN_LIMIT = 5000;
|
|
272
288
|
const PATH_SUGGESTION_MAX_OUTPUT_LENGTH = 300000;
|
|
273
289
|
const PATH_SUGGESTION_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
|
|
274
|
-
const RESTORE_TAB_LIMIT =
|
|
290
|
+
const RESTORE_TAB_LIMIT = 256;
|
|
291
|
+
const UPDATE_HEALTH_GATE_MS = Math.max(90_000, Number.parseInt(process.env.PI_WEBUI_UPDATE_HEALTH_GATE_MS || "90000", 10) || 90_000);
|
|
292
|
+
const bootIdentity = randomUUID();
|
|
275
293
|
const SESSION_SELECTOR_LIMIT = 200;
|
|
276
294
|
const TREE_SELECTOR_TEXT_LIMIT = 260;
|
|
277
295
|
const NETWORK_REBIND_DELAY_MS = 100;
|
|
@@ -694,12 +712,12 @@ async function fetchJsonWithTimeout(url, { timeoutMs = UPDATE_STATUS_TIMEOUT_MS,
|
|
|
694
712
|
return response.json();
|
|
695
713
|
}
|
|
696
714
|
|
|
697
|
-
function
|
|
698
|
-
const
|
|
699
|
-
if (!parsePackageVersion(
|
|
700
|
-
const tagName = `v${
|
|
715
|
+
function piRelease(version = piPackageJson.version) {
|
|
716
|
+
const cleanVersion = String(version || "").trim().replace(/^v/i, "");
|
|
717
|
+
if (!parsePackageVersion(cleanVersion)) throw makeHttpError(503, "The Pi release version could not be determined");
|
|
718
|
+
const tagName = `v${cleanVersion}`;
|
|
701
719
|
return {
|
|
702
|
-
version,
|
|
720
|
+
version: cleanVersion,
|
|
703
721
|
tagName,
|
|
704
722
|
apiUrl: `${PI_RELEASES_API_BASE_URL}/${encodeURIComponent(tagName)}`,
|
|
705
723
|
pageUrl: `${PI_RELEASES_PAGE_BASE_URL}/${encodeURIComponent(tagName)}`,
|
|
@@ -708,8 +726,14 @@ function installedPiRelease() {
|
|
|
708
726
|
|
|
709
727
|
let piReleaseNotesCache = null;
|
|
710
728
|
|
|
711
|
-
async function
|
|
712
|
-
const
|
|
729
|
+
async function piReleaseNotes() {
|
|
730
|
+
const cachedUpdateStatus = updateStatusCache && Date.now() - updateStatusCacheAt < UPDATE_STATUS_CACHE_MS
|
|
731
|
+
? updateStatusCache.pi
|
|
732
|
+
: null;
|
|
733
|
+
const piStatus = cachedUpdateStatus || await checkLatestPiReleaseStatus();
|
|
734
|
+
const currentVersion = String(piStatus?.currentVersion || piPackageJson.version || "").trim().replace(/^v/i, "");
|
|
735
|
+
const latestVersion = String(piStatus?.latestVersion || "").trim().replace(/^v/i, "");
|
|
736
|
+
const release = piRelease(piStatus?.updateAvailable && parsePackageVersion(latestVersion) ? latestVersion : currentVersion);
|
|
713
737
|
if (piReleaseNotesCache?.tagName === release.tagName) return piReleaseNotesCache;
|
|
714
738
|
if (process.env.PI_OFFLINE) throw makeHttpError(503, "Pi release notes are unavailable while PI_OFFLINE is set");
|
|
715
739
|
|
|
@@ -1114,6 +1138,9 @@ function makeHttpError(statusCode, message) {
|
|
|
1114
1138
|
function sendError(res, statusCode, error) {
|
|
1115
1139
|
const message = statusCode >= 500 ? sanitizeError(error) : formatCliError(error);
|
|
1116
1140
|
const payload = { ok: false, error: message };
|
|
1141
|
+
const isThemeError = typeof error?.code === "string" && error.code.startsWith("THEME_");
|
|
1142
|
+
if (isThemeError) payload.code = error.code;
|
|
1143
|
+
if (isThemeError && error?.details && typeof error.details === "object") payload.details = error.details;
|
|
1117
1144
|
if (error?.optionalFeatureInstall) payload.optionalFeatureInstall = error.optionalFeatureInstall;
|
|
1118
1145
|
sendJson(res, statusCode, payload);
|
|
1119
1146
|
}
|
|
@@ -1130,7 +1157,7 @@ function formatBytes(bytes) {
|
|
|
1130
1157
|
return `${value} B`;
|
|
1131
1158
|
}
|
|
1132
1159
|
|
|
1133
|
-
async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES } = {}) {
|
|
1160
|
+
async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES, emptyError } = {}) {
|
|
1134
1161
|
const chunks = [];
|
|
1135
1162
|
let size = 0;
|
|
1136
1163
|
for await (const chunk of req) {
|
|
@@ -1138,9 +1165,15 @@ async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES } = {}) {
|
|
|
1138
1165
|
if (size > limitBytes) throw makeHttpError(413, `Request body too large (limit ${formatBytes(limitBytes)})`);
|
|
1139
1166
|
chunks.push(chunk);
|
|
1140
1167
|
}
|
|
1141
|
-
if (chunks.length === 0)
|
|
1168
|
+
if (chunks.length === 0) {
|
|
1169
|
+
if (emptyError) throw makeHttpError(400, emptyError);
|
|
1170
|
+
return {};
|
|
1171
|
+
}
|
|
1142
1172
|
const text = Buffer.concat(chunks).toString("utf8");
|
|
1143
|
-
if (!text.trim())
|
|
1173
|
+
if (!text.trim()) {
|
|
1174
|
+
if (emptyError) throw makeHttpError(400, emptyError);
|
|
1175
|
+
return {};
|
|
1176
|
+
}
|
|
1144
1177
|
return JSON.parse(text);
|
|
1145
1178
|
}
|
|
1146
1179
|
|
|
@@ -1296,7 +1329,7 @@ function sendRemoteAuthRequired(req, res, url) {
|
|
|
1296
1329
|
// disconnects healthy Chromium EventSource streams as soon as a frame exceeds
|
|
1297
1330
|
// roughly 16 KiB. Queue subsequent frames until "drain", with strict bounds so
|
|
1298
1331
|
// a client that truly stops reading cannot grow server memory indefinitely.
|
|
1299
|
-
const SSE_BACKPRESSURE_MAX_PENDING_BYTES =
|
|
1332
|
+
const SSE_BACKPRESSURE_MAX_PENDING_BYTES = 4 * 1024 * 1024;
|
|
1300
1333
|
const SSE_BACKPRESSURE_MAX_PENDING_FRAMES = 256;
|
|
1301
1334
|
const SSE_BACKPRESSURE_TIMEOUT_MS = 10_000;
|
|
1302
1335
|
|
|
@@ -1916,6 +1949,25 @@ function formatCommandForDisplay(command, args) {
|
|
|
1916
1949
|
return [command, ...args].map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" ");
|
|
1917
1950
|
}
|
|
1918
1951
|
|
|
1952
|
+
async function npmGlobalNodeModulesRoot() {
|
|
1953
|
+
const invocation = resolveNpmCommandInvocation(["root", "-g"]);
|
|
1954
|
+
const result = await runCommand(invocation.command, invocation.args, { timeoutMs: 10_000, maxOutputLength: 8_000 });
|
|
1955
|
+
if (result.exitCode !== 0 || result.timedOut || result.error) return null;
|
|
1956
|
+
return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
async function bunGlobalNodeModulesRoots() {
|
|
1960
|
+
const available = await runCommand("bun", ["--version"], { timeoutMs: 10_000, maxOutputLength: 2_000 });
|
|
1961
|
+
if (available.exitCode !== 0 || available.timedOut || available.error) return [];
|
|
1962
|
+
const roots = new Set([path.join(homedir(), ".bun", "install", "global", "node_modules")]);
|
|
1963
|
+
const binResult = await runCommand("bun", ["pm", "bin", "-g"], { timeoutMs: 10_000, maxOutputLength: 8_000 });
|
|
1964
|
+
if (binResult.exitCode === 0 && !binResult.timedOut && !binResult.error) {
|
|
1965
|
+
const binDir = binResult.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
|
|
1966
|
+
if (binDir) roots.add(path.join(path.dirname(binDir), "install", "global", "node_modules"));
|
|
1967
|
+
}
|
|
1968
|
+
return [...roots];
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1919
1971
|
let optionalPackageNodeModulesRootsCache = null;
|
|
1920
1972
|
async function optionalPackageNodeModulesRoots() {
|
|
1921
1973
|
if (optionalPackageNodeModulesRootsCache) return optionalPackageNodeModulesRootsCache;
|
|
@@ -2541,9 +2593,25 @@ async function safetyGuardConfigModule() {
|
|
|
2541
2593
|
new URL("../../pi-extension-safety-guard/src/config.mjs", import.meta.url).href,
|
|
2542
2594
|
];
|
|
2543
2595
|
const failures = [];
|
|
2596
|
+
const requiredExports = [
|
|
2597
|
+
"SAFETY_GUARD_CATEGORIES",
|
|
2598
|
+
"SAFETY_GUARD_CONTEXT_LINES_MAX",
|
|
2599
|
+
"SAFETY_GUARD_CONTEXT_LINES_MIN",
|
|
2600
|
+
"SAFETY_GUARD_CONFIG_VERSION",
|
|
2601
|
+
"SAFETY_GUARD_THINKING_LEVELS",
|
|
2602
|
+
"assertSafetyGuardConfigPatch",
|
|
2603
|
+
"defaultSafetyGuardConfig",
|
|
2604
|
+
"mergeSafetyGuardConfig",
|
|
2605
|
+
"readSafetyGuardConfig",
|
|
2606
|
+
"safetyGuardConfigFile",
|
|
2607
|
+
"writeSafetyGuardConfig",
|
|
2608
|
+
];
|
|
2544
2609
|
for (const specifier of specifiers) {
|
|
2545
2610
|
try {
|
|
2546
|
-
|
|
2611
|
+
const module = await import(specifier);
|
|
2612
|
+
const missing = requiredExports.filter((name) => module[name] === undefined);
|
|
2613
|
+
if (missing.length) throw new Error(`missing ${missing.join(", ")}`);
|
|
2614
|
+
return module;
|
|
2547
2615
|
} catch (error) {
|
|
2548
2616
|
failures.push(error instanceof Error ? error.message : String(error));
|
|
2549
2617
|
}
|
|
@@ -2557,9 +2625,14 @@ async function safetyGuardConfigModule() {
|
|
|
2557
2625
|
return safetyGuardConfigModulePromise;
|
|
2558
2626
|
}
|
|
2559
2627
|
|
|
2560
|
-
|
|
2628
|
+
function safetyGuardModelKey(model) {
|
|
2629
|
+
return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
async function safetyGuardConfigData(tab, { config: suppliedConfig, models: suppliedModels } = {}) {
|
|
2561
2633
|
const settingsModule = await safetyGuardConfigModule();
|
|
2562
|
-
const config = settingsModule.readSafetyGuardConfig();
|
|
2634
|
+
const config = suppliedConfig || settingsModule.readSafetyGuardConfig();
|
|
2635
|
+
const models = suppliedModels || await availableGitWorkflowModels(tab);
|
|
2563
2636
|
return {
|
|
2564
2637
|
config,
|
|
2565
2638
|
defaults: settingsModule.defaultSafetyGuardConfig(),
|
|
@@ -2568,12 +2641,18 @@ async function safetyGuardConfigData() {
|
|
|
2568
2641
|
min: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MIN,
|
|
2569
2642
|
max: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MAX,
|
|
2570
2643
|
},
|
|
2644
|
+
models,
|
|
2645
|
+
modelThinkingLevels: Object.fromEntries(models.map((model) => [
|
|
2646
|
+
safetyGuardModelKey(model),
|
|
2647
|
+
supportedGitWorkflowThinkingLevels(model),
|
|
2648
|
+
])),
|
|
2649
|
+
thinkingLevels: [...settingsModule.SAFETY_GUARD_THINKING_LEVELS],
|
|
2571
2650
|
version: settingsModule.SAFETY_GUARD_CONFIG_VERSION,
|
|
2572
2651
|
path: settingsModule.safetyGuardConfigFile(),
|
|
2573
2652
|
};
|
|
2574
2653
|
}
|
|
2575
2654
|
|
|
2576
|
-
async function saveSafetyGuardConfigData(body = {}) {
|
|
2655
|
+
async function saveSafetyGuardConfigData(tab, body = {}) {
|
|
2577
2656
|
const settingsModule = await safetyGuardConfigModule();
|
|
2578
2657
|
const submitted = body.config && typeof body.config === "object" ? body.config : body;
|
|
2579
2658
|
try {
|
|
@@ -2582,12 +2661,27 @@ async function saveSafetyGuardConfigData(body = {}) {
|
|
|
2582
2661
|
throw makeHttpError(400, error instanceof Error ? error.message : String(error));
|
|
2583
2662
|
}
|
|
2584
2663
|
|
|
2664
|
+
const next = settingsModule.mergeSafetyGuardConfig(settingsModule.readSafetyGuardConfig(), submitted);
|
|
2665
|
+
let models;
|
|
2666
|
+
if (next.autoReview.enabled) {
|
|
2667
|
+
models = await availableGitWorkflowModels(tab);
|
|
2668
|
+
const provider = next.autoReview.model.provider;
|
|
2669
|
+
const modelId = next.autoReview.model.modelId;
|
|
2670
|
+
const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
|
|
2671
|
+
if (!model) throw makeHttpError(400, `Selected auto-review model is not currently available: ${provider || "unset"}/${modelId || "unset"}`);
|
|
2672
|
+
const supportedLevels = supportedGitWorkflowThinkingLevels(model);
|
|
2673
|
+
if (!supportedLevels.includes(next.autoReview.model.thinkingLevel)) {
|
|
2674
|
+
throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.autoReview.model.thinkingLevel}`);
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
|
|
2678
|
+
let config;
|
|
2585
2679
|
try {
|
|
2586
|
-
|
|
2587
|
-
return { ...(await safetyGuardConfigData()), config };
|
|
2680
|
+
config = settingsModule.writeSafetyGuardConfig(submitted);
|
|
2588
2681
|
} catch (error) {
|
|
2589
2682
|
throw makeHttpError(500, error instanceof Error ? error.message : String(error));
|
|
2590
2683
|
}
|
|
2684
|
+
return safetyGuardConfigData(tab, { config, models });
|
|
2591
2685
|
}
|
|
2592
2686
|
|
|
2593
2687
|
function requireSubagentLaunchSlotScope(value) {
|
|
@@ -2696,8 +2790,8 @@ function gitWorkflowModelKey(model) {
|
|
|
2696
2790
|
}
|
|
2697
2791
|
|
|
2698
2792
|
async function availableGitWorkflowModels(tab) {
|
|
2699
|
-
const response = await
|
|
2700
|
-
if (
|
|
2793
|
+
const response = await safeRpcResponse(tab, { type: "get_available_models" });
|
|
2794
|
+
if (response.success === false) throw makeHttpError(400, response.error || "Failed to load available models");
|
|
2701
2795
|
return (Array.isArray(response.data?.models) ? response.data.models : [])
|
|
2702
2796
|
.filter((model) => model?.provider && model?.id)
|
|
2703
2797
|
.sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
|
|
@@ -2736,6 +2830,11 @@ function requireGitWorkflowChoice(value, key, choices) {
|
|
|
2736
2830
|
return text;
|
|
2737
2831
|
}
|
|
2738
2832
|
|
|
2833
|
+
function requireGitWorkflowBoolean(value, key) {
|
|
2834
|
+
if (typeof value !== "boolean") throw makeHttpError(400, `${key} must be a boolean`);
|
|
2835
|
+
return value;
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2739
2838
|
async function saveGitWorkflowPreferencesData(tab, body = {}) {
|
|
2740
2839
|
const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
|
|
2741
2840
|
if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
|
|
@@ -2743,6 +2842,7 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
|
|
|
2743
2842
|
if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
|
|
2744
2843
|
if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
|
|
2745
2844
|
if (submitted.stagingPolicy !== undefined) requireGitWorkflowChoice(submitted.stagingPolicy, "stagingPolicy", GIT_WORKFLOW_STAGING_POLICIES);
|
|
2845
|
+
if (submitted.reviewProcessEnabled !== undefined) requireGitWorkflowBoolean(submitted.reviewProcessEnabled, "reviewProcessEnabled");
|
|
2746
2846
|
if (submitted.deliveryMode !== undefined) requireGitWorkflowChoice(submitted.deliveryMode, "deliveryMode", GIT_WORKFLOW_DELIVERY_MODES);
|
|
2747
2847
|
if (submitted.verificationPolicy !== undefined) requireGitWorkflowChoice(submitted.verificationPolicy, "verificationPolicy", GIT_WORKFLOW_VERIFICATION_POLICIES);
|
|
2748
2848
|
|
|
@@ -3283,7 +3383,12 @@ function appRunnerCandidate({ id, label, kind, command, args = [], projectFile =
|
|
|
3283
3383
|
|
|
3284
3384
|
function addAppRunner(runners, runner) {
|
|
3285
3385
|
if (!runner?.id || !runner.command) return;
|
|
3286
|
-
if (runners.some((item) => item.id === runner.id
|
|
3386
|
+
if (runners.some((item) => item.id === runner.id)) return;
|
|
3387
|
+
const duplicateIndex = runners.findIndex((item) => item.displayCommand === runner.displayCommand);
|
|
3388
|
+
if (duplicateIndex >= 0) {
|
|
3389
|
+
if (runner.custom && !runners[duplicateIndex].custom) runners.splice(duplicateIndex, 1, runner);
|
|
3390
|
+
return;
|
|
3391
|
+
}
|
|
3287
3392
|
runners.push(runner);
|
|
3288
3393
|
}
|
|
3289
3394
|
|
|
@@ -6234,9 +6339,12 @@ async function readGitIncomingChanges(root, summary) {
|
|
|
6234
6339
|
}
|
|
6235
6340
|
}
|
|
6236
6341
|
|
|
6237
|
-
async function pullGitChanges(cwd) {
|
|
6342
|
+
async function pullGitChanges(cwd, { remote } = {}) {
|
|
6238
6343
|
const root = await getGitRoot(cwd);
|
|
6239
|
-
const
|
|
6344
|
+
const pullArgs = ["pull", "--ff-only"];
|
|
6345
|
+
if (remote === "origin") pullArgs.push("origin");
|
|
6346
|
+
else if (remote) throw new Error(`Unsupported Git pull remote: ${String(remote)}`);
|
|
6347
|
+
const payload = await runGuardedGitMutation(pullArgs, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
|
|
6240
6348
|
if (payload.data) payload.data.root = root;
|
|
6241
6349
|
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
6242
6350
|
else {
|
|
@@ -8290,15 +8398,6 @@ function themeLabel(name) {
|
|
|
8290
8398
|
.join(" ");
|
|
8291
8399
|
}
|
|
8292
8400
|
|
|
8293
|
-
function stringRecord(value) {
|
|
8294
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
8295
|
-
const record = {};
|
|
8296
|
-
for (const [key, item] of Object.entries(value)) {
|
|
8297
|
-
if (typeof item === "string" || typeof item === "number" || typeof item === "boolean") record[key] = String(item);
|
|
8298
|
-
}
|
|
8299
|
-
return record;
|
|
8300
|
-
}
|
|
8301
|
-
|
|
8302
8401
|
async function directoryExists(dir) {
|
|
8303
8402
|
try {
|
|
8304
8403
|
const info = await stat(dir);
|
|
@@ -8309,7 +8408,9 @@ async function directoryExists(dir) {
|
|
|
8309
8408
|
}
|
|
8310
8409
|
|
|
8311
8410
|
async function resolveBundledThemesDir() {
|
|
8312
|
-
|
|
8411
|
+
// Pi-managed packages are the user's canonical installation. Prefer them to
|
|
8412
|
+
// any duplicate that happens to be visible from the WebUI's npm prefix.
|
|
8413
|
+
const candidates = [path.join(configuredAgentNpmRoot(), "node_modules", "@firstpick", "pi-themes-bundle", "themes")];
|
|
8313
8414
|
try {
|
|
8314
8415
|
const manifestPath = require.resolve("@firstpick/pi-themes-bundle/package.json");
|
|
8315
8416
|
const root = path.dirname(manifestPath);
|
|
@@ -8319,8 +8420,9 @@ async function resolveBundledThemesDir() {
|
|
|
8319
8420
|
if (typeof entry === "string" && entry.trim()) candidates.push(path.resolve(root, entry));
|
|
8320
8421
|
}
|
|
8321
8422
|
} catch {
|
|
8322
|
-
//
|
|
8423
|
+
// The bundle may live outside this package's Node resolution tree.
|
|
8323
8424
|
}
|
|
8425
|
+
// In repo development the bundle may be a sibling package instead.
|
|
8324
8426
|
candidates.push(path.resolve(packageRoot, "..", "pi-package-themes-bundle", "themes"));
|
|
8325
8427
|
|
|
8326
8428
|
for (const candidate of candidates) {
|
|
@@ -8329,39 +8431,350 @@ async function resolveBundledThemesDir() {
|
|
|
8329
8431
|
return null;
|
|
8330
8432
|
}
|
|
8331
8433
|
|
|
8332
|
-
function
|
|
8333
|
-
const
|
|
8334
|
-
|
|
8335
|
-
|
|
8336
|
-
|
|
8337
|
-
|
|
8338
|
-
|
|
8339
|
-
|
|
8434
|
+
function themeHttpError(statusCode, code, message, details) {
|
|
8435
|
+
const error = makeHttpError(statusCode, message);
|
|
8436
|
+
error.code = code;
|
|
8437
|
+
if (details) error.details = details;
|
|
8438
|
+
return error;
|
|
8439
|
+
}
|
|
8440
|
+
|
|
8441
|
+
function catalogTheme(theme, fileName, scope) {
|
|
8442
|
+
const validation = validateTheme(theme, { allowWebuiExport: scope === "bundled" });
|
|
8443
|
+
if (!validation.ok) throw new ThemeContractError("Theme does not satisfy the installed Pi theme contract", validation.issues);
|
|
8444
|
+
const native = canonicalizeTheme(theme, { allowWebuiExport: scope === "bundled" });
|
|
8445
|
+
if (scope === "bundled" && theme.export) {
|
|
8446
|
+
native.export = { ...(native.export || {}) };
|
|
8447
|
+
for (const [key, value] of Object.entries(theme.export)) {
|
|
8448
|
+
if (typeof value === "string" && !Object.hasOwn(native.export, key)) native.export[key] = value;
|
|
8449
|
+
}
|
|
8450
|
+
}
|
|
8451
|
+
const entry = {
|
|
8452
|
+
name: native.name,
|
|
8453
|
+
label: themeLabel(native.name),
|
|
8454
|
+
vars: native.vars || {},
|
|
8455
|
+
colors: native.colors,
|
|
8456
|
+
export: native.export || {},
|
|
8457
|
+
scope,
|
|
8458
|
+
custom: scope !== "bundled",
|
|
8340
8459
|
};
|
|
8460
|
+
if (scope !== "bundled") entry.fileName = fileName;
|
|
8461
|
+
return entry;
|
|
8462
|
+
}
|
|
8463
|
+
|
|
8464
|
+
function themePathInside(root, candidate) {
|
|
8465
|
+
const relative = path.relative(root, candidate);
|
|
8466
|
+
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
8467
|
+
}
|
|
8468
|
+
|
|
8469
|
+
async function existingThemeRoot(baseDir, segments) {
|
|
8470
|
+
let root;
|
|
8471
|
+
try {
|
|
8472
|
+
root = await realpath(baseDir);
|
|
8473
|
+
} catch {
|
|
8474
|
+
return null;
|
|
8475
|
+
}
|
|
8476
|
+
const confinementRoot = root;
|
|
8477
|
+
for (const segment of segments) {
|
|
8478
|
+
const candidate = path.join(root, segment);
|
|
8479
|
+
let info;
|
|
8480
|
+
try {
|
|
8481
|
+
info = await lstat(candidate);
|
|
8482
|
+
} catch (error) {
|
|
8483
|
+
if (error?.code === "ENOENT") return null;
|
|
8484
|
+
throw error;
|
|
8485
|
+
}
|
|
8486
|
+
if (info.isSymbolicLink() || !info.isDirectory()) return null;
|
|
8487
|
+
root = await realpath(candidate);
|
|
8488
|
+
if (!themePathInside(confinementRoot, root)) return null;
|
|
8489
|
+
}
|
|
8490
|
+
return root;
|
|
8491
|
+
}
|
|
8492
|
+
|
|
8493
|
+
async function ensureThemeRoot(baseDir, segments) {
|
|
8494
|
+
await mkdir(baseDir, { recursive: true, mode: 0o700 });
|
|
8495
|
+
const baseInfo = await stat(baseDir);
|
|
8496
|
+
if (!baseInfo.isDirectory()) throw themeHttpError(409, "THEME_UNSAFE_TARGET", "The server-derived theme base is not a directory.");
|
|
8497
|
+
let root = await realpath(baseDir);
|
|
8498
|
+
const confinementRoot = root;
|
|
8499
|
+
for (const segment of segments) {
|
|
8500
|
+
const candidate = path.join(root, segment);
|
|
8501
|
+
try {
|
|
8502
|
+
await mkdir(candidate, { mode: 0o700 });
|
|
8503
|
+
} catch (error) {
|
|
8504
|
+
if (error?.code !== "EEXIST") throw error;
|
|
8505
|
+
}
|
|
8506
|
+
const info = await lstat(candidate);
|
|
8507
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
8508
|
+
throw themeHttpError(409, "THEME_UNSAFE_TARGET", "The server-derived theme directory contains a symlink or non-directory component.");
|
|
8509
|
+
}
|
|
8510
|
+
root = await realpath(candidate);
|
|
8511
|
+
if (!themePathInside(confinementRoot, root)) {
|
|
8512
|
+
throw themeHttpError(409, "THEME_UNSAFE_TARGET", "The server-derived theme directory escapes its allowed root.");
|
|
8513
|
+
}
|
|
8514
|
+
}
|
|
8515
|
+
return root;
|
|
8516
|
+
}
|
|
8517
|
+
|
|
8518
|
+
async function readThemeDirectory(baseDir, segments, scope) {
|
|
8519
|
+
const root = await existingThemeRoot(baseDir, segments);
|
|
8520
|
+
if (!root) return [];
|
|
8521
|
+
const entries = [];
|
|
8522
|
+
let files;
|
|
8523
|
+
try {
|
|
8524
|
+
files = await readdir(root);
|
|
8525
|
+
} catch {
|
|
8526
|
+
return [];
|
|
8527
|
+
}
|
|
8528
|
+
for (const fileName of files.filter((name) => name.endsWith(".json")).sort((a, b) => a.localeCompare(b))) {
|
|
8529
|
+
try {
|
|
8530
|
+
const target = path.join(root, fileName);
|
|
8531
|
+
const info = await lstat(target);
|
|
8532
|
+
if (info.isSymbolicLink() || !info.isFile()) continue;
|
|
8533
|
+
const resolved = await realpath(target);
|
|
8534
|
+
if (!themePathInside(root, resolved)) continue;
|
|
8535
|
+
entries.push(catalogTheme(JSON.parse(await readFile(resolved, "utf8")), fileName, scope));
|
|
8536
|
+
} catch (error) {
|
|
8537
|
+
console.error(`Skipping invalid ${scope} theme ${fileName}: ${sanitizeError(error)}`);
|
|
8538
|
+
}
|
|
8539
|
+
}
|
|
8540
|
+
return entries.sort((a, b) => a.label.localeCompare(b.label) || a.fileName.localeCompare(b.fileName));
|
|
8341
8541
|
}
|
|
8342
8542
|
|
|
8343
8543
|
async function readBundledThemes() {
|
|
8344
8544
|
const dir = await resolveBundledThemesDir();
|
|
8345
8545
|
if (!dir) return { source: "@firstpick/pi-themes-bundle", themes: [] };
|
|
8346
|
-
|
|
8347
|
-
const files = (await readdir(dir)).filter((file) => file.endsWith(".json")).sort((a, b) => a.localeCompare(b));
|
|
8348
8546
|
const themes = [];
|
|
8349
|
-
for (const
|
|
8547
|
+
for (const fileName of (await readdir(dir)).filter((file) => file.endsWith(".json")).sort((a, b) => a.localeCompare(b))) {
|
|
8350
8548
|
try {
|
|
8351
|
-
const
|
|
8352
|
-
|
|
8549
|
+
const target = path.join(dir, fileName);
|
|
8550
|
+
const info = await lstat(target);
|
|
8551
|
+
if (info.isSymbolicLink() || !info.isFile()) continue;
|
|
8552
|
+
themes.push(catalogTheme(JSON.parse(await readFile(target, "utf8")), fileName, "bundled"));
|
|
8353
8553
|
} catch (error) {
|
|
8354
|
-
console.error(`Skipping invalid theme ${
|
|
8554
|
+
console.error(`Skipping invalid bundled theme ${fileName}: ${sanitizeError(error)}`);
|
|
8355
8555
|
}
|
|
8356
8556
|
}
|
|
8357
8557
|
themes.sort((a, b) => a.label.localeCompare(b.label));
|
|
8358
8558
|
return { source: "@firstpick/pi-themes-bundle", themes };
|
|
8359
8559
|
}
|
|
8360
8560
|
|
|
8561
|
+
function customThemeRoots(tab) {
|
|
8562
|
+
const projectTrusted = !!tab && projectTrustDecision(tab.cwd, agentDir);
|
|
8563
|
+
return {
|
|
8564
|
+
global: { baseDir: agentDir, segments: ["themes"] },
|
|
8565
|
+
project: { baseDir: tab?.cwd, segments: [".pi", "themes"], trusted: projectTrusted },
|
|
8566
|
+
};
|
|
8567
|
+
}
|
|
8568
|
+
|
|
8569
|
+
async function readThemeCatalog(tab) {
|
|
8570
|
+
const bundled = await readBundledThemes();
|
|
8571
|
+
const roots = customThemeRoots(tab);
|
|
8572
|
+
const globalThemes = await readThemeDirectory(roots.global.baseDir, roots.global.segments, "global");
|
|
8573
|
+
const projectThemes = roots.project.trusted
|
|
8574
|
+
? await readThemeDirectory(roots.project.baseDir, roots.project.segments, "project")
|
|
8575
|
+
: [];
|
|
8576
|
+
const themes = [];
|
|
8577
|
+
const names = new Map();
|
|
8578
|
+
const collisions = [];
|
|
8579
|
+
for (const entry of [...bundled.themes, ...globalThemes, ...projectThemes]) {
|
|
8580
|
+
const previous = names.get(entry.name);
|
|
8581
|
+
if (previous) {
|
|
8582
|
+
collisions.push({ name: entry.name, keptScope: previous.scope, skippedScope: entry.scope });
|
|
8583
|
+
continue;
|
|
8584
|
+
}
|
|
8585
|
+
names.set(entry.name, entry);
|
|
8586
|
+
themes.push(entry);
|
|
8587
|
+
}
|
|
8588
|
+
return {
|
|
8589
|
+
source: bundled.source,
|
|
8590
|
+
themes,
|
|
8591
|
+
collisions,
|
|
8592
|
+
scopes: {
|
|
8593
|
+
global: { available: true },
|
|
8594
|
+
project: { available: !!tab, trusted: roots.project.trusted },
|
|
8595
|
+
},
|
|
8596
|
+
};
|
|
8597
|
+
}
|
|
8598
|
+
|
|
8599
|
+
function requireCustomThemeJsonRequest(req) {
|
|
8600
|
+
const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
|
|
8601
|
+
if (contentType !== "application/json") throw themeHttpError(415, "THEME_JSON_REQUIRED", "Custom theme saves require Content-Type: application/json.");
|
|
8602
|
+
const fetchSite = String(req.headers["sec-fetch-site"] || "").trim().toLowerCase();
|
|
8603
|
+
if (fetchSite && !["same-origin", "same-site", "none"].includes(fetchSite)) {
|
|
8604
|
+
throw themeHttpError(403, "THEME_CROSS_SITE_BLOCKED", "Cross-site custom theme saves are blocked.");
|
|
8605
|
+
}
|
|
8606
|
+
}
|
|
8607
|
+
|
|
8608
|
+
function validateCustomThemeSaveBody(body) {
|
|
8609
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
8610
|
+
throw themeHttpError(400, "THEME_REQUEST_INVALID", "Custom theme save body must be an object.");
|
|
8611
|
+
}
|
|
8612
|
+
const allowed = new Set(["scope", "fileName", "theme", "overwrite", "expectedMtimeMs"]);
|
|
8613
|
+
const unknown = Object.keys(body).filter((key) => !allowed.has(key));
|
|
8614
|
+
if (unknown.length) throw themeHttpError(400, "THEME_REQUEST_INVALID", `Unsupported custom theme save field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`);
|
|
8615
|
+
if (body.scope !== "global" && body.scope !== "project") throw themeHttpError(400, "THEME_SCOPE_INVALID", "scope must be global or project.");
|
|
8616
|
+
let fileName;
|
|
8617
|
+
let theme;
|
|
8618
|
+
try {
|
|
8619
|
+
fileName = normalizeThemeFileName(body.fileName);
|
|
8620
|
+
theme = canonicalizeTheme(body.theme, { allowWebuiExport: true });
|
|
8621
|
+
} catch (error) {
|
|
8622
|
+
if (error instanceof ThemeContractError) throw themeHttpError(400, "THEME_INVALID", error.message, { issues: error.issues || [] });
|
|
8623
|
+
throw error;
|
|
8624
|
+
}
|
|
8625
|
+
if (theme.name !== themeNameFromFileName(fileName)) {
|
|
8626
|
+
throw themeHttpError(400, "THEME_NAME_MISMATCH", "Theme name must exactly match fileName without the .json suffix.");
|
|
8627
|
+
}
|
|
8628
|
+
if (typeof body.overwrite !== "boolean") throw themeHttpError(400, "THEME_REQUEST_INVALID", "overwrite must be a boolean.");
|
|
8629
|
+
if (body.expectedMtimeMs !== null && (typeof body.expectedMtimeMs !== "number" || !Number.isFinite(body.expectedMtimeMs) || body.expectedMtimeMs < 0)) {
|
|
8630
|
+
throw themeHttpError(400, "THEME_REQUEST_INVALID", "expectedMtimeMs must be a non-negative number or null.");
|
|
8631
|
+
}
|
|
8632
|
+
if (!body.overwrite && body.expectedMtimeMs !== null) {
|
|
8633
|
+
throw themeHttpError(400, "THEME_REQUEST_INVALID", "expectedMtimeMs must be null until overwrite is explicitly confirmed.");
|
|
8634
|
+
}
|
|
8635
|
+
if (body.overwrite && body.expectedMtimeMs === null) {
|
|
8636
|
+
throw themeHttpError(400, "THEME_REQUEST_INVALID", "An overwrite requires the target mtime returned by THEME_EXISTS.");
|
|
8637
|
+
}
|
|
8638
|
+
return { scope: body.scope, fileName, theme, overwrite: body.overwrite, expectedMtimeMs: body.expectedMtimeMs };
|
|
8639
|
+
}
|
|
8640
|
+
|
|
8641
|
+
async function customThemeCollision(request, tab) {
|
|
8642
|
+
const bundled = await readBundledThemes();
|
|
8643
|
+
if (bundled.themes.some(({ name }) => name === request.theme.name)) return { scope: "bundled" };
|
|
8644
|
+
const roots = customThemeRoots(tab);
|
|
8645
|
+
for (const scope of ["global", "project"]) {
|
|
8646
|
+
if (scope === "project" && !roots.project.trusted) continue;
|
|
8647
|
+
const root = roots[scope];
|
|
8648
|
+
const entries = await readThemeDirectory(root.baseDir, root.segments, scope);
|
|
8649
|
+
for (const entry of entries) {
|
|
8650
|
+
if (entry.name !== request.theme.name) continue;
|
|
8651
|
+
if (scope === request.scope && entry.fileName === request.fileName) continue;
|
|
8652
|
+
if (scope === request.scope) {
|
|
8653
|
+
const directory = await existingThemeRoot(root.baseDir, root.segments);
|
|
8654
|
+
if (directory) {
|
|
8655
|
+
try {
|
|
8656
|
+
const [existingPath, requestedPath] = await Promise.all([
|
|
8657
|
+
realpath(path.join(directory, entry.fileName)),
|
|
8658
|
+
realpath(path.join(directory, request.fileName)),
|
|
8659
|
+
]);
|
|
8660
|
+
if (existingPath === requestedPath) continue;
|
|
8661
|
+
} catch {
|
|
8662
|
+
// A missing differently-cased path is a real collision on a case-sensitive filesystem.
|
|
8663
|
+
}
|
|
8664
|
+
}
|
|
8665
|
+
}
|
|
8666
|
+
return { scope, fileName: entry.fileName };
|
|
8667
|
+
}
|
|
8668
|
+
}
|
|
8669
|
+
return null;
|
|
8670
|
+
}
|
|
8671
|
+
|
|
8672
|
+
let customThemeMutationQueue = Promise.resolve();
|
|
8673
|
+
|
|
8674
|
+
function queueCustomThemeMutation(operation) {
|
|
8675
|
+
const result = customThemeMutationQueue.catch(() => {}).then(operation);
|
|
8676
|
+
customThemeMutationQueue = result.catch(() => {});
|
|
8677
|
+
return result;
|
|
8678
|
+
}
|
|
8679
|
+
|
|
8680
|
+
async function saveCustomTheme(tab, request) {
|
|
8681
|
+
return queueCustomThemeMutation(async () => {
|
|
8682
|
+
const roots = customThemeRoots(tab);
|
|
8683
|
+
if (request.scope === "project" && !roots.project.trusted) {
|
|
8684
|
+
throw themeHttpError(403, "THEME_PROJECT_UNTRUSTED", "Project theme saves require a saved trusted-project decision in Pi.");
|
|
8685
|
+
}
|
|
8686
|
+
const collision = await customThemeCollision(request, tab);
|
|
8687
|
+
if (collision) {
|
|
8688
|
+
throw themeHttpError(409, "THEME_NAME_COLLISION", "A bundled or opposite-scope theme already uses this name.", {
|
|
8689
|
+
scope: collision.scope,
|
|
8690
|
+
...(collision.fileName ? { fileName: collision.fileName } : {}),
|
|
8691
|
+
});
|
|
8692
|
+
}
|
|
8693
|
+
const selected = roots[request.scope];
|
|
8694
|
+
const root = await ensureThemeRoot(selected.baseDir, selected.segments);
|
|
8695
|
+
const target = path.join(root, request.fileName);
|
|
8696
|
+
if (!themePathInside(root, target)) throw themeHttpError(409, "THEME_UNSAFE_TARGET", "Theme target escapes its server-derived root.");
|
|
8697
|
+
|
|
8698
|
+
let before = null;
|
|
8699
|
+
try {
|
|
8700
|
+
before = await lstat(target);
|
|
8701
|
+
} catch (error) {
|
|
8702
|
+
if (error?.code !== "ENOENT") throw error;
|
|
8703
|
+
}
|
|
8704
|
+
if (before?.isSymbolicLink() || (before && !before.isFile())) {
|
|
8705
|
+
throw themeHttpError(409, "THEME_UNSAFE_TARGET", "The theme target is a symlink or non-file entry.");
|
|
8706
|
+
}
|
|
8707
|
+
if (before && !request.overwrite) {
|
|
8708
|
+
throw themeHttpError(409, "THEME_EXISTS", "The custom theme already exists and requires explicit overwrite confirmation.", {
|
|
8709
|
+
scope: request.scope,
|
|
8710
|
+
fileName: request.fileName,
|
|
8711
|
+
mtimeMs: before.mtimeMs,
|
|
8712
|
+
});
|
|
8713
|
+
}
|
|
8714
|
+
if ((!before && request.overwrite) || (before && before.mtimeMs !== request.expectedMtimeMs)) {
|
|
8715
|
+
throw themeHttpError(409, "THEME_CHANGED", "The custom theme changed after overwrite confirmation.", {
|
|
8716
|
+
scope: request.scope,
|
|
8717
|
+
fileName: request.fileName,
|
|
8718
|
+
...(before ? { mtimeMs: before.mtimeMs } : {}),
|
|
8719
|
+
});
|
|
8720
|
+
}
|
|
8721
|
+
|
|
8722
|
+
const bytes = serializeTheme(request.theme, { allowWebuiExport: false });
|
|
8723
|
+
const temp = path.join(root, `.${request.fileName}.${randomUUID()}.tmp`);
|
|
8724
|
+
let handle;
|
|
8725
|
+
try {
|
|
8726
|
+
handle = await open(temp, "wx", 0o600);
|
|
8727
|
+
await handle.writeFile(bytes, "utf8");
|
|
8728
|
+
await handle.sync();
|
|
8729
|
+
await handle.close();
|
|
8730
|
+
handle = undefined;
|
|
8731
|
+
|
|
8732
|
+
const verifiedRoot = await existingThemeRoot(selected.baseDir, selected.segments);
|
|
8733
|
+
if (verifiedRoot !== root) throw themeHttpError(409, "THEME_UNSAFE_TARGET", "Theme directory changed during save.");
|
|
8734
|
+
let finalState = null;
|
|
8735
|
+
try {
|
|
8736
|
+
finalState = await lstat(target);
|
|
8737
|
+
} catch (error) {
|
|
8738
|
+
if (error?.code !== "ENOENT") throw error;
|
|
8739
|
+
}
|
|
8740
|
+
if (finalState?.isSymbolicLink() || (finalState && !finalState.isFile())) {
|
|
8741
|
+
throw themeHttpError(409, "THEME_UNSAFE_TARGET", "The theme target changed to an unsafe entry during save.");
|
|
8742
|
+
}
|
|
8743
|
+
if ((before && (!finalState || finalState.mtimeMs !== request.expectedMtimeMs)) || (!before && finalState)) {
|
|
8744
|
+
throw themeHttpError(409, "THEME_CHANGED", "The custom theme changed during save.", {
|
|
8745
|
+
scope: request.scope,
|
|
8746
|
+
fileName: request.fileName,
|
|
8747
|
+
...(finalState ? { mtimeMs: finalState.mtimeMs } : {}),
|
|
8748
|
+
});
|
|
8749
|
+
}
|
|
8750
|
+
await rename(temp, target);
|
|
8751
|
+
} finally {
|
|
8752
|
+
await handle?.close().catch(() => {});
|
|
8753
|
+
await rm(temp, { force: true }).catch(() => {});
|
|
8754
|
+
}
|
|
8755
|
+
const saved = await stat(target);
|
|
8756
|
+
return {
|
|
8757
|
+
scope: request.scope,
|
|
8758
|
+
fileName: request.fileName,
|
|
8759
|
+
themeName: request.theme.name,
|
|
8760
|
+
created: !before,
|
|
8761
|
+
overwritten: !!before,
|
|
8762
|
+
mtimeMs: saved.mtimeMs,
|
|
8763
|
+
reloadRequired: true,
|
|
8764
|
+
};
|
|
8765
|
+
});
|
|
8766
|
+
}
|
|
8767
|
+
|
|
8768
|
+
const STATIC_PUBLIC_FILE_EXTENSIONS = new Set([".html", ".css", ".js", ".mjs", ".svg", ".png", ".webp", ".webmanifest"]);
|
|
8769
|
+
|
|
8361
8770
|
function normalizeStaticPath(urlPath) {
|
|
8362
8771
|
if (urlPath === "/") return "index.html";
|
|
8363
8772
|
const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
|
|
8364
|
-
|
|
8773
|
+
// public/ is the package's explicit browser-asset boundary. Accept any safe,
|
|
8774
|
+
// flat asset name from it so a newly imported module cannot outrun a second
|
|
8775
|
+
// manually maintained server allowlist during an in-place package update.
|
|
8776
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) return undefined;
|
|
8777
|
+
if (!STATIC_PUBLIC_FILE_EXTENSIONS.has(path.extname(name))) return undefined;
|
|
8365
8778
|
return name;
|
|
8366
8779
|
}
|
|
8367
8780
|
|
|
@@ -8657,6 +9070,12 @@ function commandFromGet(pathname) {
|
|
|
8657
9070
|
}
|
|
8658
9071
|
}
|
|
8659
9072
|
|
|
9073
|
+
const candidateProbeRequested = process.argv.length === 3 && process.argv[2] === "--candidate-probe";
|
|
9074
|
+
if (candidateProbeRequested) {
|
|
9075
|
+
process.stdout.write(`${JSON.stringify({ ok: true, packageName: WEBUI_PACKAGE, version: packageJson.version, piVersion: piPackageJson.version, serverEntry: fileURLToPath(import.meta.url) })}\n`);
|
|
9076
|
+
process.exit(0);
|
|
9077
|
+
}
|
|
9078
|
+
|
|
8660
9079
|
let options;
|
|
8661
9080
|
try {
|
|
8662
9081
|
options = parseArgs(process.argv.slice(2));
|
|
@@ -8713,7 +9132,7 @@ if (Number.isFinite(startupDelayMs) && startupDelayMs > 0) {
|
|
|
8713
9132
|
await delay(Math.min(startupDelayMs, 10_000));
|
|
8714
9133
|
}
|
|
8715
9134
|
|
|
8716
|
-
const restoreTabs = readRestoreTabsFromEnv();
|
|
9135
|
+
const restoreTabs = await readRestoreTabsFromEnv();
|
|
8717
9136
|
const supervisorAttachCursor = readSupervisorCursorFromEnv();
|
|
8718
9137
|
|
|
8719
9138
|
function normalizedRestoreString(value, maxLength) {
|
|
@@ -8741,18 +9160,17 @@ function normalizeRestoreTabDescriptor(item, seenIds) {
|
|
|
8741
9160
|
return descriptor;
|
|
8742
9161
|
}
|
|
8743
9162
|
|
|
8744
|
-
function readRestoreTabsFromEnv() {
|
|
8745
|
-
const
|
|
9163
|
+
async function readRestoreTabsFromEnv() {
|
|
9164
|
+
const restoreFile = process.env.PI_WEBUI_RESTORE_FILE;
|
|
9165
|
+
delete process.env.PI_WEBUI_RESTORE_FILE;
|
|
8746
9166
|
delete process.env.PI_WEBUI_RESTORE_TABS;
|
|
8747
|
-
if (!
|
|
8748
|
-
|
|
9167
|
+
if (!restoreFile) return [];
|
|
8749
9168
|
try {
|
|
8750
|
-
const
|
|
8751
|
-
const items = Array.isArray(parsed) ? parsed : [];
|
|
9169
|
+
const items = await readRestoreFileOnce(restoreFile, agentDir);
|
|
8752
9170
|
const seenIds = new Set();
|
|
8753
9171
|
return items.map((item) => normalizeRestoreTabDescriptor(item, seenIds)).filter(Boolean).slice(0, RESTORE_TAB_LIMIT);
|
|
8754
9172
|
} catch (error) {
|
|
8755
|
-
console.warn(`failed to
|
|
9173
|
+
console.warn(`failed to read private restore descriptor: ${sanitizeError(error)}`);
|
|
8756
9174
|
return [];
|
|
8757
9175
|
}
|
|
8758
9176
|
}
|
|
@@ -8977,19 +9395,43 @@ function resolveSelectedPiCommand(piArgs) {
|
|
|
8977
9395
|
};
|
|
8978
9396
|
}
|
|
8979
9397
|
|
|
8980
|
-
|
|
8981
|
-
|
|
8982
|
-
|
|
8983
|
-
|
|
8984
|
-
if (
|
|
8985
|
-
|
|
8986
|
-
|
|
8987
|
-
|
|
8988
|
-
|
|
8989
|
-
|
|
9398
|
+
let canonicalPiRuntimePromise = null;
|
|
9399
|
+
let canonicalPiRuntimeProbeVersion = null;
|
|
9400
|
+
|
|
9401
|
+
async function canonicalPiRuntimeIdentity({ force = false, probeVersion = true } = {}) {
|
|
9402
|
+
if (force || canonicalPiRuntimeProbeVersion !== probeVersion) canonicalPiRuntimePromise = null;
|
|
9403
|
+
if (!canonicalPiRuntimePromise) {
|
|
9404
|
+
canonicalPiRuntimeProbeVersion = probeVersion;
|
|
9405
|
+
canonicalPiRuntimePromise = (async () => resolveCanonicalPiRuntime({
|
|
9406
|
+
explicitCommand: options.piBinExplicit ? options.piBin : "",
|
|
9407
|
+
bundledCli: await resolvedPiCliScript(),
|
|
9408
|
+
pathCommand: options.piBin || "pi",
|
|
9409
|
+
runCommand,
|
|
9410
|
+
timeoutMs: 10_000,
|
|
9411
|
+
probeVersion,
|
|
9412
|
+
}))().catch((error) => {
|
|
9413
|
+
canonicalPiRuntimePromise = null;
|
|
9414
|
+
throw error;
|
|
9415
|
+
});
|
|
8990
9416
|
}
|
|
9417
|
+
return canonicalPiRuntimePromise;
|
|
9418
|
+
}
|
|
9419
|
+
|
|
9420
|
+
function invalidateCanonicalPiRuntime() {
|
|
9421
|
+
canonicalPiRuntimePromise = null;
|
|
9422
|
+
canonicalPiRuntimeProbeVersion = null;
|
|
9423
|
+
}
|
|
8991
9424
|
|
|
8992
|
-
|
|
9425
|
+
async function resolvePiCommand(piArgs) {
|
|
9426
|
+
const resolution = await canonicalPiRuntimeIdentity({ probeVersion: false });
|
|
9427
|
+
const active = resolution.active;
|
|
9428
|
+
if (!active) throw new Error(resolution.refusal?.message || "No supported active Pi runtime could be verified.");
|
|
9429
|
+
const args = [...(active.invocation?.args || []), ...piArgs];
|
|
9430
|
+
return {
|
|
9431
|
+
command: active.invocation.command,
|
|
9432
|
+
args,
|
|
9433
|
+
displayCommand: formatCommandForDisplay(active.invocation.command, args),
|
|
9434
|
+
};
|
|
8993
9435
|
}
|
|
8994
9436
|
|
|
8995
9437
|
const tabs = new Map();
|
|
@@ -10929,17 +11371,19 @@ async function loadWebuiWorkspace(id, body = {}) {
|
|
|
10929
11371
|
}
|
|
10930
11372
|
}
|
|
10931
11373
|
|
|
10932
|
-
function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
11374
|
+
async function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
11375
|
+
const restore = await createRestoreFile(agentDir, restorableTabs || []);
|
|
10933
11376
|
const env = {
|
|
10934
11377
|
...process.env,
|
|
10935
|
-
|
|
11378
|
+
PI_WEBUI_RESTORE_FILE: restore.file,
|
|
10936
11379
|
PI_WEBUI_START_DELAY_MS: "1200",
|
|
10937
11380
|
};
|
|
10938
11381
|
if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
|
|
10939
11382
|
else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
|
|
10940
11383
|
if (webuiDevServer) env.PI_WEBUI_DEV = "1";
|
|
10941
11384
|
else delete env.PI_WEBUI_DEV;
|
|
10942
|
-
const
|
|
11385
|
+
const launcher = path.join(packageRoot, "bin", "pi-webui-launcher.mjs");
|
|
11386
|
+
const child = spawn(process.execPath, [launcher, ...process.argv.slice(2)], {
|
|
10943
11387
|
cwd: process.cwd(),
|
|
10944
11388
|
env,
|
|
10945
11389
|
detached: true,
|
|
@@ -10955,6 +11399,279 @@ let updateStatusCacheAt = 0;
|
|
|
10955
11399
|
let piUpdateInProgress = false;
|
|
10956
11400
|
const componentUpdateState = new ComponentUpdateState();
|
|
10957
11401
|
|
|
11402
|
+
async function canonicalUpdateIdentities({ forcePi = false } = {}) {
|
|
11403
|
+
const pi = await canonicalPiRuntimeIdentity({ force: forcePi });
|
|
11404
|
+
const webui = resolveWebuiRuntimeIdentity({
|
|
11405
|
+
packageRoot,
|
|
11406
|
+
packageName: WEBUI_PACKAGE,
|
|
11407
|
+
version: packageJson.version,
|
|
11408
|
+
owner: { manager: webuiDevServer ? "source" : "managed-bootstrap" },
|
|
11409
|
+
});
|
|
11410
|
+
return { pi, webui };
|
|
11411
|
+
}
|
|
11412
|
+
|
|
11413
|
+
function updateOwnerForTarget(target, identities) {
|
|
11414
|
+
if (target === "webui") {
|
|
11415
|
+
const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
|
|
11416
|
+
return sourceCheckout
|
|
11417
|
+
? { manager: "unknown", packageRoot, ownerRoot: packageRoot, sourceCheckout: true }
|
|
11418
|
+
: { manager: "npm", packageRoot, ownerRoot: nodeModulesParentForPackageRoot(packageRoot), topLevel: true };
|
|
11419
|
+
}
|
|
11420
|
+
const active = identities.pi.active;
|
|
11421
|
+
const piRoot = active?.packageRoot || "";
|
|
11422
|
+
const installRoot = piRoot ? nodeModulesParentForPackageRoot(piRoot) : "";
|
|
11423
|
+
const bundled = piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot);
|
|
11424
|
+
if (bundled && webuiDevServer) return { manager: "unknown", packageRoot: piRoot, ownerRoot: packageRoot, sourceCheckout: true };
|
|
11425
|
+
if (bundled) return { manager: "npm", packageRoot: piRoot, ownerRoot: installRoot, topLevel: true };
|
|
11426
|
+
if ((active?.source === "explicit" || active?.source === "path") && piRoot) {
|
|
11427
|
+
return { manager: "pi", packageRoot: piRoot, ownerRoot: piRoot, topLevel: true };
|
|
11428
|
+
}
|
|
11429
|
+
return { manager: "unknown", packageRoot: piRoot, ownerRoot: "", topLevel: true };
|
|
11430
|
+
}
|
|
11431
|
+
|
|
11432
|
+
async function createServerOwnedUpdatePlan(targets) {
|
|
11433
|
+
if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
|
|
11434
|
+
const identities = await canonicalUpdateIdentities({ forcePi: true });
|
|
11435
|
+
const transactionId = randomUUID();
|
|
11436
|
+
const statePaths = managedRuntimePaths(agentDir);
|
|
11437
|
+
const status = await getUpdateStatus({ force: true });
|
|
11438
|
+
for (const target of targets) {
|
|
11439
|
+
if (!status[target]?.checked || !status[target]?.latestVersion) throw makeHttpError(409, `${target} exact target metadata is unavailable.`);
|
|
11440
|
+
}
|
|
11441
|
+
const piRoot = identities.pi.active?.packageRoot || "";
|
|
11442
|
+
const bundledPi = Boolean(piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot));
|
|
11443
|
+
const requested = new Set(targets);
|
|
11444
|
+
const desiredPiVersion = requested.has("pi") ? status.pi.latestVersion : identities.pi.active?.version;
|
|
11445
|
+
const desiredWebuiVersion = requested.has("webui") ? status.webui.latestVersion : identities.webui.version;
|
|
11446
|
+
const separatePathPi = identities.pi.path?.canonicalId && identities.pi.path.canonicalId !== identities.pi.active?.canonicalId
|
|
11447
|
+
? identities.pi.path
|
|
11448
|
+
: null;
|
|
11449
|
+
const managedRuntimeRoot = path.join(statePaths.runtimesDir, `txn-${transactionId}`);
|
|
11450
|
+
const candidates = [];
|
|
11451
|
+
for (const target of targets) {
|
|
11452
|
+
const identity = target === "pi" ? identities.pi.active : identities.webui;
|
|
11453
|
+
if (!identity) throw makeHttpError(409, identities.pi.refusal?.message || `The ${target} runtime identity could not be verified.`);
|
|
11454
|
+
const managedRuntime = target === "webui" || (target === "pi" && bundledPi);
|
|
11455
|
+
candidates.push({
|
|
11456
|
+
id: target,
|
|
11457
|
+
kind: target,
|
|
11458
|
+
packageName: target === "pi" ? PI_CODING_AGENT_PACKAGE : WEBUI_PACKAGE,
|
|
11459
|
+
currentVersion: identity.version,
|
|
11460
|
+
identityId: identity.canonicalId,
|
|
11461
|
+
requested: "latest",
|
|
11462
|
+
registry: NPM_REGISTRY_URL,
|
|
11463
|
+
strategy: managedRuntime ? "managed-side-by-side" : "delegate-exact-pi",
|
|
11464
|
+
owner: updateOwnerForTarget(target, identities),
|
|
11465
|
+
exactTargetVersion: status[target].latestVersion,
|
|
11466
|
+
managedRuntime,
|
|
11467
|
+
runtimeRoot: managedRuntime ? managedRuntimeRoot : "",
|
|
11468
|
+
commandForVersion: async (version, registry) => {
|
|
11469
|
+
if (!managedRuntime) {
|
|
11470
|
+
const invocation = identity.invocation;
|
|
11471
|
+
if (!invocation?.command) throw new Error("The exact active Pi executable cannot own its update.");
|
|
11472
|
+
return { command: invocation.command, args: [...(invocation.args || []), "update", "--self"] };
|
|
11473
|
+
}
|
|
11474
|
+
const piVersion = target === "pi" ? version : desiredPiVersion;
|
|
11475
|
+
const webuiVersion = target === "webui" ? version : desiredWebuiVersion;
|
|
11476
|
+
const npm = resolvedNpmCommandForExactUpdate([
|
|
11477
|
+
"install", "--prefix", managedRuntimeRoot, "--ignore-scripts", "--no-save", "--package-lock=false", "--registry", registry,
|
|
11478
|
+
`${WEBUI_PACKAGE}@${webuiVersion}`,
|
|
11479
|
+
`${PI_CODING_AGENT_PACKAGE}@${piVersion}`,
|
|
11480
|
+
]);
|
|
11481
|
+
return { command: npm.command, args: npm.args };
|
|
11482
|
+
},
|
|
11483
|
+
});
|
|
11484
|
+
}
|
|
11485
|
+
|
|
11486
|
+
if (requested.has("pi") && requested.has("webui") && identities.pi.active) {
|
|
11487
|
+
const optionalStatuses = await optionalFeaturePackageStatuses(options.cwd);
|
|
11488
|
+
for (const feature of optionalStatuses.features) {
|
|
11489
|
+
if (!feature.configured || !feature.ready || !feature.installedVersion || !feature.installedRoot) continue;
|
|
11490
|
+
const latest = await checkLatestNpmPackageStatus(feature.packageName, feature.installedVersion);
|
|
11491
|
+
if (!latest.checked || !latest.updateAvailable || !latest.latestVersion) continue;
|
|
11492
|
+
const invocation = identities.pi.active.invocation;
|
|
11493
|
+
candidates.push({
|
|
11494
|
+
id: `optional:${feature.featureId}`,
|
|
11495
|
+
kind: "optional",
|
|
11496
|
+
packageName: feature.packageName,
|
|
11497
|
+
currentVersion: feature.installedVersion,
|
|
11498
|
+
identityId: identities.pi.active.canonicalId,
|
|
11499
|
+
requested: "latest",
|
|
11500
|
+
registry: NPM_REGISTRY_URL,
|
|
11501
|
+
strategy: "pi-owned-optional",
|
|
11502
|
+
owner: {
|
|
11503
|
+
manager: "pi",
|
|
11504
|
+
packageRoot: feature.installedRoot,
|
|
11505
|
+
ownerRoot: configuredAgentNpmRoot(),
|
|
11506
|
+
topLevel: true,
|
|
11507
|
+
optional: true,
|
|
11508
|
+
piOwned: true,
|
|
11509
|
+
},
|
|
11510
|
+
exactTargetVersion: latest.latestVersion,
|
|
11511
|
+
optionalFeature: true,
|
|
11512
|
+
featureId: feature.featureId,
|
|
11513
|
+
commandForVersion: async (version) => ({
|
|
11514
|
+
command: invocation.command,
|
|
11515
|
+
args: [...(invocation.args || []), "install", `npm:${feature.packageName}@${version}`],
|
|
11516
|
+
}),
|
|
11517
|
+
});
|
|
11518
|
+
}
|
|
11519
|
+
}
|
|
11520
|
+
|
|
11521
|
+
const plan = await createUpdatePlan({
|
|
11522
|
+
transactionId,
|
|
11523
|
+
registry: NPM_REGISTRY_URL,
|
|
11524
|
+
identities: [identities.pi.active, separatePathPi, identities.webui].filter(Boolean),
|
|
11525
|
+
candidates,
|
|
11526
|
+
resolveExactTarget: async ({ id, registry }) => {
|
|
11527
|
+
const candidate = candidates.find((item) => item.id === id);
|
|
11528
|
+
const targetVersion = candidate?.exactTargetVersion;
|
|
11529
|
+
if (!candidate || !targetVersion) throw new Error(`${id} exact target metadata is unavailable.`);
|
|
11530
|
+
let metadata = { delegatedExecutable: true };
|
|
11531
|
+
if (candidate.managedRuntime) {
|
|
11532
|
+
metadata = {
|
|
11533
|
+
managedRuntime: true,
|
|
11534
|
+
runtimeRoot: candidate.runtimeRoot,
|
|
11535
|
+
webuiVersion: id === "webui" ? targetVersion : desiredWebuiVersion,
|
|
11536
|
+
piVersion: id === "pi" ? targetVersion : desiredPiVersion,
|
|
11537
|
+
};
|
|
11538
|
+
} else if (candidate.optionalFeature) {
|
|
11539
|
+
metadata = { optionalFeature: true, featureId: candidate.featureId };
|
|
11540
|
+
}
|
|
11541
|
+
return { version: targetVersion, registry, metadata };
|
|
11542
|
+
},
|
|
11543
|
+
});
|
|
11544
|
+
await createUpdateJournal(agentDir, plan);
|
|
11545
|
+
return plan;
|
|
11546
|
+
}
|
|
11547
|
+
|
|
11548
|
+
async function activeIdentityForTarget(target) {
|
|
11549
|
+
const usesPiIdentity = target.id === "pi" || target.metadata?.optionalFeature === true;
|
|
11550
|
+
const identities = await canonicalUpdateIdentities({ forcePi: usesPiIdentity });
|
|
11551
|
+
return usesPiIdentity ? identities.pi.active : identities.webui;
|
|
11552
|
+
}
|
|
11553
|
+
|
|
11554
|
+
async function launchManagedActivation(journal, target, lock, outcome) {
|
|
11555
|
+
const runtimeRoot = path.resolve(target.metadata.runtimeRoot);
|
|
11556
|
+
const serverEntry = path.join(runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
|
|
11557
|
+
const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
|
|
11558
|
+
if (!probe.ok) throw new Error(probe.error || "Managed Web UI candidate probe failed.");
|
|
11559
|
+
if (target.metadata.webuiVersion !== packageJson.version) {
|
|
11560
|
+
const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-activation" });
|
|
11561
|
+
const featureIds = snapshot.features
|
|
11562
|
+
.filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
|
|
11563
|
+
.map(({ featureId }) => featureId);
|
|
11564
|
+
await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
|
|
11565
|
+
}
|
|
11566
|
+
const restore = await createRestoreFile(agentDir, await restorableTabsForRestart());
|
|
11567
|
+
const supervisorCursor = await prepareRpcSupervisorHandoff();
|
|
11568
|
+
const helper = path.join(packageRoot, "bin", "pi-webui-update-supervisor.mjs");
|
|
11569
|
+
const host = formatUrlHost(currentHost);
|
|
11570
|
+
const helperArgs = [
|
|
11571
|
+
helper,
|
|
11572
|
+
"--agent-dir", agentDir,
|
|
11573
|
+
"--runtime-root", runtimeRoot,
|
|
11574
|
+
"--server-entry", serverEntry,
|
|
11575
|
+
"--version", target.metadata.webuiVersion,
|
|
11576
|
+
"--pi-version", target.metadata.piVersion,
|
|
11577
|
+
"--outcome", outcome,
|
|
11578
|
+
"--transaction", journal.transactionId,
|
|
11579
|
+
"--url", `http://${host}:${options.port}/`,
|
|
11580
|
+
"--old-boot", bootIdentity,
|
|
11581
|
+
"--timeout-ms", String(UPDATE_HEALTH_GATE_MS),
|
|
11582
|
+
"--server-args", Buffer.from(JSON.stringify(process.argv.slice(2))).toString("base64url"),
|
|
11583
|
+
];
|
|
11584
|
+
const env = { ...process.env, PI_WEBUI_RESTORE_FILE: restore.file, PI_WEBUI_START_DELAY_MS: "300", PI_WEBUI_UPDATE_LOCK_TOKEN: lock.token };
|
|
11585
|
+
if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
|
|
11586
|
+
const child = spawn(process.execPath, helperArgs, { cwd: process.cwd(), env, detached: true, stdio: "ignore", windowsHide: true });
|
|
11587
|
+
await new Promise((resolve, reject) => {
|
|
11588
|
+
child.once("spawn", resolve);
|
|
11589
|
+
child.once("error", reject);
|
|
11590
|
+
});
|
|
11591
|
+
await transferInstallLock(lock, child.pid);
|
|
11592
|
+
child.unref();
|
|
11593
|
+
return { pid: child.pid, runtimeRoot, serverEntry };
|
|
11594
|
+
}
|
|
11595
|
+
|
|
11596
|
+
async function applyServerOwnedUpdate(transactionId, planDigest) {
|
|
11597
|
+
if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
|
|
11598
|
+
const journal = await readUpdateJournal(agentDir, transactionId);
|
|
11599
|
+
if (!journal) throw makeHttpError(404, "Update transaction was not found.");
|
|
11600
|
+
assertUpdatePlanDigest(journal.plan, planDigest);
|
|
11601
|
+
if (journal.state !== "planned") throw makeHttpError(409, `Update transaction is already ${journal.state}.`);
|
|
11602
|
+
piUpdateInProgress = true;
|
|
11603
|
+
let lock = null;
|
|
11604
|
+
let lockTransferred = false;
|
|
11605
|
+
let state = "planned";
|
|
11606
|
+
try {
|
|
11607
|
+
lock = await acquireInstallLock(agentDir);
|
|
11608
|
+
await transitionUpdateJournal(agentDir, transactionId, "applying");
|
|
11609
|
+
state = "applying";
|
|
11610
|
+
let installedManagedRuntime = "";
|
|
11611
|
+
const result = await executePlanTargets(journal.plan, {
|
|
11612
|
+
runner: async (command, args, { target }) => {
|
|
11613
|
+
if (target.metadata?.managedRuntime && installedManagedRuntime === target.metadata.runtimeRoot) {
|
|
11614
|
+
return { exitCode: 0, timedOut: false, error: "", stdout: "Managed runtime exact package set already staged by the preceding target.", stderr: "", skippedDuplicate: true };
|
|
11615
|
+
}
|
|
11616
|
+
const commandResult = await executeCommand(command, args, { cwd: target.metadata?.runtimeRoot || process.cwd(), timeoutMs: PACKAGE_UPDATE_TIMEOUT_MS, maxOutputLength: PACKAGE_UPDATE_OUTPUT_MAX_CHARS });
|
|
11617
|
+
if (target.metadata?.managedRuntime && commandResult.exitCode === 0 && !commandResult.timedOut && !commandResult.error) installedManagedRuntime = target.metadata.runtimeRoot;
|
|
11618
|
+
return commandResult;
|
|
11619
|
+
},
|
|
11620
|
+
beforeTarget: async (target) => {
|
|
11621
|
+
const active = await activeIdentityForTarget(target);
|
|
11622
|
+
assertPlanIdentity(target, active);
|
|
11623
|
+
if (target.metadata?.managedRuntime) {
|
|
11624
|
+
await mkdir(target.metadata.runtimeRoot, { recursive: true, mode: 0o700 });
|
|
11625
|
+
try {
|
|
11626
|
+
await writeFile(path.join(target.metadata.runtimeRoot, "package.json"), `${JSON.stringify({ private: true })}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
11627
|
+
} catch (error) {
|
|
11628
|
+
if (error?.code !== "EEXIST") throw error;
|
|
11629
|
+
}
|
|
11630
|
+
}
|
|
11631
|
+
},
|
|
11632
|
+
verifyTarget: async (target, command) => {
|
|
11633
|
+
if (target.metadata?.optionalFeature) {
|
|
11634
|
+
const [afterIdentity, afterStatus] = await Promise.all([
|
|
11635
|
+
activeIdentityForTarget(target),
|
|
11636
|
+
optionalFeaturePackageStatus(target.metadata.featureId, options.cwd),
|
|
11637
|
+
]);
|
|
11638
|
+
return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity, beforeVersion: target.currentVersion, afterVersion: afterStatus.ready ? afterStatus.installedVersion : "", command });
|
|
11639
|
+
}
|
|
11640
|
+
if (target.metadata?.managedRuntime) {
|
|
11641
|
+
const serverEntry = path.join(target.metadata.runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
|
|
11642
|
+
const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
|
|
11643
|
+
const afterVersion = target.id === "pi" ? probe.data?.piVersion : probe.data?.version;
|
|
11644
|
+
return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: { canonicalId: target.identityId }, beforeVersion: target.currentVersion, afterVersion: probe.ok ? afterVersion : "", command });
|
|
11645
|
+
}
|
|
11646
|
+
const after = await activeIdentityForTarget(target);
|
|
11647
|
+
return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: after, beforeVersion: target.currentVersion, afterVersion: after?.version, command });
|
|
11648
|
+
},
|
|
11649
|
+
});
|
|
11650
|
+
await transitionUpdateJournal(agentDir, transactionId, "verifying", { outcome: result.outcome, receipts: result.receipts });
|
|
11651
|
+
state = "verifying";
|
|
11652
|
+
const managedTargets = journal.plan.targets.filter((target) => target.metadata?.managedRuntime);
|
|
11653
|
+
const managedTargetsVerified = managedTargets.length > 0 && managedTargets.every((target) => result.receipts.find((receipt) => receipt.targetId === target.id)?.status === "success");
|
|
11654
|
+
const activationTarget = managedTargetsVerified ? managedTargets[0] : null;
|
|
11655
|
+
if (activationTarget) {
|
|
11656
|
+
const activation = await launchManagedActivation(journal, activationTarget, lock, result.outcome);
|
|
11657
|
+
lockTransferred = true;
|
|
11658
|
+
return { transactionId, planDigest, state: "activating", outcome: result.outcome, receipts: result.receipts, activation };
|
|
11659
|
+
}
|
|
11660
|
+
const terminal = result.outcome === "success" ? "success" : result.outcome === "partial" ? "partial" : "failed";
|
|
11661
|
+
const completed = await transitionUpdateJournal(agentDir, transactionId, terminal, { outcome: result.outcome, receipts: result.receipts });
|
|
11662
|
+
return completed;
|
|
11663
|
+
} catch (error) {
|
|
11664
|
+
if (state === "applying" || state === "verifying") await transitionUpdateJournal(agentDir, transactionId, "failed", { error: sanitizeComponentUpdateError(error), outcome: "failed" }).catch(() => {});
|
|
11665
|
+
throw error;
|
|
11666
|
+
} finally {
|
|
11667
|
+
if (lock && !lockTransferred) await releaseInstallLock(lock);
|
|
11668
|
+
piUpdateInProgress = false;
|
|
11669
|
+
invalidateCanonicalPiRuntime();
|
|
11670
|
+
updateStatusCache = null;
|
|
11671
|
+
updateStatusCacheAt = 0;
|
|
11672
|
+
}
|
|
11673
|
+
}
|
|
11674
|
+
|
|
10958
11675
|
function webuiComponentUpdateUnavailableReason() {
|
|
10959
11676
|
if (webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules")) {
|
|
10960
11677
|
return "Automatic Web UI update is unavailable from a source or development checkout.";
|
|
@@ -10995,8 +11712,17 @@ function basePackageUpdateStatus(packageName, currentVersion) {
|
|
|
10995
11712
|
};
|
|
10996
11713
|
}
|
|
10997
11714
|
|
|
11715
|
+
async function currentPiRuntimeVersion() {
|
|
11716
|
+
try {
|
|
11717
|
+
return (await canonicalUpdateIdentities({ forcePi: true })).pi.active?.version || "unknown";
|
|
11718
|
+
} catch {
|
|
11719
|
+
return "unknown";
|
|
11720
|
+
}
|
|
11721
|
+
}
|
|
11722
|
+
|
|
10998
11723
|
async function checkLatestPiReleaseStatus() {
|
|
10999
|
-
const
|
|
11724
|
+
const currentVersion = await currentPiRuntimeVersion();
|
|
11725
|
+
const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, currentVersion);
|
|
11000
11726
|
const skippedReason = updateChecksSkippedReason();
|
|
11001
11727
|
if (skippedReason) {
|
|
11002
11728
|
status.skipped = true;
|
|
@@ -11006,7 +11732,7 @@ async function checkLatestPiReleaseStatus() {
|
|
|
11006
11732
|
try {
|
|
11007
11733
|
const data = await fetchJsonWithTimeout(PI_LATEST_VERSION_URL, {
|
|
11008
11734
|
headers: {
|
|
11009
|
-
"User-Agent": `pi-webui/${packageJson.version} pi/${
|
|
11735
|
+
"User-Agent": `pi-webui/${packageJson.version} pi/${currentVersion || "unknown"}`,
|
|
11010
11736
|
accept: "application/json",
|
|
11011
11737
|
},
|
|
11012
11738
|
});
|
|
@@ -11074,464 +11800,28 @@ async function getUpdateStatus({ force = false } = {}) {
|
|
|
11074
11800
|
checkedAt: new Date(now).toISOString(),
|
|
11075
11801
|
updateAvailable,
|
|
11076
11802
|
restartRequired: true,
|
|
11077
|
-
|
|
11078
|
-
|
|
11079
|
-
allFallbackCommand: piUpdateCommandText({ all: true }),
|
|
11803
|
+
planEndpoint: "/api/update/plan",
|
|
11804
|
+
applyEndpoint: "/api/update/apply",
|
|
11080
11805
|
webuiDev: webuiDevServer,
|
|
11081
11806
|
pi: piStatus,
|
|
11082
11807
|
webui: webuiStatus,
|
|
11083
11808
|
packages: {
|
|
11084
11809
|
checked: false,
|
|
11085
|
-
note: "
|
|
11810
|
+
note: "Automatic updates use only persisted exact-target plans. Unsupported or unproven owners are reported as refusals and never scanned or mutated."
|
|
11086
11811
|
},
|
|
11087
11812
|
};
|
|
11088
11813
|
updateStatusCacheAt = now;
|
|
11089
11814
|
return updateStatusCache;
|
|
11090
11815
|
}
|
|
11091
11816
|
|
|
11092
|
-
|
|
11093
|
-
const
|
|
11094
|
-
|
|
11095
|
-
timeoutMs: 5000,
|
|
11096
|
-
maxOutputLength: 20_000,
|
|
11097
|
-
});
|
|
11098
|
-
if (result.exitCode !== 0 || result.timedOut || result.error) return false;
|
|
11099
|
-
return piUpdateHelpSupportsAll(`${result.stdout}\n${result.stderr}`);
|
|
11100
|
-
}
|
|
11101
|
-
|
|
11102
|
-
async function resolvePiUpdateCommands({ all = false } = {}) {
|
|
11103
|
-
let resolveCommand;
|
|
11104
|
-
let labelPrefix = "";
|
|
11105
|
-
let useBundledPi = false;
|
|
11106
|
-
|
|
11107
|
-
if (options.piBinExplicit) {
|
|
11108
|
-
resolveCommand = (args) => resolvePiCommand(args);
|
|
11109
|
-
} else {
|
|
11110
|
-
const selectedPi = resolveSelectedPiCommand(["--version"]);
|
|
11111
|
-
const pathPi = await runCommand(selectedPi.command, selectedPi.args, { timeoutMs: 3000, maxOutputLength: 4000 });
|
|
11112
|
-
if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
|
|
11113
|
-
resolveCommand = async (args) => resolveSelectedPiCommand(args);
|
|
11114
|
-
} else {
|
|
11115
|
-
resolveCommand = (args) => resolvePiCommand(args);
|
|
11116
|
-
labelPrefix = "bundled ";
|
|
11117
|
-
useBundledPi = true;
|
|
11118
|
-
}
|
|
11119
|
-
}
|
|
11120
|
-
|
|
11121
|
-
const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
|
|
11122
|
-
const steps = piUpdateCommandSteps({ all, supportsAll });
|
|
11123
|
-
return Promise.all(steps.map(async (step) => {
|
|
11124
|
-
const command = await resolveCommand(step.args);
|
|
11125
|
-
const selectedPiDirectory = useBundledPi || isNodeScriptCommand(options.piBin) ? "" : resolveCommandDirectory(options.piBin);
|
|
11126
|
-
const piInstallDirectory = selectedPiDirectory || resolveCommandDirectory(command.command);
|
|
11127
|
-
return {
|
|
11128
|
-
...command,
|
|
11129
|
-
label: `${labelPrefix}${step.label}`,
|
|
11130
|
-
timeoutMs: PI_UPDATE_TIMEOUT_MS,
|
|
11131
|
-
maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
|
|
11132
|
-
piInstallDirectory,
|
|
11133
|
-
env: piInstallDirectory ? prependedPathEnvironment(piInstallDirectory) : undefined,
|
|
11134
|
-
};
|
|
11135
|
-
}));
|
|
11136
|
-
}
|
|
11137
|
-
|
|
11138
|
-
function packageNodeModulesPath(nodeModulesRoot, packageName) {
|
|
11139
|
-
return path.join(nodeModulesRoot, ...String(packageName || "").split("/").filter(Boolean));
|
|
11140
|
-
}
|
|
11141
|
-
|
|
11142
|
-
function isWebuiOrPiPackageName(packageName) {
|
|
11143
|
-
const name = String(packageName || "").trim();
|
|
11144
|
-
if (OPTIONAL_FEATURE_PACKAGE_NAMES.has(name)) return false;
|
|
11145
|
-
return UPDATE_PACKAGE_NAMES.includes(name)
|
|
11146
|
-
|| /^@firstpick\/pi(?:-|$)/.test(name)
|
|
11147
|
-
|| /^@earendil-works\/pi(?:-|$)/.test(name)
|
|
11148
|
-
|| /^@firstpick\/.*webui/i.test(name);
|
|
11149
|
-
}
|
|
11150
|
-
|
|
11151
|
-
function declaredWebuiPiPackageNames(manifest) {
|
|
11152
|
-
const names = new Set();
|
|
11153
|
-
for (const section of [manifest?.dependencies, manifest?.optionalDependencies, manifest?.devDependencies]) {
|
|
11154
|
-
for (const packageName of Object.keys(section || {})) {
|
|
11155
|
-
if (isWebuiOrPiPackageName(packageName)) names.add(packageName);
|
|
11156
|
-
}
|
|
11157
|
-
}
|
|
11158
|
-
return [...names].sort();
|
|
11159
|
-
}
|
|
11160
|
-
|
|
11161
|
-
async function packagesPresentInNodeModulesRoot(nodeModulesRoot, packageNames = UPDATE_PACKAGE_NAMES) {
|
|
11162
|
-
const found = new Set();
|
|
11163
|
-
if (!nodeModulesRoot || !await directoryExists(nodeModulesRoot)) return [];
|
|
11164
|
-
for (const packageName of packageNames) {
|
|
11165
|
-
if (await directoryExists(packageNodeModulesPath(nodeModulesRoot, packageName))) found.add(packageName);
|
|
11166
|
-
}
|
|
11167
|
-
|
|
11168
|
-
let entries = [];
|
|
11169
|
-
try {
|
|
11170
|
-
entries = await readdir(nodeModulesRoot, { withFileTypes: true });
|
|
11171
|
-
} catch {
|
|
11172
|
-
return [...found].sort();
|
|
11173
|
-
}
|
|
11174
|
-
|
|
11175
|
-
for (const entry of entries) {
|
|
11176
|
-
if (!entry.isDirectory()) continue;
|
|
11177
|
-
if (entry.name.startsWith("@")) {
|
|
11178
|
-
let scopedEntries = [];
|
|
11179
|
-
try {
|
|
11180
|
-
scopedEntries = await readdir(path.join(nodeModulesRoot, entry.name), { withFileTypes: true });
|
|
11181
|
-
} catch {
|
|
11182
|
-
continue;
|
|
11183
|
-
}
|
|
11184
|
-
for (const scopedEntry of scopedEntries) {
|
|
11185
|
-
if (!scopedEntry.isDirectory()) continue;
|
|
11186
|
-
const packageName = `${entry.name}/${scopedEntry.name}`;
|
|
11187
|
-
if (isWebuiOrPiPackageName(packageName)) found.add(packageName);
|
|
11188
|
-
}
|
|
11189
|
-
continue;
|
|
11190
|
-
}
|
|
11191
|
-
if (isWebuiOrPiPackageName(entry.name)) found.add(entry.name);
|
|
11192
|
-
}
|
|
11193
|
-
return [...found].sort();
|
|
11194
|
-
}
|
|
11195
|
-
|
|
11196
|
-
async function packagesPresentInInstallPrefix(installRoot, packageNames = UPDATE_PACKAGE_NAMES) {
|
|
11197
|
-
const found = new Set();
|
|
11198
|
-
if (!installRoot || !await directoryExists(installRoot)) return [];
|
|
11199
|
-
const manifest = await readJsonFileIfExists(path.join(installRoot, "package.json"));
|
|
11200
|
-
for (const packageName of packageNames) {
|
|
11201
|
-
if (declaredDependencySpec(manifest, packageName) !== undefined) found.add(packageName);
|
|
11202
|
-
}
|
|
11203
|
-
for (const packageName of declaredWebuiPiPackageNames(manifest)) found.add(packageName);
|
|
11204
|
-
for (const packageName of await packagesPresentInNodeModulesRoot(path.join(installRoot, "node_modules"), packageNames)) {
|
|
11205
|
-
found.add(packageName);
|
|
11206
|
-
}
|
|
11207
|
-
return [...found].sort();
|
|
11208
|
-
}
|
|
11209
|
-
|
|
11210
|
-
function packageInstallSpecs(packageNames) {
|
|
11211
|
-
return packageNames.map((packageName) => `${packageName}@latest`);
|
|
11212
|
-
}
|
|
11213
|
-
|
|
11214
|
-
function resolvedNpmCommand(args, runtime = {}) {
|
|
11215
|
-
const invocation = resolveNpmCommandInvocation(args, runtime);
|
|
11216
|
-
return {
|
|
11217
|
-
command: invocation.command,
|
|
11218
|
-
args: invocation.args,
|
|
11219
|
-
displayCommand: formatCommandForDisplay(invocation.displayCommand, invocation.displayArgs),
|
|
11220
|
-
};
|
|
11221
|
-
}
|
|
11222
|
-
|
|
11223
|
-
function npmPrefixUpdateTask(label, installRoot, packageNames, npmRuntime = {}) {
|
|
11224
|
-
if (!packageNames.length) return null;
|
|
11225
|
-
const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)], npmRuntime);
|
|
11226
|
-
return {
|
|
11227
|
-
label,
|
|
11228
|
-
command: npmCommand.command,
|
|
11229
|
-
args: npmCommand.args,
|
|
11230
|
-
displayCommand: npmCommand.displayCommand,
|
|
11231
|
-
cwd: installRoot,
|
|
11232
|
-
};
|
|
11233
|
-
}
|
|
11234
|
-
|
|
11235
|
-
async function currentWebuiPackageUpdateTask(npmRuntime = {}) {
|
|
11236
|
-
const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
|
|
11237
|
-
if (sourceCheckout) {
|
|
11238
|
-
const manifest = await readJsonFileIfExists(path.join(packageRoot, "package.json"));
|
|
11239
|
-
const packages = declaredWebuiPiPackageNames(manifest);
|
|
11240
|
-
return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages, npmRuntime);
|
|
11241
|
-
}
|
|
11242
|
-
|
|
11243
|
-
const installRoot = nodeModulesParentForPackageRoot(packageRoot);
|
|
11244
|
-
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
11245
|
-
return npmPrefixUpdateTask("current Web UI install root", installRoot, packages, npmRuntime);
|
|
11246
|
-
}
|
|
11247
|
-
|
|
11248
|
-
async function agentPackageRootUpdateTask(npmRuntime = {}) {
|
|
11249
|
-
const installRoot = configuredAgentNpmRoot();
|
|
11250
|
-
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
11251
|
-
return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages, npmRuntime);
|
|
11252
|
-
}
|
|
11253
|
-
|
|
11254
|
-
async function optionalFeatureInstallRootUpdateTask(npmRuntime = {}) {
|
|
11255
|
-
const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
|
|
11256
|
-
if (!configuredRoot) return null;
|
|
11257
|
-
const installRoot = path.resolve(expandUserPath(configuredRoot));
|
|
11258
|
-
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
11259
|
-
return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages, npmRuntime);
|
|
11260
|
-
}
|
|
11261
|
-
|
|
11262
|
-
function activeProjectPackageRoots() {
|
|
11263
|
-
const roots = new Set();
|
|
11264
|
-
const add = (cwd) => {
|
|
11265
|
-
if (!cwd) return;
|
|
11266
|
-
roots.add(path.join(path.resolve(cwd), ".pi", "npm"));
|
|
11267
|
-
};
|
|
11268
|
-
add(options.cwd);
|
|
11269
|
-
for (const tab of tabs.values()) add(tab.cwd);
|
|
11270
|
-
for (const tab of closedRestorableTabs) add(tab.cwd);
|
|
11271
|
-
return [...roots].sort();
|
|
11272
|
-
}
|
|
11273
|
-
|
|
11274
|
-
async function projectPackageRootUpdateTasks(npmRuntime = {}) {
|
|
11275
|
-
const tasks = [];
|
|
11276
|
-
for (const installRoot of activeProjectPackageRoots()) {
|
|
11277
|
-
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
11278
|
-
const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages, npmRuntime);
|
|
11279
|
-
if (task) tasks.push(task);
|
|
11280
|
-
}
|
|
11281
|
-
return tasks;
|
|
11282
|
-
}
|
|
11283
|
-
|
|
11284
|
-
async function npmGlobalNodeModulesRoot(npmRuntime = {}) {
|
|
11285
|
-
const npmCommand = resolvedNpmCommand(["root", "-g"], npmRuntime);
|
|
11286
|
-
const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
|
|
11287
|
-
if (result.exitCode !== 0 || result.timedOut || result.error) return null;
|
|
11288
|
-
return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
|
|
11289
|
-
}
|
|
11290
|
-
|
|
11291
|
-
async function npmGlobalPackageRootUpdateTask(npmRuntime = {}) {
|
|
11292
|
-
const nodeModulesRoot = await npmGlobalNodeModulesRoot(npmRuntime);
|
|
11293
|
-
const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
|
|
11294
|
-
if (!packages.length) return null;
|
|
11295
|
-
const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)], npmRuntime);
|
|
11296
|
-
return {
|
|
11297
|
-
label: "global npm package root",
|
|
11298
|
-
command: npmCommand.command,
|
|
11299
|
-
args: npmCommand.args,
|
|
11300
|
-
displayCommand: npmCommand.displayCommand,
|
|
11301
|
-
cwd: nodeModulesRoot ? path.dirname(nodeModulesRoot) : process.cwd(),
|
|
11302
|
-
};
|
|
11303
|
-
}
|
|
11304
|
-
|
|
11305
|
-
async function bunGlobalNodeModulesRoots() {
|
|
11306
|
-
const available = await runCommand("bun", ["--version"], { timeoutMs: 3000, maxOutputLength: 2000 });
|
|
11307
|
-
if (available.exitCode !== 0 || available.timedOut || available.error) return [];
|
|
11308
|
-
|
|
11309
|
-
const roots = new Set([path.join(homedir(), ".bun", "install", "global", "node_modules")]);
|
|
11310
|
-
const binResult = await runCommand("bun", ["pm", "bin", "-g"], { timeoutMs: 3000, maxOutputLength: 8000 });
|
|
11311
|
-
if (binResult.exitCode === 0 && !binResult.timedOut && !binResult.error) {
|
|
11312
|
-
const binDir = binResult.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
|
|
11313
|
-
if (binDir) roots.add(path.join(path.dirname(binDir), "install", "global", "node_modules"));
|
|
11314
|
-
}
|
|
11315
|
-
return [...roots];
|
|
11316
|
-
}
|
|
11317
|
-
|
|
11318
|
-
async function bunGlobalPackageRootUpdateTask() {
|
|
11319
|
-
const packages = new Set();
|
|
11320
|
-
for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
|
|
11321
|
-
for (const packageName of await packagesPresentInNodeModulesRoot(nodeModulesRoot)) packages.add(packageName);
|
|
11322
|
-
}
|
|
11323
|
-
if (!packages.size) return null;
|
|
11324
|
-
return {
|
|
11325
|
-
label: "global Bun package root",
|
|
11326
|
-
command: "bun",
|
|
11327
|
-
args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", ...packageInstallSpecs([...packages])],
|
|
11328
|
-
cwd: homedir(),
|
|
11329
|
-
};
|
|
11330
|
-
}
|
|
11331
|
-
|
|
11332
|
-
async function currentWebuiComponentUpdateTask(npmRuntime = {}) {
|
|
11333
|
-
const unavailableReason = webuiComponentUpdateUnavailableReason();
|
|
11334
|
-
if (unavailableReason) throw makeHttpError(409, unavailableReason);
|
|
11335
|
-
|
|
11336
|
-
const normalizedPackageRoot = path.resolve(packageRoot);
|
|
11337
|
-
for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
|
|
11338
|
-
if (path.resolve(packageNodeModulesPath(nodeModulesRoot, WEBUI_PACKAGE)) !== normalizedPackageRoot) continue;
|
|
11339
|
-
return {
|
|
11340
|
-
label: "global Bun Web UI package",
|
|
11341
|
-
command: "bun",
|
|
11342
|
-
args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", `${WEBUI_PACKAGE}@latest`],
|
|
11343
|
-
cwd: homedir(),
|
|
11344
|
-
};
|
|
11345
|
-
}
|
|
11346
|
-
|
|
11347
|
-
const installRoot = nodeModulesParentForPackageRoot(packageRoot);
|
|
11348
|
-
return npmPrefixUpdateTask("current Web UI package", installRoot, [WEBUI_PACKAGE], npmRuntime);
|
|
11349
|
-
}
|
|
11350
|
-
|
|
11351
|
-
async function resolveComponentUpdateTasks(target) {
|
|
11352
|
-
if (target === "pi") return resolvePiUpdateCommands({ all: false });
|
|
11353
|
-
if (target === "webui") {
|
|
11354
|
-
let npmRuntime = {};
|
|
11355
|
-
try {
|
|
11356
|
-
const piTasks = await resolvePiUpdateCommands({ all: false });
|
|
11357
|
-
npmRuntime = {
|
|
11358
|
-
preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
|
|
11359
|
-
};
|
|
11360
|
-
} catch {
|
|
11361
|
-
recordEvent({ type: "webui_component_update_npm_resolution_fallback", target });
|
|
11362
|
-
}
|
|
11363
|
-
return [await currentWebuiComponentUpdateTask(npmRuntime)];
|
|
11364
|
-
}
|
|
11365
|
-
throw makeHttpError(400, "Unsupported component update target.");
|
|
11366
|
-
}
|
|
11367
|
-
|
|
11368
|
-
function updateTaskDisplay(task) {
|
|
11369
|
-
return task.displayCommand || formatCommandForDisplay(task.command, task.args || []);
|
|
11370
|
-
}
|
|
11371
|
-
|
|
11372
|
-
function uniqueUpdateTasks(tasks) {
|
|
11373
|
-
const unique = [];
|
|
11374
|
-
const seen = new Set();
|
|
11375
|
-
for (const task of tasks.filter(Boolean)) {
|
|
11376
|
-
const key = [task.command, JSON.stringify(task.args || []), task.cwd || ""].join("\u0000");
|
|
11377
|
-
if (seen.has(key)) continue;
|
|
11378
|
-
seen.add(key);
|
|
11379
|
-
unique.push(task);
|
|
11380
|
-
}
|
|
11381
|
-
return unique;
|
|
11382
|
-
}
|
|
11383
|
-
|
|
11384
|
-
async function resolveUpdateTasks({ all = false } = {}) {
|
|
11385
|
-
const piTasks = await resolvePiUpdateCommands({ all });
|
|
11386
|
-
if (!all) return uniqueUpdateTasks(piTasks);
|
|
11387
|
-
|
|
11388
|
-
const npmRuntime = {
|
|
11389
|
-
preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
|
|
11390
|
-
};
|
|
11391
|
-
const [
|
|
11392
|
-
currentWebuiTask,
|
|
11393
|
-
agentTask,
|
|
11394
|
-
optionalFeatureTask,
|
|
11395
|
-
projectTasks,
|
|
11396
|
-
globalNpmTask,
|
|
11397
|
-
globalBunTask,
|
|
11398
|
-
] = await Promise.all([
|
|
11399
|
-
currentWebuiPackageUpdateTask(npmRuntime),
|
|
11400
|
-
agentPackageRootUpdateTask(npmRuntime),
|
|
11401
|
-
optionalFeatureInstallRootUpdateTask(npmRuntime),
|
|
11402
|
-
projectPackageRootUpdateTasks(npmRuntime),
|
|
11403
|
-
npmGlobalPackageRootUpdateTask(npmRuntime),
|
|
11404
|
-
bunGlobalPackageRootUpdateTask(),
|
|
11405
|
-
]);
|
|
11406
|
-
|
|
11407
|
-
return uniqueUpdateTasks([
|
|
11408
|
-
...piTasks,
|
|
11409
|
-
currentWebuiTask,
|
|
11410
|
-
agentTask,
|
|
11411
|
-
optionalFeatureTask,
|
|
11412
|
-
...projectTasks,
|
|
11413
|
-
globalNpmTask,
|
|
11414
|
-
globalBunTask,
|
|
11415
|
-
]);
|
|
11416
|
-
}
|
|
11417
|
-
|
|
11418
|
-
function updateFailureDetails(result) {
|
|
11419
|
-
return [result.error, result.timedOut ? "timed out" : undefined, result.stderr?.trim(), result.stdout?.trim()].filter(Boolean).join("\n");
|
|
11420
|
-
}
|
|
11421
|
-
|
|
11422
|
-
async function runUpdateTask(task) {
|
|
11423
|
-
const command = updateTaskDisplay(task);
|
|
11424
|
-
recordEvent({ type: "webui_update_step_started", command });
|
|
11425
|
-
const result = await runCommand(task.command, task.args || [], {
|
|
11426
|
-
cwd: task.cwd || process.cwd(),
|
|
11427
|
-
timeoutMs: task.timeoutMs || PACKAGE_UPDATE_TIMEOUT_MS,
|
|
11428
|
-
maxOutputLength: task.maxOutputLength || PACKAGE_UPDATE_OUTPUT_MAX_CHARS,
|
|
11429
|
-
env: task.env,
|
|
11430
|
-
});
|
|
11431
|
-
const ok = result.exitCode === 0 && !result.timedOut && !result.error;
|
|
11432
|
-
if (!ok) {
|
|
11433
|
-
const details = updateFailureDetails(result);
|
|
11434
|
-
recordEvent({ type: "webui_update_step_failed", command, error: truncateStatusText(details || `exit code ${result.exitCode ?? "unknown"}`) });
|
|
11435
|
-
throw makeHttpError(500, truncateLongText(`Update step failed (${task.label || "package update"}): ${command}${details ? `\n${details}` : ""}`));
|
|
11436
|
-
}
|
|
11437
|
-
recordEvent({ type: "webui_update_step_completed", command });
|
|
11438
|
-
return {
|
|
11439
|
-
label: task.label || "package update",
|
|
11440
|
-
command,
|
|
11441
|
-
stdout: result.stdout,
|
|
11442
|
-
stderr: result.stderr,
|
|
11443
|
-
};
|
|
11444
|
-
}
|
|
11445
|
-
|
|
11446
|
-
function combinedUpdateOutput(results, field) {
|
|
11447
|
-
return results
|
|
11448
|
-
.map((result) => {
|
|
11449
|
-
const output = String(result?.[field] || "").trim();
|
|
11450
|
-
return output ? `# ${result.label}\n${output}` : "";
|
|
11451
|
-
})
|
|
11452
|
-
.filter(Boolean)
|
|
11453
|
-
.join("\n\n");
|
|
11454
|
-
}
|
|
11455
|
-
|
|
11456
|
-
function componentUpdateSuccessMessage(target) {
|
|
11457
|
-
if (target === "pi") return "Pi update completed. New or reloaded Pi sessions use the update.";
|
|
11458
|
-
return "Web UI update completed. Restart the Web UI to use the update.";
|
|
11459
|
-
}
|
|
11460
|
-
|
|
11461
|
-
async function persistOptionalFeaturePendingUpgrade() {
|
|
11462
|
-
optionalFeatureAuditCoordinator.assertIdle();
|
|
11463
|
-
const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-update" });
|
|
11464
|
-
const featureIds = snapshot.features
|
|
11465
|
-
.filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
|
|
11466
|
-
.map(({ featureId }) => featureId);
|
|
11467
|
-
await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
|
|
11468
|
-
}
|
|
11469
|
-
|
|
11470
|
-
async function runComponentUpdate(target) {
|
|
11471
|
-
try {
|
|
11472
|
-
if (target === "webui") await persistOptionalFeaturePendingUpgrade();
|
|
11473
|
-
const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
|
|
11474
|
-
if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
|
|
11475
|
-
const command = updateTasks.map(updateTaskDisplay).join(" && ");
|
|
11476
|
-
recordEvent({ type: "webui_component_update_started", target, command });
|
|
11477
|
-
for (const task of updateTasks) await runUpdateTask(task);
|
|
11478
|
-
updateStatusCache = null;
|
|
11479
|
-
updateStatusCacheAt = 0;
|
|
11480
|
-
componentUpdateState.succeed(target, componentUpdateSuccessMessage(target));
|
|
11481
|
-
recordEvent({ type: "webui_component_update_completed", target, command });
|
|
11482
|
-
} catch (error) {
|
|
11483
|
-
updateStatusCache = null;
|
|
11484
|
-
updateStatusCacheAt = 0;
|
|
11485
|
-
componentUpdateState.fail(target, error);
|
|
11486
|
-
recordEvent({ type: "webui_component_update_failed", target, error: componentUpdateState.get(target).error });
|
|
11487
|
-
}
|
|
11488
|
-
}
|
|
11489
|
-
|
|
11490
|
-
function startComponentUpdate(target) {
|
|
11491
|
-
if (piUpdateInProgress || componentUpdateState.hasRunning()) throw makeHttpError(409, "Another privileged update is already running.");
|
|
11492
|
-
const unavailableReason = target === "webui" ? webuiComponentUpdateUnavailableReason() : "";
|
|
11493
|
-
if (unavailableReason) throw makeHttpError(409, unavailableReason);
|
|
11494
|
-
componentUpdateState.begin(target);
|
|
11495
|
-
recordEvent({ type: "webui_component_update_accepted", target });
|
|
11496
|
-
setImmediate(() => { void runComponentUpdate(target); });
|
|
11497
|
-
return componentUpdateState.get(target);
|
|
11817
|
+
function resolvedNpmCommandForExactUpdate(args) {
|
|
11818
|
+
const invocation = resolveNpmCommandInvocation(args);
|
|
11819
|
+
return { command: invocation.command, args: invocation.args };
|
|
11498
11820
|
}
|
|
11499
11821
|
|
|
11500
|
-
|
|
11501
|
-
|
|
11502
|
-
|
|
11503
|
-
piUpdateInProgress = true;
|
|
11504
|
-
let restartPrepared = false;
|
|
11505
|
-
try {
|
|
11506
|
-
if (all) await persistOptionalFeaturePendingUpgrade();
|
|
11507
|
-
const restorableTabs = await restorableTabsForRestart();
|
|
11508
|
-
const updateTasks = await resolveUpdateTasks({ all });
|
|
11509
|
-
if (!updateTasks.length) throw makeHttpError(500, "No Pi update command could be resolved.");
|
|
11510
|
-
const command = updateTasks.map(updateTaskDisplay).join(" && ");
|
|
11511
|
-
const updateLabel = all ? "Pi and package updates" : "Pi update";
|
|
11512
|
-
recordEvent({ type: "webui_update_started", command, updateAll: all, restorableTabCount: restorableTabs.length });
|
|
11513
|
-
const results = [];
|
|
11514
|
-
for (const task of updateTasks) results.push(await runUpdateTask(task));
|
|
11515
|
-
|
|
11516
|
-
updateStatusCache = null;
|
|
11517
|
-
updateStatusCacheAt = 0;
|
|
11518
|
-
const supervisorCursor = await prepareRpcSupervisorHandoff();
|
|
11519
|
-
const child = spawnRestartServer(restorableTabs, supervisorCursor);
|
|
11520
|
-
restartPrepared = true;
|
|
11521
|
-
recordEvent({ type: "webui_update_restarting", command, updateAll: all, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
|
|
11522
|
-
return {
|
|
11523
|
-
message: `${updateLabel} completed. Pi Web UI is restarting.`,
|
|
11524
|
-
command,
|
|
11525
|
-
commands: results.map((result) => ({ label: result.label, command: result.command })),
|
|
11526
|
-
stdout: combinedUpdateOutput(results, "stdout"),
|
|
11527
|
-
stderr: combinedUpdateOutput(results, "stderr"),
|
|
11528
|
-
webuiPid: process.pid,
|
|
11529
|
-
nextWebuiPid: child.pid,
|
|
11530
|
-
restorableTabCount: restorableTabs.length,
|
|
11531
|
-
};
|
|
11532
|
-
} finally {
|
|
11533
|
-
if (!restartPrepared) piUpdateInProgress = false;
|
|
11534
|
-
}
|
|
11822
|
+
function exactUpdatePathInside(root, candidate) {
|
|
11823
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
11824
|
+
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
11535
11825
|
}
|
|
11536
11826
|
|
|
11537
11827
|
function rememberClosedRestorableTab(tab, state = null) {
|
|
@@ -13301,9 +13591,15 @@ async function moveFileSystemEntryData(tab, body = {}) {
|
|
|
13301
13591
|
}
|
|
13302
13592
|
|
|
13303
13593
|
function defaultEditorCommand(targetPath) {
|
|
13594
|
+
if (process.env.PI_WEBUI_OPEN_COMMAND) {
|
|
13595
|
+
const override = process.env.PI_WEBUI_OPEN_COMMAND;
|
|
13596
|
+
return [".js", ".cjs", ".mjs"].includes(path.extname(override).toLowerCase())
|
|
13597
|
+
? { command: process.execPath, args: [override, targetPath] }
|
|
13598
|
+
: { command: override, args: [targetPath] };
|
|
13599
|
+
}
|
|
13304
13600
|
if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
|
|
13305
13601
|
if (platform() === "darwin") return { command: "open", args: [targetPath] };
|
|
13306
|
-
return { command:
|
|
13602
|
+
return { command: "xdg-open", args: [targetPath] };
|
|
13307
13603
|
}
|
|
13308
13604
|
|
|
13309
13605
|
function firstCommandOutputLine(value = "") {
|
|
@@ -14901,6 +15197,33 @@ const server = createServer(async (req, res) => {
|
|
|
14901
15197
|
return;
|
|
14902
15198
|
}
|
|
14903
15199
|
|
|
15200
|
+
const samplingParametersRoute = /^\/api\/tabs\/([^/]+)\/sampling-parameters$/.exec(url.pathname);
|
|
15201
|
+
if (samplingParametersRoute && (req.method === "GET" || req.method === "PUT")) {
|
|
15202
|
+
const tabId = decodeURIComponent(samplingParametersRoute[1]);
|
|
15203
|
+
const tab = tabs.get(tabId);
|
|
15204
|
+
if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${tabId}`);
|
|
15205
|
+
if (req.method === "GET") {
|
|
15206
|
+
sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "sampling-state") }, { "cache-control": "private, no-store" });
|
|
15207
|
+
return;
|
|
15208
|
+
}
|
|
15209
|
+
let samplingParams;
|
|
15210
|
+
try {
|
|
15211
|
+
samplingParams = await readJsonBody(req, {
|
|
15212
|
+
limitBytes: SAMPLING_PARAMS_HTTP_MAX_BYTES,
|
|
15213
|
+
emptyError: "Sampling parameters body must be a JSON object.",
|
|
15214
|
+
});
|
|
15215
|
+
} catch (error) {
|
|
15216
|
+
if (error instanceof SyntaxError) throw makeHttpError(400, "Sampling parameters body must be valid JSON.");
|
|
15217
|
+
throw error;
|
|
15218
|
+
}
|
|
15219
|
+
const action = samplingParams && typeof samplingParams === "object" && !Array.isArray(samplingParams) && Object.keys(samplingParams).length === 0
|
|
15220
|
+
? "sampling-reset"
|
|
15221
|
+
: "sampling-set";
|
|
15222
|
+
const payload = action === "sampling-set" ? { samplingParams } : {};
|
|
15223
|
+
sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, action, payload) }, { "cache-control": "private, no-store" });
|
|
15224
|
+
return;
|
|
15225
|
+
}
|
|
15226
|
+
|
|
14904
15227
|
if (url.pathname === "/api/workspaces" && req.method === "GET") {
|
|
14905
15228
|
sendJson(res, 200, { ok: true, data: { workspaces: await listWebuiWorkspaces() } });
|
|
14906
15229
|
return;
|
|
@@ -15119,6 +15442,7 @@ const server = createServer(async (req, res) => {
|
|
|
15119
15442
|
const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
|
|
15120
15443
|
sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
|
|
15121
15444
|
ok: optionalFeatureStartupReady,
|
|
15445
|
+
bootIdentity,
|
|
15122
15446
|
startupPhase: optionalFeatureAuditCoordinator.current().phase,
|
|
15123
15447
|
webuiVersion: status.webuiVersion,
|
|
15124
15448
|
piVersion: status.piVersion,
|
|
@@ -15138,7 +15462,7 @@ const server = createServer(async (req, res) => {
|
|
|
15138
15462
|
}
|
|
15139
15463
|
|
|
15140
15464
|
if (url.pathname === "/api/pi-release-notes" && req.method === "GET") {
|
|
15141
|
-
sendJson(res, 200, { ok: true, data: await
|
|
15465
|
+
sendJson(res, 200, { ok: true, data: await piReleaseNotes() }, { "cache-control": "private, no-store" });
|
|
15142
15466
|
return;
|
|
15143
15467
|
}
|
|
15144
15468
|
|
|
@@ -15188,7 +15512,25 @@ const server = createServer(async (req, res) => {
|
|
|
15188
15512
|
}
|
|
15189
15513
|
|
|
15190
15514
|
if (url.pathname === "/api/themes" && req.method === "GET") {
|
|
15191
|
-
|
|
15515
|
+
const tab = tabs.size ? getRequestedTab(req, url) : null;
|
|
15516
|
+
sendJson(res, 200, { ok: true, data: await readThemeCatalog(tab) });
|
|
15517
|
+
return;
|
|
15518
|
+
}
|
|
15519
|
+
|
|
15520
|
+
if (url.pathname === "/api/themes/custom" && req.method === "POST") {
|
|
15521
|
+
requireLocalhostRoute(req, url.pathname);
|
|
15522
|
+
requireCustomThemeJsonRequest(req);
|
|
15523
|
+
let body;
|
|
15524
|
+
try {
|
|
15525
|
+
body = await readJsonBody(req, { limitBytes: CUSTOM_THEME_BODY_LIMIT_BYTES });
|
|
15526
|
+
} catch (error) {
|
|
15527
|
+
if (error instanceof SyntaxError) throw themeHttpError(400, "THEME_JSON_INVALID", "Custom theme save body contains malformed JSON.");
|
|
15528
|
+
throw error;
|
|
15529
|
+
}
|
|
15530
|
+
const tab = getRequestedTab(req, url);
|
|
15531
|
+
const request = validateCustomThemeSaveBody(body);
|
|
15532
|
+
const data = await saveCustomTheme(tab, request);
|
|
15533
|
+
sendJson(res, data.created ? 201 : 200, { ok: true, data });
|
|
15192
15534
|
return;
|
|
15193
15535
|
}
|
|
15194
15536
|
|
|
@@ -15248,33 +15590,70 @@ const server = createServer(async (req, res) => {
|
|
|
15248
15590
|
requireLocalhostRoute(req, url.pathname);
|
|
15249
15591
|
const restorableTabs = await restorableTabsForRestart();
|
|
15250
15592
|
const supervisorCursor = await prepareRpcSupervisorHandoff();
|
|
15251
|
-
const child = spawnRestartServer(restorableTabs, supervisorCursor);
|
|
15593
|
+
const child = await spawnRestartServer(restorableTabs, supervisorCursor);
|
|
15252
15594
|
sendJson(res, 200, { ok: true, message: "Pi Web UI restarting", webuiPid: process.pid, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
|
|
15253
15595
|
setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
|
|
15254
15596
|
return;
|
|
15255
15597
|
}
|
|
15256
15598
|
|
|
15257
|
-
if (url.pathname === "/api/
|
|
15599
|
+
if (url.pathname === "/api/update/plan" && req.method === "POST") {
|
|
15258
15600
|
requireLocalhostRoute(req, url.pathname);
|
|
15259
|
-
const
|
|
15260
|
-
const validation = validateComponentUpdateRequest(body);
|
|
15601
|
+
const validation = validateUpdatePlanRequest(await readJsonBody(req));
|
|
15261
15602
|
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
15262
|
-
|
|
15263
|
-
sendJson(res,
|
|
15603
|
+
const plan = await createServerOwnedUpdatePlan(validation.targets);
|
|
15604
|
+
sendJson(res, 201, { ok: true, data: { plan } });
|
|
15264
15605
|
return;
|
|
15265
15606
|
}
|
|
15266
15607
|
|
|
15267
|
-
if (url.pathname === "/api/update" && req.method === "POST") {
|
|
15608
|
+
if (url.pathname === "/api/update/apply" && req.method === "POST") {
|
|
15268
15609
|
requireLocalhostRoute(req, url.pathname);
|
|
15269
|
-
const
|
|
15270
|
-
|
|
15271
|
-
const
|
|
15272
|
-
|
|
15273
|
-
|
|
15274
|
-
|
|
15610
|
+
const validation = validateUpdateApplyRequest(await readJsonBody(req));
|
|
15611
|
+
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
15612
|
+
const data = await applyServerOwnedUpdate(validation.transactionId, validation.planDigest);
|
|
15613
|
+
sendJson(res, data.state === "activating" ? 202 : 200, { ok: true, data });
|
|
15614
|
+
if (data.state === "activating") setTimeout(() => { void shutdown("managed Web UI activation", { preserveSessions: true }); }, 20).unref();
|
|
15615
|
+
return;
|
|
15616
|
+
}
|
|
15617
|
+
|
|
15618
|
+
const updateTransactionRoute = url.pathname.match(/^\/api\/update\/transactions\/([A-Za-z0-9._-]{1,128})$/);
|
|
15619
|
+
if (updateTransactionRoute && req.method === "GET") {
|
|
15620
|
+
requireLocalhost(req, "Viewing update transactions is only allowed from localhost");
|
|
15621
|
+
const journal = await readUpdateJournal(agentDir, updateTransactionRoute[1]);
|
|
15622
|
+
if (!journal) throw makeHttpError(404, "Update transaction was not found.");
|
|
15623
|
+
sendJson(res, 200, { ok: true, data: journal });
|
|
15275
15624
|
return;
|
|
15276
15625
|
}
|
|
15277
15626
|
|
|
15627
|
+
if (url.pathname === "/api/update/rollback" && req.method === "POST") {
|
|
15628
|
+
requireLocalhostRoute(req, url.pathname);
|
|
15629
|
+
const validation = validateUpdateApplyRequest(await readJsonBody(req));
|
|
15630
|
+
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
15631
|
+
const journal = await readUpdateJournal(agentDir, validation.transactionId);
|
|
15632
|
+
if (!journal) throw makeHttpError(404, "Update transaction was not found.");
|
|
15633
|
+
assertUpdatePlanDigest(journal.plan, validation.planDigest);
|
|
15634
|
+
const webuiTarget = journal.plan.targets.find((target) => target.id === "webui");
|
|
15635
|
+
if (journal.state !== "success" || !webuiTarget) throw makeHttpError(409, "Only a successfully activated Web UI transaction can be rolled back manually.");
|
|
15636
|
+
const currentPointer = await readRuntimePointer(agentDir, "current");
|
|
15637
|
+
if (!currentPointer || currentPointer.version !== webuiTarget.targetVersion) throw makeHttpError(409, "The active managed runtime no longer matches this rollback receipt.");
|
|
15638
|
+
const lock = await acquireInstallLock(agentDir);
|
|
15639
|
+
let pointer;
|
|
15640
|
+
let child;
|
|
15641
|
+
try {
|
|
15642
|
+
pointer = await rollbackRuntimePointer(agentDir);
|
|
15643
|
+
child = await spawnRestartServer(await restorableTabsForRestart(), await prepareRpcSupervisorHandoff());
|
|
15644
|
+
await transitionUpdateJournal(agentDir, journal.transactionId, "rolled-back", { outcome: "rolled-back", rollback: { manual: true, at: new Date().toISOString(), pointer } });
|
|
15645
|
+
} finally {
|
|
15646
|
+
await releaseInstallLock(lock);
|
|
15647
|
+
}
|
|
15648
|
+
sendJson(res, 202, { ok: true, data: { outcome: "rolled-back", pointer, nextWebuiPid: child.pid } });
|
|
15649
|
+
setTimeout(() => { void shutdown("manual update rollback", { preserveSessions: true }); }, 20).unref();
|
|
15650
|
+
return;
|
|
15651
|
+
}
|
|
15652
|
+
|
|
15653
|
+
if ((url.pathname === "/api/component-update" || url.pathname === "/api/update") && req.method === "POST") {
|
|
15654
|
+
throw makeHttpError(410, "Legacy update mutation is disabled. Create an exact server-owned plan and apply its transactionId plus planDigest.");
|
|
15655
|
+
}
|
|
15656
|
+
|
|
15278
15657
|
if (url.pathname === "/api/shutdown" && req.method === "POST") {
|
|
15279
15658
|
requireLocalhostRoute(req, url.pathname);
|
|
15280
15659
|
sendJson(res, 200, { ok: true, message: "Pi Web UI shutting down", webuiPid: process.pid });
|
|
@@ -15760,8 +16139,8 @@ const server = createServer(async (req, res) => {
|
|
|
15760
16139
|
}
|
|
15761
16140
|
|
|
15762
16141
|
if (url.pathname === "/api/safety-guard/config" && req.method === "GET") {
|
|
15763
|
-
getRequestedTab(req, url);
|
|
15764
|
-
sendJson(res, 200, { ok: true, data: await safetyGuardConfigData() });
|
|
16142
|
+
const tab = getRequestedTab(req, url);
|
|
16143
|
+
sendJson(res, 200, { ok: true, data: await safetyGuardConfigData(tab) });
|
|
15765
16144
|
return;
|
|
15766
16145
|
}
|
|
15767
16146
|
|
|
@@ -15769,7 +16148,7 @@ const server = createServer(async (req, res) => {
|
|
|
15769
16148
|
const body = await readJsonBody(req);
|
|
15770
16149
|
const tab = getRequestedTab(req, url, body);
|
|
15771
16150
|
ensureNaturalConversationRouteAllowed(tab, "safety guard setup changes are blocked");
|
|
15772
|
-
sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(body) });
|
|
16151
|
+
sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(tab, body) });
|
|
15773
16152
|
return;
|
|
15774
16153
|
}
|
|
15775
16154
|
|
|
@@ -15928,7 +16307,7 @@ const server = createServer(async (req, res) => {
|
|
|
15928
16307
|
const tab = getRequestedTab(req, url, body);
|
|
15929
16308
|
ensureNaturalConversationRouteAllowed(tab, "git pull is blocked");
|
|
15930
16309
|
try {
|
|
15931
|
-
sendJson(res, 200, await pullGitChanges(tab.cwd));
|
|
16310
|
+
sendJson(res, 200, await pullGitChanges(tab.cwd, { remote: body?.remote }));
|
|
15932
16311
|
} catch (error) {
|
|
15933
16312
|
sendJson(res, 200, { ok: false, error: sanitizeError(error) });
|
|
15934
16313
|
}
|
|
@@ -16183,6 +16562,7 @@ const server = createServer(async (req, res) => {
|
|
|
16183
16562
|
});
|
|
16184
16563
|
|
|
16185
16564
|
server.on("error", (error) => {
|
|
16565
|
+
if (error?.code === "EADDRINUSE" && !server.listening) return;
|
|
16186
16566
|
if (networkRebindInProgress) {
|
|
16187
16567
|
console.error("Web UI network rebind failed:", sanitizeError(error));
|
|
16188
16568
|
return;
|
|
@@ -16199,19 +16579,7 @@ function sweepWebuiTempArtifacts() {
|
|
|
16199
16579
|
sweepWebuiTempArtifacts();
|
|
16200
16580
|
setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
|
|
16201
16581
|
|
|
16202
|
-
await
|
|
16203
|
-
const onError = (error) => {
|
|
16204
|
-
server.off("listening", onListening);
|
|
16205
|
-
reject(error);
|
|
16206
|
-
};
|
|
16207
|
-
const onListening = () => {
|
|
16208
|
-
server.off("error", onError);
|
|
16209
|
-
resolve();
|
|
16210
|
-
};
|
|
16211
|
-
server.once("error", onError);
|
|
16212
|
-
server.once("listening", onListening);
|
|
16213
|
-
server.listen(options.port, currentHost);
|
|
16214
|
-
});
|
|
16582
|
+
await listenWithRetry(server, { port: options.port, host: currentHost, attempts: 40, initialDelayMs: 250 });
|
|
16215
16583
|
|
|
16216
16584
|
const urlHost = formatUrlHost(currentHost);
|
|
16217
16585
|
console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
|
|
@@ -16220,6 +16588,17 @@ if (!isLocalHost(currentHost)) {
|
|
|
16220
16588
|
console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
|
|
16221
16589
|
}
|
|
16222
16590
|
|
|
16591
|
+
await sweepRestoreFiles(agentDir).catch(() => {});
|
|
16592
|
+
await collectManagedRuntimes(agentDir).catch((error) => console.warn(`managed runtime retention failed: ${sanitizeError(error)}`));
|
|
16593
|
+
if (!process.env.PI_WEBUI_ACTIVATION_TRANSACTION) {
|
|
16594
|
+
await reconcileInterruptedUpdates(agentDir, {
|
|
16595
|
+
recover: async (journal) => {
|
|
16596
|
+
if (journal.state !== "activating") return { state: "failed", error: "Update was interrupted before verification completed." };
|
|
16597
|
+
const pointer = await rollbackRuntimePointer(agentDir);
|
|
16598
|
+
return { state: "rolled-back", pointer, error: "Activation was interrupted; the previous runtime pointer was restored." };
|
|
16599
|
+
},
|
|
16600
|
+
}).catch((error) => console.warn(`update reconciliation failed: ${sanitizeError(error)}`));
|
|
16601
|
+
}
|
|
16223
16602
|
const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
|
|
16224
16603
|
if (options.migrationDryRun) {
|
|
16225
16604
|
console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);
|