@firstpick/pi-package-webui 0.10.7 → 0.10.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT.md +95 -15
- package/README.md +1 -1
- package/TECHNICAL.md +6 -4
- package/bin/pi-webui-launcher.mjs +6 -3
- package/bin/pi-webui-native-update-guardian.mjs +37 -0
- package/bin/pi-webui-native-update-runner.mjs +148 -0
- package/bin/pi-webui-rpc-supervisor.mjs +85 -10
- package/bin/pi-webui-update-context.mjs +83 -0
- package/bin/pi-webui.mjs +537 -339
- package/lib/component-update-state.mjs +4 -4
- package/lib/rpc-supervisor-client.mjs +4 -0
- package/lib/rpc-supervisor-protocol.mjs +17 -4
- package/lib/update/coordination.mjs +207 -0
- package/lib/update/discovery.mjs +58 -0
- package/lib/update/migration.mjs +115 -0
- package/lib/update/native-jobs.mjs +215 -0
- package/lib/update/native-targets.mjs +81 -0
- package/lib/update/path-pi.mjs +76 -0
- package/lib/update/supervisor.mjs +50 -29
- package/lib/update/verification.mjs +18 -0
- package/lib/update-commands.mjs +17 -27
- package/package.json +2 -2
- package/public/app.js +170 -201
- package/public/index.html +5 -3
- package/public/styles.css +29 -1
- package/tests/browser/control-deck-component-updates.spec.mjs +90 -141
- package/tests/browser/update-reconnect.spec.mjs +37 -1
- package/tests/component-update-api-static.test.mjs +13 -11
- package/tests/control-deck-component-updates-static.test.mjs +25 -25
- package/tests/cwd-footer-reliability-static.test.mjs +4 -1
- package/tests/http-endpoints-harness.test.mjs +32 -9
- package/tests/mobile-static.test.mjs +9 -6
- package/tests/native-update-discovery.test.mjs +69 -0
- package/tests/native-update-lifecycle.test.mjs +92 -0
- package/tests/native-update-shell-survival.test.mjs +68 -0
- package/tests/native-update-verification.test.mjs +17 -0
- package/tests/rpc-supervisor-host.test.mjs +63 -1
- package/tests/rpc-supervisor-protocol.test.mjs +8 -0
- package/tests/run-all.mjs +6 -2
- package/tests/update-api-harness.test.mjs +57 -50
- package/tests/update-commands.test.mjs +29 -15
- package/tests/update-executor-process-tree-harness.test.mjs +84 -1
- package/tests/update-journal-harness.test.mjs +9 -1
- package/tests/update-lock-multiprocess-harness.test.mjs +60 -1
- package/tests/update-owners.test.mjs +32 -0
- package/tests/update-plan.test.mjs +110 -0
- package/tests/update-resolver.test.mjs +36 -0
- package/tests/update-supervisor-harness.test.mjs +74 -1
- package/tests/update-tab-restore-harness.test.mjs +9 -2
- package/bin/pi-webui-update-supervisor.mjs +0 -86
package/bin/pi-webui.mjs
CHANGED
|
@@ -72,14 +72,18 @@ import {
|
|
|
72
72
|
isWindowsDriveRoot,
|
|
73
73
|
windowsDrivesPickerData,
|
|
74
74
|
} from "../lib/windows-drive-roots.mjs";
|
|
75
|
-
import { ComponentUpdateState, sanitizeComponentUpdateError,
|
|
76
|
-
import { resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity } from "../lib/update/resolver.mjs";
|
|
77
|
-
import {
|
|
78
|
-
import {
|
|
79
|
-
import {
|
|
80
|
-
import {
|
|
81
|
-
import {
|
|
82
|
-
import {
|
|
75
|
+
import { ComponentUpdateState, sanitizeComponentUpdateError, validateUpdateApplyRequest, validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
|
|
76
|
+
import { parseRuntimeVersion, resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity } from "../lib/update/resolver.mjs";
|
|
77
|
+
import { resolveUpdatePathPi } from "../lib/update/path-pi.mjs";
|
|
78
|
+
import { npmGlobalWebuiTarget, piUserWebuiTarget, selfUpdateCommand } from "../lib/update/native-targets.mjs";
|
|
79
|
+
import { acknowledgeUpdateFence, affectedParticipants, assertEffectAdmission, createUpdateAdmissionCounter, effectLockForRoot, persistSharedJob, readSharedJob, registerUpdateParticipant, releaseEffectLocks, sharedUpdateRoot, unregisterUpdateParticipant } from "../lib/update/coordination.mjs";
|
|
80
|
+
import { affectedActivePiDependency, createNativeUpdatePlan, inspectNativeJob, launchNativeUpdate, validateNativePlan } from "../lib/update/native-jobs.mjs";
|
|
81
|
+
import { discoverNativeJobs, nativeJobBlocksUpdates, publicNativeJob } from "../lib/update/discovery.mjs";
|
|
82
|
+
import { assertRestoredPiState, nativeUpdateOutcome } from "../lib/update/verification.mjs";
|
|
83
|
+
import { frozenUpdateEnvironment, readUpdateContext } from "./pi-webui-update-context.mjs";
|
|
84
|
+
import { packageOwnerRoot } from "../lib/update/package-layout.mjs";
|
|
85
|
+
import { updateStatePaths } from "../lib/update/journal.mjs";
|
|
86
|
+
import { createRestoreFile, listenWithRetry, probeStartupRestore, readRestoreFileOnce, sweepRestoreFiles } from "../lib/update/supervisor.mjs";
|
|
83
87
|
import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
|
|
84
88
|
import {
|
|
85
89
|
OptionalFeatureAuditCoordinator,
|
|
@@ -779,7 +783,7 @@ async function piReleaseNotes() {
|
|
|
779
783
|
? updateStatusCache.pi
|
|
780
784
|
: null;
|
|
781
785
|
const piStatus = cachedUpdateStatus || await checkLatestPiReleaseStatus();
|
|
782
|
-
const currentVersion = String(piStatus?.currentVersion || piPackageJson.version || "").trim().replace(/^v/i, "");
|
|
786
|
+
const currentVersion = String(piStatus?.currentVersion || piStatus?.activeRuntimeVersion || piPackageJson.version || "").trim().replace(/^v/i, "");
|
|
783
787
|
const latestVersion = String(piStatus?.latestVersion || "").trim().replace(/^v/i, "");
|
|
784
788
|
const release = piRelease(piStatus?.updateAvailable && parsePackageVersion(latestVersion) ? latestVersion : currentVersion);
|
|
785
789
|
if (piReleaseNotesCache?.tagName === release.tagName) return piReleaseNotesCache;
|
|
@@ -856,6 +860,26 @@ function mirrorPiStderr(text, onFailure) {
|
|
|
856
860
|
}
|
|
857
861
|
}
|
|
858
862
|
|
|
863
|
+
let nativeAdmissionState = null;
|
|
864
|
+
const nativeAdmittedWork = createUpdateAdmissionCounter();
|
|
865
|
+
let startupProbeReady = false;
|
|
866
|
+
|
|
867
|
+
async function assertNativeMutationAdmission() {
|
|
868
|
+
if (process.env.PI_WEBUI_STARTUP_PROBE === "1") throw makeHttpError(409, "Isolated startup probes cannot mutate packages or restart.");
|
|
869
|
+
if (!nativeAdmissionState) throw makeHttpError(409, "Update admission is not initialized.");
|
|
870
|
+
try { await assertEffectAdmission(nativeAdmissionState.root, nativeAdmissionState.participant.canonicalRoots); }
|
|
871
|
+
catch (error) {
|
|
872
|
+
if (error?.code === "UPDATE_FENCED") throw makeHttpError(409, "An affected package installation is fenced for update or recovery.");
|
|
873
|
+
throw error;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async function assertNativeRpcAdmission(command) {
|
|
878
|
+
if (["get_state", "get_messages", "get_session_stats", "get_available_models", "get_commands"].includes(command?.type)) return;
|
|
879
|
+
if (!nativeAdmissionState) throw new Error("Update admission is not initialized.");
|
|
880
|
+
await assertEffectAdmission(nativeAdmissionState.root, nativeAdmissionState.participant.canonicalRoots);
|
|
881
|
+
}
|
|
882
|
+
|
|
859
883
|
class SupervisorPiRpcProcess {
|
|
860
884
|
constructor({ supervisor, tabId, displayCommand = "supervised Pi RPC", cwd, snapshot = {} }) {
|
|
861
885
|
this.supervisor = supervisor;
|
|
@@ -865,6 +889,7 @@ class SupervisorPiRpcProcess {
|
|
|
865
889
|
this.startedAt = snapshot.startedAt || new Date().toISOString();
|
|
866
890
|
this.listeners = new Set();
|
|
867
891
|
this.metadataUpdate = Promise.resolve();
|
|
892
|
+
this.admissionTail = Promise.resolve();
|
|
868
893
|
this.applySnapshot(snapshot);
|
|
869
894
|
}
|
|
870
895
|
|
|
@@ -924,18 +949,36 @@ class SupervisorPiRpcProcess {
|
|
|
924
949
|
}
|
|
925
950
|
}
|
|
926
951
|
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
952
|
+
// Reserve wrapper order before admission's filesystem await. Only dispatch
|
|
953
|
+
// holds the barrier: an RPC response may wait on a subsequent UI write.
|
|
954
|
+
dispatchInOrder(operation) {
|
|
955
|
+
const dispatch = this.admissionTail.catch(() => {}).then(operation);
|
|
956
|
+
this.admissionTail = dispatch.then(() => {}, () => {});
|
|
957
|
+
return dispatch;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async send(command, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
961
|
+
const response = await this.dispatchInOrder(async () => {
|
|
962
|
+
await assertNativeRpcAdmission(command);
|
|
963
|
+
const requestId = command?.id || randomUUID();
|
|
964
|
+
const boundedTimeoutMs = Math.min(Math.max(1, Number(timeoutMs) || REQUEST_TIMEOUT_MS), RPC_SUPERVISOR_COMMAND_TIMEOUT_MAX_MS);
|
|
965
|
+
return { response: this.supervisor.command(this.tabId, command, { requestId, timeoutMs: boundedTimeoutMs }) };
|
|
966
|
+
});
|
|
967
|
+
return response.response;
|
|
931
968
|
}
|
|
932
969
|
|
|
933
970
|
async writeRaw(command) {
|
|
934
|
-
|
|
971
|
+
return this.dispatchInOrder(async () => {
|
|
972
|
+
await assertNativeRpcAdmission(command);
|
|
973
|
+
return this.supervisor.write(this.tabId, command);
|
|
974
|
+
});
|
|
935
975
|
}
|
|
936
976
|
|
|
937
|
-
async replace({ child, metadata, displayCommand }) {
|
|
938
|
-
const snapshot = await this.
|
|
977
|
+
async replace({ child, metadata, displayCommand, restart }) {
|
|
978
|
+
const snapshot = await this.dispatchInOrder(async () => {
|
|
979
|
+
const request = { tabId: this.tabId, metadata, child };
|
|
980
|
+
return restart ? this.supervisor.replaceTabUnderUpdate({ ...request, restart }) : this.supervisor.replaceTab(request);
|
|
981
|
+
});
|
|
939
982
|
if (displayCommand) this.displayCommand = displayCommand;
|
|
940
983
|
this.applySnapshot(snapshot);
|
|
941
984
|
return snapshot;
|
|
@@ -1153,7 +1196,7 @@ class PiRpcProcess {
|
|
|
1153
1196
|
if (!this.isRunning() || !this.child?.stdin) {
|
|
1154
1197
|
throw new Error("Pi RPC process is not running");
|
|
1155
1198
|
}
|
|
1156
|
-
|
|
1199
|
+
await assertNativeRpcAdmission(command);
|
|
1157
1200
|
const line = `${JSON.stringify(command)}\n`;
|
|
1158
1201
|
if (!this.child.stdin.write(line)) {
|
|
1159
1202
|
await new Promise((resolve) => this.child.stdin.once("drain", resolve));
|
|
@@ -2280,6 +2323,7 @@ function makeOptionalFeatureInstallError(statusCode, message, details = {}) {
|
|
|
2280
2323
|
}
|
|
2281
2324
|
|
|
2282
2325
|
async function installOptionalFeaturePackage(featureId, cwd = options.cwd) {
|
|
2326
|
+
await assertNativeMutationAdmission();
|
|
2283
2327
|
const beforeStatus = await optionalFeaturePackageStatus(featureId, cwd);
|
|
2284
2328
|
const packageName = beforeStatus.packageName;
|
|
2285
2329
|
const source = `npm:${packageName}`;
|
|
@@ -2296,6 +2340,7 @@ async function installOptionalFeaturePackage(featureId, cwd = options.cwd) {
|
|
|
2296
2340
|
});
|
|
2297
2341
|
}
|
|
2298
2342
|
const piCommand = await resolvePiCommand(["install", source]);
|
|
2343
|
+
await assertNativeMutationAdmission();
|
|
2299
2344
|
const command = piCommand.displayCommand;
|
|
2300
2345
|
const result = await runCommand(piCommand.command, piCommand.args, {
|
|
2301
2346
|
cwd,
|
|
@@ -2425,6 +2470,7 @@ function optionalFeatureProgressResult(result) {
|
|
|
2425
2470
|
}
|
|
2426
2471
|
|
|
2427
2472
|
async function runOptionalFeatureBatchMutation({ revision, featureIds, cwd = options.cwd, migration = false, tab = null, install = null }) {
|
|
2473
|
+
await assertNativeMutationAdmission();
|
|
2428
2474
|
return optionalFeatureAuditCoordinator.runMutation(revision, async () => {
|
|
2429
2475
|
optionalFeatureAuditCoordinator.setProgress({ phase: "migrating", migration, startedAt: new Date().toISOString(), completed: 0, remaining: Array.isArray(featureIds) ? featureIds.length : 0, total: Array.isArray(featureIds) ? featureIds.length : 0, results: [] });
|
|
2430
2476
|
const batch = install ? await install() : await installOptionalFeaturePackages(featureIds, cwd);
|
|
@@ -11630,6 +11676,10 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
|
|
|
11630
11676
|
}
|
|
11631
11677
|
|
|
11632
11678
|
async function createTab({ id: requestedId, index, title, titleSource, conversationStarted, cwd, sessionFile, gitWorkspace } = {}) {
|
|
11679
|
+
const releaseAdmittedWork = nativeAdmittedWork.begin();
|
|
11680
|
+
try {
|
|
11681
|
+
if (!nativeAdmissionState) throw new Error("Update admission is not initialized.");
|
|
11682
|
+
await assertEffectAdmission(nativeAdmissionState.root, nativeAdmissionState.participant.canonicalRoots);
|
|
11633
11683
|
const tabIndex = Number.isInteger(index) && index > 0 ? index : nextTabIndex;
|
|
11634
11684
|
nextTabIndex = Math.max(nextTabIndex, tabIndex + 1);
|
|
11635
11685
|
const explicitTitle = String(title || "").trim();
|
|
@@ -11663,6 +11713,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
|
|
|
11663
11713
|
tabs.set(id, tab);
|
|
11664
11714
|
workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
|
|
11665
11715
|
try {
|
|
11716
|
+
await assertEffectAdmission(nativeAdmissionState.root, nativeAdmissionState.participant.canonicalRoots);
|
|
11666
11717
|
if (rpc instanceof SupervisorPiRpcProcess) {
|
|
11667
11718
|
const snapshot = await rpcSupervisor.createTab({
|
|
11668
11719
|
tabId: id,
|
|
@@ -11689,6 +11740,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
|
|
|
11689
11740
|
recordEvent({ type: "webui_tab_restored", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd });
|
|
11690
11741
|
}
|
|
11691
11742
|
return tab;
|
|
11743
|
+
} finally { releaseAdmittedWork(); }
|
|
11692
11744
|
}
|
|
11693
11745
|
|
|
11694
11746
|
async function hydrateManagedTabs(snapshot) {
|
|
@@ -12458,7 +12510,7 @@ async function loadWebuiWorkspace(id, body = {}) {
|
|
|
12458
12510
|
}
|
|
12459
12511
|
}
|
|
12460
12512
|
|
|
12461
|
-
async function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
12513
|
+
async function spawnRestartServer(restorableTabs, supervisorCursor, updateRestart = null) {
|
|
12462
12514
|
const restore = await createRestoreFile(agentDir, restorableTabs || []);
|
|
12463
12515
|
const env = {
|
|
12464
12516
|
...process.env,
|
|
@@ -12467,6 +12519,13 @@ async function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
|
12467
12519
|
};
|
|
12468
12520
|
if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
|
|
12469
12521
|
else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
|
|
12522
|
+
if (updateRestart) {
|
|
12523
|
+
env.PI_WEBUI_NATIVE_RESTART_TRANSACTION = updateRestart.transactionId;
|
|
12524
|
+
env.PI_WEBUI_NATIVE_RESTART_TOKEN = updateRestart.lockToken;
|
|
12525
|
+
} else {
|
|
12526
|
+
delete env.PI_WEBUI_NATIVE_RESTART_TRANSACTION;
|
|
12527
|
+
delete env.PI_WEBUI_NATIVE_RESTART_TOKEN;
|
|
12528
|
+
}
|
|
12470
12529
|
if (webuiDevServer) env.PI_WEBUI_DEV = "1";
|
|
12471
12530
|
else delete env.PI_WEBUI_DEV;
|
|
12472
12531
|
const launcher = path.join(packageRoot, "bin", "pi-webui-launcher.mjs");
|
|
@@ -12483,7 +12542,6 @@ async function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
|
12483
12542
|
|
|
12484
12543
|
let updateStatusCache = null;
|
|
12485
12544
|
let updateStatusCacheAt = 0;
|
|
12486
|
-
let piUpdateInProgress = false;
|
|
12487
12545
|
const componentUpdateState = new ComponentUpdateState();
|
|
12488
12546
|
|
|
12489
12547
|
async function canonicalUpdateIdentities({ forcePi = false } = {}) {
|
|
@@ -12497,266 +12555,312 @@ async function canonicalUpdateIdentities({ forcePi = false } = {}) {
|
|
|
12497
12555
|
return { pi, webui };
|
|
12498
12556
|
}
|
|
12499
12557
|
|
|
12500
|
-
function
|
|
12501
|
-
|
|
12502
|
-
|
|
12503
|
-
|
|
12504
|
-
|
|
12505
|
-
|
|
12506
|
-
}
|
|
12507
|
-
const
|
|
12508
|
-
|
|
12509
|
-
|
|
12510
|
-
|
|
12511
|
-
if (
|
|
12512
|
-
|
|
12513
|
-
|
|
12514
|
-
|
|
12515
|
-
|
|
12516
|
-
}
|
|
12517
|
-
|
|
12518
|
-
|
|
12519
|
-
|
|
12520
|
-
|
|
12521
|
-
|
|
12522
|
-
|
|
12523
|
-
|
|
12524
|
-
|
|
12525
|
-
|
|
12526
|
-
|
|
12527
|
-
|
|
12528
|
-
|
|
12529
|
-
|
|
12530
|
-
const desiredPiVersion = requested.has("pi") ? status.pi.latestVersion : identities.pi.active?.version;
|
|
12531
|
-
const desiredWebuiVersion = requested.has("webui") ? status.webui.latestVersion : identities.webui.version;
|
|
12532
|
-
const separatePathPi = identities.pi.path?.canonicalId && identities.pi.path.canonicalId !== identities.pi.active?.canonicalId
|
|
12533
|
-
? identities.pi.path
|
|
12534
|
-
: null;
|
|
12535
|
-
const managedRuntimeRoot = path.join(statePaths.runtimesDir, `txn-${transactionId}`);
|
|
12536
|
-
const candidates = [];
|
|
12537
|
-
for (const target of targets) {
|
|
12538
|
-
const identity = target === "pi" ? identities.pi.active : identities.webui;
|
|
12539
|
-
if (!identity) throw makeHttpError(409, identities.pi.refusal?.message || `The ${target} runtime identity could not be verified.`);
|
|
12540
|
-
const managedRuntime = target === "webui" || (target === "pi" && bundledPi);
|
|
12541
|
-
candidates.push({
|
|
12542
|
-
id: target,
|
|
12543
|
-
kind: target,
|
|
12544
|
-
packageName: target === "pi" ? PI_CODING_AGENT_PACKAGE : WEBUI_PACKAGE,
|
|
12545
|
-
currentVersion: identity.version,
|
|
12546
|
-
identityId: identity.canonicalId,
|
|
12547
|
-
requested: "latest",
|
|
12548
|
-
registry: NPM_REGISTRY_URL,
|
|
12549
|
-
strategy: managedRuntime ? "managed-side-by-side" : "delegate-exact-pi",
|
|
12550
|
-
owner: updateOwnerForTarget(target, identities),
|
|
12551
|
-
exactTargetVersion: status[target].latestVersion,
|
|
12552
|
-
managedRuntime,
|
|
12553
|
-
runtimeRoot: managedRuntime ? managedRuntimeRoot : "",
|
|
12554
|
-
commandForVersion: async (version, registry) => {
|
|
12555
|
-
if (!managedRuntime) {
|
|
12556
|
-
const invocation = identity.invocation;
|
|
12557
|
-
if (!invocation?.command) throw new Error("The exact active Pi executable cannot own its update.");
|
|
12558
|
-
return { command: invocation.command, args: [...(invocation.args || []), "update", "--self"] };
|
|
12559
|
-
}
|
|
12560
|
-
const piVersion = target === "pi" ? version : desiredPiVersion;
|
|
12561
|
-
const webuiVersion = target === "webui" ? version : desiredWebuiVersion;
|
|
12562
|
-
const npm = resolvedNpmCommandForExactUpdate([
|
|
12563
|
-
"install", "--prefix", managedRuntimeRoot, "--ignore-scripts", "--no-save", "--package-lock=false", "--registry", registry,
|
|
12564
|
-
`${WEBUI_PACKAGE}@${webuiVersion}`,
|
|
12565
|
-
`${PI_CODING_AGENT_PACKAGE}@${piVersion}`,
|
|
12566
|
-
]);
|
|
12567
|
-
return { command: npm.command, args: npm.args };
|
|
12568
|
-
},
|
|
12569
|
-
});
|
|
12570
|
-
}
|
|
12571
|
-
|
|
12572
|
-
if (requested.has("pi") && requested.has("webui") && identities.pi.active) {
|
|
12573
|
-
const optionalStatuses = await optionalFeaturePackageStatuses(options.cwd);
|
|
12574
|
-
for (const feature of optionalStatuses.features) {
|
|
12575
|
-
if (!feature.configured || !feature.ready || !feature.installedVersion || !feature.installedRoot) continue;
|
|
12576
|
-
const latest = await checkLatestNpmPackageStatus(feature.packageName, feature.installedVersion);
|
|
12577
|
-
if (!latest.checked || !latest.updateAvailable || !latest.latestVersion) continue;
|
|
12578
|
-
const invocation = identities.pi.active.invocation;
|
|
12579
|
-
candidates.push({
|
|
12580
|
-
id: `optional:${feature.featureId}`,
|
|
12581
|
-
kind: "optional",
|
|
12582
|
-
packageName: feature.packageName,
|
|
12583
|
-
currentVersion: feature.installedVersion,
|
|
12584
|
-
identityId: identities.pi.active.canonicalId,
|
|
12585
|
-
requested: "latest",
|
|
12586
|
-
registry: NPM_REGISTRY_URL,
|
|
12587
|
-
strategy: "pi-owned-optional",
|
|
12588
|
-
owner: {
|
|
12589
|
-
manager: "pi",
|
|
12590
|
-
packageRoot: feature.installedRoot,
|
|
12591
|
-
ownerRoot: configuredAgentNpmRoot(),
|
|
12592
|
-
topLevel: true,
|
|
12593
|
-
optional: true,
|
|
12594
|
-
piOwned: true,
|
|
12595
|
-
},
|
|
12596
|
-
exactTargetVersion: latest.latestVersion,
|
|
12597
|
-
optionalFeature: true,
|
|
12598
|
-
featureId: feature.featureId,
|
|
12599
|
-
commandForVersion: async (version) => ({
|
|
12600
|
-
command: invocation.command,
|
|
12601
|
-
args: [...(invocation.args || []), "install", `npm:${feature.packageName}@${version}`],
|
|
12602
|
-
}),
|
|
12603
|
-
});
|
|
12558
|
+
async function nativeUpdateContext() {
|
|
12559
|
+
const stateRoot = await sharedUpdateRoot();
|
|
12560
|
+
try {
|
|
12561
|
+
await lstat(updateStatePaths(agentDir).installLock);
|
|
12562
|
+
throw makeHttpError(409, "A legacy update lock is present; inspect that job and stop it safely before native updates.");
|
|
12563
|
+
} catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
12564
|
+
const pathPi = await resolveUpdatePathPi({ runVersion: runCommand });
|
|
12565
|
+
const npmInvocation = resolveNpmCommandInvocation([]);
|
|
12566
|
+
let npm = null;
|
|
12567
|
+
// A configured JavaScript file is not evidence of npm: first prove that
|
|
12568
|
+
// the CLI belongs to an npm package, then probe its actual global effects.
|
|
12569
|
+
if (["node-cli", "configured-cli"].includes(npmInvocation.source) && path.isAbsolute(npmInvocation.command) && path.isAbsolute(npmInvocation.args[0] || "")) {
|
|
12570
|
+
const cli = await realpath(npmInvocation.args[0]).catch(() => "");
|
|
12571
|
+
const npmPackageRoot = path.resolve(path.dirname(cli), "..");
|
|
12572
|
+
let npmManifest = null;
|
|
12573
|
+
try { npmManifest = JSON.parse(await readFile(path.join(npmPackageRoot, "package.json"), "utf8")); }
|
|
12574
|
+
catch { /* An unproven npm executable remains manual-only. */ }
|
|
12575
|
+
if (cli === path.join(npmPackageRoot, "bin", "npm-cli.js") && npmManifest?.name === "npm" &&
|
|
12576
|
+
String(npmManifest.bin?.npm || "").replace(/^\.\//, "") === "bin/npm-cli.js" &&
|
|
12577
|
+
await realpath(npmPackageRoot) === npmPackageRoot) {
|
|
12578
|
+
const probe = async (args) => runCommand(npmInvocation.command, [...npmInvocation.args, ...args], { cwd: stateRoot, timeoutMs: 10_000, maxOutputLength: 4_000 });
|
|
12579
|
+
const [root, prefix] = await Promise.all([probe(["root", "-g"]), probe(["prefix", "-g"])]);
|
|
12580
|
+
if (root.exitCode === 0 && prefix.exitCode === 0 && !root.timedOut && !prefix.timedOut && !root.error && !prefix.error) {
|
|
12581
|
+
const [userconfig, globalconfig] = await Promise.all([probe(["config", "get", "userconfig"]), probe(["config", "get", "globalconfig"])]);
|
|
12582
|
+
const configPath = (result) => result.exitCode === 0 && !result.error && !result.timedOut &&
|
|
12583
|
+
path.isAbsolute(result.stdout.trim()) && !/[\r\n]/.test(result.stdout.trim()) ? path.resolve(result.stdout.trim()) : "";
|
|
12584
|
+
const configFiles = [configPath(userconfig), configPath(globalconfig)];
|
|
12585
|
+
if (configFiles.every(Boolean)) npm = { invocation: { command: await realpath(npmInvocation.command), args: [cli] },
|
|
12586
|
+
root: root.stdout.trim(), prefix: prefix.stdout.trim(), configFiles };
|
|
12587
|
+
}
|
|
12604
12588
|
}
|
|
12605
12589
|
}
|
|
12590
|
+
let globalSettings = {};
|
|
12591
|
+
const settingsFile = path.join(agentDir, "settings.json");
|
|
12592
|
+
try { globalSettings = JSON.parse(await readFile(settingsFile, "utf8")); }
|
|
12593
|
+
catch (error) { if (error.code !== "ENOENT") throw makeHttpError(409, "Pi user settings cannot be inspected safely."); }
|
|
12594
|
+
return { stateRoot, pathPi, npm, globalSettings, settingsFile };
|
|
12595
|
+
}
|
|
12606
12596
|
|
|
12607
|
-
|
|
12608
|
-
|
|
12609
|
-
|
|
12610
|
-
|
|
12611
|
-
|
|
12612
|
-
|
|
12613
|
-
|
|
12614
|
-
|
|
12615
|
-
|
|
12616
|
-
|
|
12617
|
-
|
|
12618
|
-
|
|
12619
|
-
|
|
12620
|
-
|
|
12621
|
-
|
|
12622
|
-
|
|
12623
|
-
|
|
12624
|
-
|
|
12625
|
-
|
|
12626
|
-
|
|
12627
|
-
|
|
12628
|
-
|
|
12597
|
+
async function createNativeServerPlan(targets, { persist = true } = {}) {
|
|
12598
|
+
const requested = targets[0];
|
|
12599
|
+
const context = await nativeUpdateContext();
|
|
12600
|
+
const accepted = [];
|
|
12601
|
+
const refusals = [];
|
|
12602
|
+
const include = async (item) => {
|
|
12603
|
+
if (!item.eligible) { refusals.push(item.guidance); return; }
|
|
12604
|
+
item.driver = item.command.args[0];
|
|
12605
|
+
accepted.push(item);
|
|
12606
|
+
};
|
|
12607
|
+
if (requested === "pi") {
|
|
12608
|
+
if (!context.npm || !context.pathPi.eligible || path.resolve(context.pathPi.prefix) !== path.resolve(context.npm.prefix) || context.globalSettings.npmCommand) {
|
|
12609
|
+
refusals.push("PATH Pi's npm-global owner or configured npmCommand cannot be proven; update Pi manually.");
|
|
12610
|
+
} else await include(selfUpdateCommand(context.pathPi));
|
|
12611
|
+
} else {
|
|
12612
|
+
if (context.npm) await include(await npmGlobalWebuiTarget({ nodeModulesRoot: context.npm.root, prefix: context.npm.prefix, npmInvocation: context.npm.invocation }));
|
|
12613
|
+
else refusals.push("The configured global npm executable and prefix are unproven; npm-global Web UI needs a manual update.");
|
|
12614
|
+
await include(await piUserWebuiTarget({ agentDir, settings: context.globalSettings, pathPi: context.pathPi }));
|
|
12615
|
+
if (context.globalSettings.npmCommand || !context.npm) {
|
|
12616
|
+
const index = accepted.findIndex((target) => target.id === "webui:pi-user");
|
|
12617
|
+
if (index >= 0) accepted.splice(index, 1);
|
|
12618
|
+
refusals.push("Pi's npm command or custom npmCommand cannot be proven to preserve the confirmed user-only effects; update that installation manually.");
|
|
12619
|
+
}
|
|
12620
|
+
}
|
|
12621
|
+
if (accepted.length === 2 && accepted[0].installed.root === accepted[1].installed.root) {
|
|
12622
|
+
refusals.push("Pi and npm resolve to the same Web UI package root; updating it once through npm-global only.");
|
|
12623
|
+
accepted.pop();
|
|
12624
|
+
}
|
|
12625
|
+
if (!accepted.length) throw makeHttpError(409, refusals.join(" ") || "No proven native update target is installed.");
|
|
12626
|
+
const shell = process.platform === "win32"
|
|
12627
|
+
? path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "/bin/bash";
|
|
12628
|
+
let shellPath;
|
|
12629
|
+
try { shellPath = await realpath(shell); }
|
|
12630
|
+
catch { throw makeHttpError(409, "Required background PowerShell/Bash is unavailable; update manually."); }
|
|
12631
|
+
const canonicalAgentDir = await realpath(agentDir);
|
|
12632
|
+
const frozenEnv = frozenUpdateEnvironment(process.env, canonicalAgentDir);
|
|
12633
|
+
const npmConfigFiles = [...new Set([
|
|
12634
|
+
path.join(context.stateRoot, ".npmrc"),
|
|
12635
|
+
...(context.npm?.configFiles || []),
|
|
12636
|
+
path.join(canonicalAgentDir, "npm", "etc", "npmrc"),
|
|
12637
|
+
])];
|
|
12638
|
+
const bindings = await readUpdateContext({ env: frozenEnv, settingsPath: context.settingsFile, npmConfigFiles });
|
|
12639
|
+
const fileDigest = async (file) => createHash("sha256").update(await readFile(file)).digest("hex");
|
|
12640
|
+
const activePiIdentity = (await canonicalPiRuntimeIdentity({ force: true })).active;
|
|
12641
|
+
const activePiCli = activePiIdentity?.cliPath || "";
|
|
12642
|
+
const activePiManifest = activePiIdentity?.packageRoot ? path.join(activePiIdentity.packageRoot, "package.json") : "";
|
|
12643
|
+
const plan = await createNativeUpdatePlan({ requested, targets: accepted, refusals,
|
|
12644
|
+
pathPi: { eligible: context.pathPi.eligible === true, version: context.pathPi.version || "",
|
|
12645
|
+
packageRoot: context.pathPi.packageRoot || "", executable: context.pathPi.executable || "",
|
|
12646
|
+
cli: context.pathPi.cli || "", guidance: context.pathPi.guidance || "" },
|
|
12647
|
+
context: { cwd: context.stateRoot, agentDir: canonicalAgentDir, npmPrefix: context.npm?.prefix, shell: shellPath,
|
|
12648
|
+
shellDigest: await fileDigest(shellPath), nodeDigest: await fileDigest(process.execPath),
|
|
12649
|
+
npmDriver: context.npm?.invocation.args[0] || "", npmDriverDigest: context.npm ? await fileDigest(context.npm.invocation.args[0]) : "",
|
|
12650
|
+
settingsPath: context.settingsFile, npmConfigFiles, ...bindings,
|
|
12651
|
+
ownerPackageRoot: realpathSync(packageRoot), ownerBootIdentity: bootIdentity },
|
|
12652
|
+
active: { pi: activePiIdentity?.version || "unknown", piRoot: activePiIdentity?.packageRoot || "",
|
|
12653
|
+
piCli: activePiCli, piCliDigest: activePiCli ? await fileDigest(activePiCli) : "",
|
|
12654
|
+
piManifestDigest: activePiManifest ? await fileDigest(activePiManifest) : "",
|
|
12655
|
+
webui: packageJson.version, webuiRoot: packageRoot },
|
|
12629
12656
|
});
|
|
12630
|
-
|
|
12631
|
-
await createUpdateJournal(agentDir, plan);
|
|
12657
|
+
if (persist) await persistSharedJob(context.stateRoot, { transactionId: plan.transactionId, phase: "planned", plan });
|
|
12632
12658
|
return plan;
|
|
12633
12659
|
}
|
|
12634
12660
|
|
|
12635
|
-
async function
|
|
12636
|
-
const
|
|
12637
|
-
const
|
|
12638
|
-
|
|
12639
|
-
|
|
12640
|
-
|
|
12641
|
-
|
|
12642
|
-
|
|
12643
|
-
|
|
12644
|
-
|
|
12645
|
-
if (
|
|
12646
|
-
|
|
12647
|
-
const
|
|
12648
|
-
|
|
12649
|
-
|
|
12650
|
-
|
|
12651
|
-
|
|
12652
|
-
}
|
|
12653
|
-
const
|
|
12654
|
-
const
|
|
12655
|
-
|
|
12656
|
-
|
|
12657
|
-
|
|
12658
|
-
|
|
12659
|
-
|
|
12660
|
-
|
|
12661
|
-
"
|
|
12662
|
-
|
|
12663
|
-
|
|
12664
|
-
"
|
|
12665
|
-
|
|
12666
|
-
|
|
12667
|
-
|
|
12668
|
-
|
|
12669
|
-
|
|
12670
|
-
|
|
12671
|
-
|
|
12672
|
-
|
|
12673
|
-
|
|
12674
|
-
await
|
|
12675
|
-
|
|
12676
|
-
|
|
12677
|
-
|
|
12678
|
-
|
|
12679
|
-
|
|
12680
|
-
|
|
12681
|
-
|
|
12682
|
-
|
|
12683
|
-
|
|
12684
|
-
|
|
12685
|
-
|
|
12686
|
-
|
|
12687
|
-
|
|
12688
|
-
|
|
12689
|
-
|
|
12690
|
-
|
|
12691
|
-
|
|
12692
|
-
|
|
12693
|
-
|
|
12661
|
+
async function applyNativeServerPlan(transactionId, digest) {
|
|
12662
|
+
const stateRoot = await sharedUpdateRoot();
|
|
12663
|
+
const job = await inspectNativeJob(stateRoot, transactionId);
|
|
12664
|
+
if (!job) throw makeHttpError(404, "Update job not found.");
|
|
12665
|
+
if (job.phase !== "planned") throw makeHttpError(409, "This update job has already been launched or is recovering.");
|
|
12666
|
+
validateNativePlan(job.plan, digest);
|
|
12667
|
+
const context = await nativeUpdateContext();
|
|
12668
|
+
if (job.plan.context.agentDir !== await realpath(agentDir) || job.plan.context.npmPrefix !== (context.npm?.prefix || "")) {
|
|
12669
|
+
throw makeHttpError(409, "Confirmed update context has changed; request another preview.");
|
|
12670
|
+
}
|
|
12671
|
+
if (optionalFeatureAuditCoordinator?.mutation) throw makeHttpError(409, "Another package mutation is in progress.");
|
|
12672
|
+
for (const tab of tabs.values()) {
|
|
12673
|
+
const state = await tab.rpc.send({ type: "get_state" }, 3_000).catch(() => null);
|
|
12674
|
+
if (!state || state.success === false || state.data?.isStreaming || state.data?.isCompacting || tab.activity?.isWorking ||
|
|
12675
|
+
(tab.bashQueue?.length || 0) > 0 || (tab.compactionQueue?.length || 0) > 0 || pendingExtensionUiRequests(tab).length) {
|
|
12676
|
+
throw makeHttpError(409, "Known Pi tab work is busy or could not prove idle; update was not launched.");
|
|
12677
|
+
}
|
|
12678
|
+
}
|
|
12679
|
+
const plannedIds = job.plan.targets.map((target) => target.id).join(",");
|
|
12680
|
+
const current = await createNativeServerPlan([job.plan.requested], { persist: false });
|
|
12681
|
+
if (JSON.stringify(current.context) !== JSON.stringify(job.plan.context) ||
|
|
12682
|
+
JSON.stringify(current.active) !== JSON.stringify(job.plan.active) ||
|
|
12683
|
+
JSON.stringify(current.pathPi) !== JSON.stringify(job.plan.pathPi) ||
|
|
12684
|
+
current.targets.map((target) => target.id).join(",") !== plannedIds || current.targets.some((target, i) =>
|
|
12685
|
+
target.driverDigest !== job.plan.targets[i].driverDigest || target.beforeVersion !== job.plan.targets[i].beforeVersion ||
|
|
12686
|
+
target.effectRoot !== job.plan.targets[i].effectRoot || JSON.stringify(target.command) !== JSON.stringify(job.plan.targets[i].command))) {
|
|
12687
|
+
throw makeHttpError(409, "Confirmed commands or installed roots changed; request another preview.");
|
|
12688
|
+
}
|
|
12689
|
+
if (rpcSupervisor && !rpcSupervisor.isCurrentVersion()) {
|
|
12690
|
+
throw makeHttpError(409, "The retained RPC supervisor does not support update admission; fully stop and restart Web UI first.");
|
|
12691
|
+
}
|
|
12692
|
+
const requiredParticipants = [{ kind: "server", token: nativeAdmissionState?.participant.token }];
|
|
12693
|
+
if (rpcSupervisor) requiredParticipants.push({ kind: "rpc-supervisor", pid: rpcSupervisor.state.pid });
|
|
12694
|
+
return launchNativeUpdate(job.plan, digest, { stateRoot, env: frozenUpdateEnvironment(process.env, job.plan.context.agentDir),
|
|
12695
|
+
requiredParticipants });
|
|
12696
|
+
}
|
|
12697
|
+
|
|
12698
|
+
async function nativeRestartIdle(job, stateRoot) {
|
|
12699
|
+
if (!nativeAdmittedWork.idle) return false;
|
|
12700
|
+
const participants = await affectedParticipants(stateRoot, job.lock);
|
|
12701
|
+
if (!participants.length || participants.some((participant) => participant.ack?.lockToken !== job.lock.token ||
|
|
12702
|
+
participant.ack.idle !== true || Date.now() - Date.parse(participant.ack.at) > 2_000)) return false;
|
|
12703
|
+
for (const tab of tabs.values()) {
|
|
12704
|
+
const state = await tab.rpc.send({ type: "get_state" }, 3_000).catch(() => null);
|
|
12705
|
+
if (!state || state.success === false || state.data?.isStreaming || state.data?.isCompacting ||
|
|
12706
|
+
tab.activity?.isWorking || tab.rpc?.pending?.size || tab.bashQueue?.length || tab.compactionQueue?.length ||
|
|
12707
|
+
pendingExtensionUiRequests(tab).length || tab.browserPromptRequests?.size) return false;
|
|
12708
|
+
}
|
|
12709
|
+
return true;
|
|
12710
|
+
}
|
|
12711
|
+
|
|
12712
|
+
async function continueNativeRestart(job, stateRoot) {
|
|
12713
|
+
const transactionId = job.transactionId;
|
|
12714
|
+
if (job.plan.context.ownerBootIdentity !== bootIdentity) {
|
|
12715
|
+
return { ...job, phase: "unknown", error: "The update owner exited before a verified restart; manual recovery is required." };
|
|
12716
|
+
}
|
|
12717
|
+
const verifiedTargets = job.verifiedTargets;
|
|
12718
|
+
const active = await canonicalPiRuntimeIdentity({ force: true });
|
|
12719
|
+
const activePi = verifiedTargets.find((target) => target.status === "healthy" &&
|
|
12720
|
+
(target.id === "pi" && target.installedRoot === job.plan.active.piRoot || target.piChanged === true) &&
|
|
12721
|
+
job.plan.active.piRoot === active.active?.packageRoot);
|
|
12722
|
+
const activeWebui = verifiedTargets.find((target) => target.id !== "pi" && target.status === "healthy" &&
|
|
12723
|
+
target.installedRoot === job.plan.active.webuiRoot && target.installedRoot === realpathSync(packageRoot));
|
|
12724
|
+
if ((activePi && tabs.size) || activeWebui) {
|
|
12725
|
+
if (!await nativeRestartIdle(job, stateRoot)) return inspectNativeJob(stateRoot, transactionId);
|
|
12726
|
+
if (activePi && [...tabs.values()].some((tab) => !(tab.rpc instanceof SupervisorPiRpcProcess)) ||
|
|
12727
|
+
activeWebui && !rpcSupervisor && tabs.size) {
|
|
12728
|
+
await persistSharedJob(stateRoot, { ...job, phase: "unknown", error: "Direct Pi tabs cannot be preserved across a fenced native restart." });
|
|
12729
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12730
|
+
}
|
|
12731
|
+
}
|
|
12732
|
+
const action = path.join(job.jobDir, "restart-action.claim");
|
|
12733
|
+
let handle;
|
|
12734
|
+
try {
|
|
12735
|
+
handle = await open(action, "wx", 0o600);
|
|
12736
|
+
await handle.writeFile(`${JSON.stringify({ pid: process.pid, bootIdentity, startedAt: new Date().toISOString() })}\n`);
|
|
12737
|
+
await handle.sync();
|
|
12738
|
+
} catch (error) { if (error?.code === "EEXIST") return inspectNativeJob(stateRoot, transactionId); throw error; }
|
|
12739
|
+
finally { await handle?.close(); }
|
|
12694
12740
|
try {
|
|
12695
|
-
|
|
12696
|
-
|
|
12697
|
-
|
|
12698
|
-
|
|
12699
|
-
|
|
12700
|
-
|
|
12701
|
-
|
|
12702
|
-
|
|
12741
|
+
if (activePi && tabs.size) {
|
|
12742
|
+
for (const tab of tabs.values()) {
|
|
12743
|
+
await restartTabRpc(tab, "native-update", { transactionId, lockToken: job.lock.token,
|
|
12744
|
+
effectRoot: activePi.effectRoot, nonce: randomUUID() });
|
|
12745
|
+
}
|
|
12746
|
+
}
|
|
12747
|
+
if (activeWebui) {
|
|
12748
|
+
const restored = await restorableTabsForRestart();
|
|
12749
|
+
const child = await spawnRestartServer(restored, await prepareRpcSupervisorHandoff(), {
|
|
12750
|
+
transactionId, lockToken: job.lock.token,
|
|
12751
|
+
});
|
|
12752
|
+
await persistSharedJob(stateRoot, { ...job, phase: "restart-pending", successorPid: child.pid });
|
|
12753
|
+
setTimeout(() => { void shutdown("verified native Web UI update", { preserveSessions: true }); }, 20).unref();
|
|
12754
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12755
|
+
}
|
|
12756
|
+
await releaseEffectLocks(job.lock, { completionVerified: true });
|
|
12757
|
+
await persistSharedJob(stateRoot, { ...job, phase: job.outcome });
|
|
12758
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12759
|
+
} catch (error) {
|
|
12760
|
+
await persistSharedJob(stateRoot, { ...job, phase: "unknown", error: sanitizeComponentUpdateError(error) });
|
|
12761
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12762
|
+
}
|
|
12763
|
+
}
|
|
12764
|
+
|
|
12765
|
+
async function finalizeNativeJob(transactionId) {
|
|
12766
|
+
const stateRoot = await sharedUpdateRoot();
|
|
12767
|
+
const observed = await inspectNativeJob(stateRoot, transactionId);
|
|
12768
|
+
if (!observed || !["command-complete", "restart-authorized", "launch-failed"].includes(observed.phase)) return observed;
|
|
12769
|
+
const owner = observed.plan.context;
|
|
12770
|
+
if (owner.agentDir !== await realpath(agentDir) || owner.ownerPackageRoot !== realpathSync(packageRoot)) {
|
|
12771
|
+
return { ...observed, phase: "unknown", error: "Only the original agent directory and runtime may recover this job." };
|
|
12772
|
+
}
|
|
12773
|
+
if (owner.ownerBootIdentity !== bootIdentity) {
|
|
12774
|
+
return { ...observed, phase: "unknown", error: "Original job owner is not this server; recovery requires manual verification." };
|
|
12775
|
+
}
|
|
12776
|
+
if (observed.phase === "restart-authorized") return continueNativeRestart(observed, stateRoot);
|
|
12777
|
+
const claim = path.join(observed.jobDir, "finalize.claim");
|
|
12778
|
+
let handle;
|
|
12779
|
+
try {
|
|
12780
|
+
handle = await open(claim, "wx", 0o600);
|
|
12781
|
+
await handle.writeFile(`${JSON.stringify({ pid: process.pid, bootIdentity, startedAt: new Date().toISOString() })}\n`);
|
|
12782
|
+
await handle.sync();
|
|
12783
|
+
} catch (error) { if (error?.code === "EEXIST") return inspectNativeJob(stateRoot, transactionId); throw error; }
|
|
12784
|
+
finally { await handle?.close(); }
|
|
12785
|
+
const job = await readSharedJob(stateRoot, transactionId);
|
|
12786
|
+
try {
|
|
12787
|
+
if (observed.phase === "launch-failed") {
|
|
12788
|
+
await releaseEffectLocks(job.lock, { completionVerified: true });
|
|
12789
|
+
await persistSharedJob(stateRoot, { ...job, phase: "failed", outcome: "failed",
|
|
12790
|
+
error: "PowerShell could not start; no native command ran." });
|
|
12791
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12792
|
+
}
|
|
12793
|
+
if (observed.receipts.length !== job.plan.targets.length || observed.receipts.some((receipt, index) =>
|
|
12794
|
+
receipt.id !== job.plan.targets[index].id || !["changed", "unchanged", "failed"].includes(receipt.status))) {
|
|
12795
|
+
throw new Error("A native command completion receipt is missing, mismatched or uncertain.");
|
|
12796
|
+
}
|
|
12797
|
+
const verifiedTargets = [];
|
|
12798
|
+
for (let index = 0; index < job.plan.targets.length; index++) {
|
|
12799
|
+
const target = job.plan.targets[index];
|
|
12800
|
+
const receipt = observed.receipts[index];
|
|
12801
|
+
if (receipt.status !== "changed") {
|
|
12802
|
+
verifiedTargets.push({ id: target.id, effectRoot: target.effectRoot, status: receipt.status });
|
|
12803
|
+
continue;
|
|
12804
|
+
}
|
|
12805
|
+
try {
|
|
12806
|
+
const manifest = JSON.parse(await readFile(target.manifestPath, "utf8"));
|
|
12807
|
+
const comparison = comparePackageVersions(receipt.afterVersion, target.beforeVersion);
|
|
12808
|
+
if (manifest.name !== target.packageName || manifest.version !== receipt.afterVersion ||
|
|
12809
|
+
comparison === undefined || comparison <= 0) {
|
|
12810
|
+
throw new Error(`Installed identity/version for ${target.id} is not an independently verified upgrade.`);
|
|
12811
|
+
}
|
|
12812
|
+
if (target.id === "pi") {
|
|
12813
|
+
const result = await runCommand(target.command.command, [target.driver, "--version"], { cwd: job.plan.context.cwd, timeoutMs: 10_000 });
|
|
12814
|
+
if (result.exitCode !== 0 || result.timedOut || parseRuntimeVersion(result.stdout) !== receipt.afterVersion) {
|
|
12815
|
+
throw new Error("Updated Pi CLI did not pass its independent version check.");
|
|
12703
12816
|
}
|
|
12704
|
-
|
|
12705
|
-
|
|
12706
|
-
|
|
12707
|
-
}
|
|
12708
|
-
|
|
12709
|
-
|
|
12710
|
-
|
|
12711
|
-
|
|
12712
|
-
|
|
12713
|
-
|
|
12714
|
-
|
|
12715
|
-
|
|
12716
|
-
|
|
12817
|
+
} else {
|
|
12818
|
+
const candidate = await probeStartupRestore(path.join(target.installedRoot, "bin", "pi-webui.mjs"), { expectedVersion: receipt.afterVersion });
|
|
12819
|
+
if (!candidate.ok) throw new Error(`Updated Web UI did not pass isolated startup and restoration: ${candidate.error || "unknown failure"}`);
|
|
12820
|
+
}
|
|
12821
|
+
verifiedTargets.push({ id: target.id, effectRoot: target.effectRoot, status: "healthy", version: receipt.afterVersion,
|
|
12822
|
+
installedRoot: target.installedRoot });
|
|
12823
|
+
} catch (error) {
|
|
12824
|
+
verifiedTargets.push({ id: target.id, effectRoot: target.effectRoot, status: "unverified",
|
|
12825
|
+
error: sanitizeComponentUpdateError(error) });
|
|
12826
|
+
}
|
|
12827
|
+
}
|
|
12828
|
+
// A targeted WebUI command can replace its bundled or hoisted Pi even if
|
|
12829
|
+
// the WebUI manifest itself remains at the same version. Verify that
|
|
12830
|
+
// changed active dependency independently before authorizing its reload.
|
|
12831
|
+
const plannedPi = job.plan.active;
|
|
12832
|
+
const piEffect = affectedActivePiDependency(job.plan, verifiedTargets);
|
|
12833
|
+
if (piEffect && plannedPi.piCli && plannedPi.piManifestDigest) {
|
|
12834
|
+
try {
|
|
12835
|
+
const currentManifestDigest = createHash("sha256").update(await readFile(path.join(plannedPi.piRoot, "package.json"))).digest("hex");
|
|
12836
|
+
const currentCliDigest = createHash("sha256").update(await readFile(plannedPi.piCli)).digest("hex");
|
|
12837
|
+
if (currentManifestDigest !== plannedPi.piManifestDigest || currentCliDigest !== plannedPi.piCliDigest) {
|
|
12838
|
+
const currentPi = (await canonicalPiRuntimeIdentity({ force: true })).active;
|
|
12839
|
+
const currentManifest = JSON.parse(await readFile(path.join(plannedPi.piRoot, "package.json"), "utf8"));
|
|
12840
|
+
if (currentPi?.packageRoot !== plannedPi.piRoot || currentPi.cliPath !== plannedPi.piCli ||
|
|
12841
|
+
currentManifest.name !== "@earendil-works/pi-coding-agent" || currentManifest.version !== currentPi.version) {
|
|
12842
|
+
throw new Error("Changed active Pi dependency identity or version could not be verified.");
|
|
12717
12843
|
}
|
|
12844
|
+
const webuiManifest = JSON.parse(await readFile(path.join(job.plan.targets.find((target) => target.id === piEffect.id).installedRoot, "package.json"), "utf8"));
|
|
12845
|
+
const healthy = await probeStartupRestore(path.join(job.plan.targets.find((target) => target.id === piEffect.id).installedRoot, "bin", "pi-webui.mjs"),
|
|
12846
|
+
{ expectedVersion: webuiManifest.version });
|
|
12847
|
+
if (!healthy.ok) throw new Error("Changed active Pi dependency did not pass WebUI startup/restoration.");
|
|
12848
|
+
piEffect.status = "healthy";
|
|
12849
|
+
piEffect.piChanged = true;
|
|
12850
|
+
piEffect.version = webuiManifest.version;
|
|
12718
12851
|
}
|
|
12719
|
-
}
|
|
12720
|
-
|
|
12721
|
-
|
|
12722
|
-
|
|
12723
|
-
|
|
12724
|
-
|
|
12725
|
-
|
|
12726
|
-
|
|
12727
|
-
|
|
12728
|
-
if (target.metadata?.managedRuntime) {
|
|
12729
|
-
const serverEntry = path.join(target.metadata.runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
|
|
12730
|
-
const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
|
|
12731
|
-
const afterVersion = target.id === "pi" ? probe.data?.piVersion : probe.data?.version;
|
|
12732
|
-
return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: { canonicalId: target.identityId }, beforeVersion: target.currentVersion, afterVersion: probe.ok ? afterVersion : "", command });
|
|
12733
|
-
}
|
|
12734
|
-
const after = await activeIdentityForTarget(target);
|
|
12735
|
-
return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: after, beforeVersion: target.currentVersion, afterVersion: after?.version, command });
|
|
12736
|
-
},
|
|
12737
|
-
});
|
|
12738
|
-
await transitionUpdateJournal(agentDir, transactionId, "verifying", { outcome: result.outcome, receipts: result.receipts });
|
|
12739
|
-
state = "verifying";
|
|
12740
|
-
const managedTargets = journal.plan.targets.filter((target) => target.metadata?.managedRuntime);
|
|
12741
|
-
const managedTargetsVerified = managedTargets.length > 0 && managedTargets.every((target) => result.receipts.find((receipt) => receipt.targetId === target.id)?.status === "success");
|
|
12742
|
-
const activationTarget = managedTargetsVerified ? managedTargets[0] : null;
|
|
12743
|
-
if (activationTarget) {
|
|
12744
|
-
const activation = await launchManagedActivation(journal, activationTarget, lock, result.outcome);
|
|
12745
|
-
lockTransferred = true;
|
|
12746
|
-
return { transactionId, planDigest, state: "activating", outcome: result.outcome, receipts: result.receipts, activation };
|
|
12747
|
-
}
|
|
12748
|
-
const terminal = result.outcome === "success" ? "success" : result.outcome === "partial" ? "partial" : "failed";
|
|
12749
|
-
const completed = await transitionUpdateJournal(agentDir, transactionId, terminal, { outcome: result.outcome, receipts: result.receipts });
|
|
12750
|
-
return completed;
|
|
12852
|
+
} catch (error) {
|
|
12853
|
+
piEffect.status = "unverified";
|
|
12854
|
+
piEffect.error = sanitizeComponentUpdateError(error);
|
|
12855
|
+
}
|
|
12856
|
+
}
|
|
12857
|
+
const outcome = nativeUpdateOutcome(verifiedTargets);
|
|
12858
|
+
const authorized = { ...job, phase: "restart-authorized", outcome, verifiedTargets };
|
|
12859
|
+
await persistSharedJob(stateRoot, authorized);
|
|
12860
|
+
return continueNativeRestart(authorized, stateRoot);
|
|
12751
12861
|
} catch (error) {
|
|
12752
|
-
|
|
12753
|
-
|
|
12754
|
-
} finally {
|
|
12755
|
-
if (lock && !lockTransferred) await releaseInstallLock(lock);
|
|
12756
|
-
piUpdateInProgress = false;
|
|
12757
|
-
invalidateCanonicalPiRuntime();
|
|
12758
|
-
updateStatusCache = null;
|
|
12759
|
-
updateStatusCacheAt = 0;
|
|
12862
|
+
await persistSharedJob(stateRoot, { ...job, phase: "unknown", error: sanitizeComponentUpdateError(error) });
|
|
12863
|
+
return inspectNativeJob(stateRoot, transactionId);
|
|
12760
12864
|
}
|
|
12761
12865
|
}
|
|
12762
12866
|
|
|
@@ -12767,15 +12871,18 @@ function webuiComponentUpdateUnavailableReason() {
|
|
|
12767
12871
|
return "";
|
|
12768
12872
|
}
|
|
12769
12873
|
|
|
12770
|
-
function privilegedUpdateInProgress() {
|
|
12771
|
-
|
|
12874
|
+
async function privilegedUpdateInProgress() {
|
|
12875
|
+
if (componentUpdateState.hasRunning()) return true;
|
|
12876
|
+
if (!nativeAdmissionState) return true;
|
|
12877
|
+
try { await assertEffectAdmission(nativeAdmissionState.root, nativeAdmissionState.participant.canonicalRoots); return false; }
|
|
12878
|
+
catch { return true; }
|
|
12772
12879
|
}
|
|
12773
12880
|
|
|
12774
|
-
function componentUpdatesForRequest(req) {
|
|
12881
|
+
async function componentUpdatesForRequest(req, updateInProgress) {
|
|
12775
12882
|
const webuiUnavailableReason = webuiComponentUpdateUnavailableReason();
|
|
12776
12883
|
return componentUpdateState.publicStates({
|
|
12777
12884
|
localRequest: isLocalRequest(req),
|
|
12778
|
-
updateInProgress
|
|
12885
|
+
updateInProgress,
|
|
12779
12886
|
webuiAvailable: !webuiUnavailableReason,
|
|
12780
12887
|
webuiUnavailableReason,
|
|
12781
12888
|
});
|
|
@@ -12800,17 +12907,16 @@ function basePackageUpdateStatus(packageName, currentVersion) {
|
|
|
12800
12907
|
};
|
|
12801
12908
|
}
|
|
12802
12909
|
|
|
12803
|
-
async function currentPiRuntimeVersion() {
|
|
12804
|
-
try {
|
|
12805
|
-
return (await canonicalUpdateIdentities({ forcePi: true })).pi.active?.version || "unknown";
|
|
12806
|
-
} catch {
|
|
12807
|
-
return "unknown";
|
|
12808
|
-
}
|
|
12809
|
-
}
|
|
12810
|
-
|
|
12811
12910
|
async function checkLatestPiReleaseStatus() {
|
|
12812
|
-
const
|
|
12911
|
+
const [selected, pathPi] = await Promise.all([
|
|
12912
|
+
canonicalPiRuntimeIdentity({ force: true }).catch(() => null),
|
|
12913
|
+
resolveUpdatePathPi({ runVersion: runCommand }),
|
|
12914
|
+
]);
|
|
12915
|
+
const currentVersion = pathPi.eligible ? pathPi.version : "";
|
|
12813
12916
|
const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, currentVersion);
|
|
12917
|
+
status.activeRuntimeVersion = selected?.active?.version || "unknown";
|
|
12918
|
+
status.pathInstallationVersion = currentVersion || "unknown";
|
|
12919
|
+
status.pathGuidance = pathPi.eligible ? "" : pathPi.guidance;
|
|
12814
12920
|
const skippedReason = updateChecksSkippedReason();
|
|
12815
12921
|
if (skippedReason) {
|
|
12816
12922
|
status.skipped = true;
|
|
@@ -12867,12 +12973,27 @@ async function checkLatestNpmPackageStatus(packageName, currentVersion) {
|
|
|
12867
12973
|
return status;
|
|
12868
12974
|
}
|
|
12869
12975
|
|
|
12870
|
-
function updateStatusForRequest(status, req) {
|
|
12976
|
+
async function updateStatusForRequest(status, req) {
|
|
12977
|
+
const localRequest = isLocalRequest(req);
|
|
12978
|
+
let nativeJobs = { pi: null, webui: null };
|
|
12979
|
+
let nativeJobDiscoveryError = "";
|
|
12980
|
+
if (localRequest) {
|
|
12981
|
+
try {
|
|
12982
|
+
nativeJobs = await discoverNativeJobs(await sharedUpdateRoot(), {
|
|
12983
|
+
agentDir: await realpath(agentDir), ownerPackageRoot: realpathSync(packageRoot), ownerBootIdentity: bootIdentity,
|
|
12984
|
+
});
|
|
12985
|
+
} catch {
|
|
12986
|
+
nativeJobDiscoveryError = "Durable update history could not be verified. Inspect the host before retrying or restarting.";
|
|
12987
|
+
}
|
|
12988
|
+
}
|
|
12989
|
+
const updateInProgress = await privilegedUpdateInProgress() || Boolean(nativeJobDiscoveryError) ||
|
|
12990
|
+
Object.values(nativeJobs).some(nativeJobBlocksUpdates);
|
|
12871
12991
|
return {
|
|
12872
12992
|
...status,
|
|
12873
|
-
canRunUpdate:
|
|
12874
|
-
updateInProgress
|
|
12875
|
-
componentUpdates: componentUpdatesForRequest(req),
|
|
12993
|
+
canRunUpdate: localRequest && !updateInProgress,
|
|
12994
|
+
updateInProgress,
|
|
12995
|
+
componentUpdates: await componentUpdatesForRequest(req, updateInProgress),
|
|
12996
|
+
...(localRequest ? { nativeJobs, nativeJobDiscoveryError } : {}),
|
|
12876
12997
|
};
|
|
12877
12998
|
}
|
|
12878
12999
|
|
|
@@ -12887,7 +13008,7 @@ async function getUpdateStatus({ force = false } = {}) {
|
|
|
12887
13008
|
updateStatusCache = {
|
|
12888
13009
|
checkedAt: new Date(now).toISOString(),
|
|
12889
13010
|
updateAvailable,
|
|
12890
|
-
restartRequired:
|
|
13011
|
+
restartRequired: false,
|
|
12891
13012
|
planEndpoint: "/api/update/plan",
|
|
12892
13013
|
applyEndpoint: "/api/update/apply",
|
|
12893
13014
|
webuiDev: webuiDevServer,
|
|
@@ -12895,18 +13016,13 @@ async function getUpdateStatus({ force = false } = {}) {
|
|
|
12895
13016
|
webui: webuiStatus,
|
|
12896
13017
|
packages: {
|
|
12897
13018
|
checked: false,
|
|
12898
|
-
note: "
|
|
13019
|
+
note: "Separate native Pi and Web UI actions use confirmed PATH Pi or proven npm ownership; uncertain targets require a manual update."
|
|
12899
13020
|
},
|
|
12900
13021
|
};
|
|
12901
13022
|
updateStatusCacheAt = now;
|
|
12902
13023
|
return updateStatusCache;
|
|
12903
13024
|
}
|
|
12904
13025
|
|
|
12905
|
-
function resolvedNpmCommandForExactUpdate(args) {
|
|
12906
|
-
const invocation = resolveNpmCommandInvocation(args);
|
|
12907
|
-
return { command: invocation.command, args: invocation.args };
|
|
12908
|
-
}
|
|
12909
|
-
|
|
12910
13026
|
function exactUpdatePathInside(root, candidate) {
|
|
12911
13027
|
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
12912
13028
|
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
@@ -13105,7 +13221,24 @@ async function performTabCwdUpdate(tab, cwd) {
|
|
|
13105
13221
|
return { tab, changed: true };
|
|
13106
13222
|
}
|
|
13107
13223
|
|
|
13108
|
-
async function
|
|
13224
|
+
async function writeNativeRestartMarker(restart, tabId, metadata, child) {
|
|
13225
|
+
// The original owner has already claimed restart-action; inspection reports
|
|
13226
|
+
// restart-in-progress while the durable authorization remains unchanged.
|
|
13227
|
+
const job = await readSharedJob(await sharedUpdateRoot(), restart.transactionId);
|
|
13228
|
+
if (!job || job.phase !== "restart-authorized" || job.lock?.token !== restart.lockToken ||
|
|
13229
|
+
job.plan.context.ownerBootIdentity !== bootIdentity) {
|
|
13230
|
+
throw makeHttpError(409, "No durable verified native update can restart this tab.");
|
|
13231
|
+
}
|
|
13232
|
+
const directory = path.join(job.jobDir, "restarts");
|
|
13233
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
13234
|
+
const marker = { tabId, transactionId: restart.transactionId, lockToken: restart.lockToken, effectRoot: restart.effectRoot,
|
|
13235
|
+
requestDigest: createHash("sha256").update(JSON.stringify({ tabId, metadata, child })).digest("hex") };
|
|
13236
|
+
const handle = await open(path.join(directory, `${restart.nonce}.json`), "wx", 0o600);
|
|
13237
|
+
try { await handle.writeFile(`${JSON.stringify(marker)}\n`); await handle.sync(); }
|
|
13238
|
+
finally { await handle.close(); }
|
|
13239
|
+
}
|
|
13240
|
+
|
|
13241
|
+
async function restartTabRpc(tab, reason = "reload", restart = null) {
|
|
13109
13242
|
const state = await tab.rpc.send({ type: "get_state" });
|
|
13110
13243
|
if (state.success === false) throw makeHttpError(400, state.error || "Unable to read Pi state before reload");
|
|
13111
13244
|
rememberTabState(tab, state.data);
|
|
@@ -13119,6 +13252,7 @@ async function restartTabRpc(tab, reason = "reload") {
|
|
|
13119
13252
|
const reloadingEvent = { type: "webui_tab_reloading", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, reason, sessionFile: state.data?.sessionFile };
|
|
13120
13253
|
broadcastTabEvent(tab, reloadingEvent);
|
|
13121
13254
|
|
|
13255
|
+
const expectedSessionFile = state.data?.sessionFile || "";
|
|
13122
13256
|
const oldRpc = tab.rpc;
|
|
13123
13257
|
tab.rpcUnsubscribe?.();
|
|
13124
13258
|
tab.rpcUnsubscribe = undefined;
|
|
@@ -13133,15 +13267,24 @@ async function restartTabRpc(tab, reason = "reload") {
|
|
|
13133
13267
|
resetCodexFastMode(tab);
|
|
13134
13268
|
let rpc;
|
|
13135
13269
|
if (oldRpc instanceof SupervisorPiRpcProcess) {
|
|
13270
|
+
const child = { command: piCommand.command, args: piCommand.args, cwd: tab.cwd };
|
|
13271
|
+
const metadata = supervisedTabMetadata(tab, { prompt: launch.prompt });
|
|
13272
|
+
if (restart) await writeNativeRestartMarker(restart, tab.id, metadata, child);
|
|
13136
13273
|
const snapshot = await oldRpc.replace({
|
|
13137
|
-
child
|
|
13138
|
-
metadata: supervisedTabMetadata(tab, { prompt: launch.prompt }),
|
|
13274
|
+
child, metadata, restart,
|
|
13139
13275
|
displayCommand: piCommand.displayCommand,
|
|
13140
13276
|
});
|
|
13141
13277
|
oldRpc.dispose();
|
|
13142
13278
|
rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
|
|
13143
13279
|
attachRpcToTab(tab, rpc);
|
|
13280
|
+
if (restart) {
|
|
13281
|
+
const restored = await rpc.send({ type: "get_state" }, 5_000);
|
|
13282
|
+
assertRestoredPiState(restored, expectedSessionFile);
|
|
13283
|
+
if (!rpc.isRunning()) throw new Error("Restored Pi child exited before session verification.");
|
|
13284
|
+
rememberTabState(tab, restored.data);
|
|
13285
|
+
}
|
|
13144
13286
|
} else {
|
|
13287
|
+
if (restart) throw makeHttpError(409, "A direct Pi tab cannot be restarted while the update fence is held; supervised handoff is required.");
|
|
13145
13288
|
oldRpc.stop();
|
|
13146
13289
|
rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
|
|
13147
13290
|
attachRpcToTab(tab, rpc);
|
|
@@ -15804,6 +15947,10 @@ async function saveAppendSystemSelection(tab, body) {
|
|
|
15804
15947
|
async function createInitialTabs() {
|
|
15805
15948
|
const managedTabs = await hydrateManagedTabs(rpcSupervisorSnapshot);
|
|
15806
15949
|
if (rpcSupervisorSnapshot?.tabs?.length) return managedTabs;
|
|
15950
|
+
// A successor cannot create new affected work while its predecessor's
|
|
15951
|
+
// verified update fence is still held. Ordinary tab creation resumes after
|
|
15952
|
+
// the successor has proved startup and released that fence.
|
|
15953
|
+
if (process.env.PI_WEBUI_NATIVE_RESTART_TRANSACTION) return [];
|
|
15807
15954
|
if (!restoreTabs.length) return options.cwdExplicit ? [await createTab()] : [];
|
|
15808
15955
|
|
|
15809
15956
|
const created = [];
|
|
@@ -16937,7 +17084,7 @@ const server = createServer(async (req, res) => {
|
|
|
16937
17084
|
if (url.pathname === "/api/update-status" && req.method === "GET") {
|
|
16938
17085
|
const force = ["1", "true", "yes", "refresh"].includes(String(url.searchParams.get("refresh") || "").toLowerCase());
|
|
16939
17086
|
const status = await getUpdateStatus({ force });
|
|
16940
|
-
sendJson(res, 200, { ok: true, data: updateStatusForRequest(status, req) });
|
|
17087
|
+
sendJson(res, 200, { ok: true, data: await updateStatusForRequest(status, req) });
|
|
16941
17088
|
return;
|
|
16942
17089
|
}
|
|
16943
17090
|
|
|
@@ -17048,66 +17195,60 @@ const server = createServer(async (req, res) => {
|
|
|
17048
17195
|
|
|
17049
17196
|
if (url.pathname === "/api/restart" && req.method === "POST") {
|
|
17050
17197
|
requireLocalhostRoute(req, url.pathname);
|
|
17051
|
-
const
|
|
17052
|
-
|
|
17053
|
-
|
|
17054
|
-
|
|
17055
|
-
|
|
17198
|
+
const releaseAdmittedWork = nativeAdmittedWork.begin();
|
|
17199
|
+
try {
|
|
17200
|
+
await assertNativeMutationAdmission();
|
|
17201
|
+
const restorableTabs = await restorableTabsForRestart();
|
|
17202
|
+
const supervisorCursor = await prepareRpcSupervisorHandoff();
|
|
17203
|
+
await assertNativeMutationAdmission();
|
|
17204
|
+
const child = await spawnRestartServer(restorableTabs, supervisorCursor);
|
|
17205
|
+
sendJson(res, 200, { ok: true, message: "Pi Web UI restarting", webuiPid: process.pid, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
|
|
17206
|
+
setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
|
|
17207
|
+
return;
|
|
17208
|
+
} finally { releaseAdmittedWork(); }
|
|
17209
|
+
}
|
|
17210
|
+
|
|
17211
|
+
if (url.pathname === "/api/update/startup-probe" && req.method === "GET" && process.env.PI_WEBUI_STARTUP_PROBE === "1") {
|
|
17212
|
+
requireLocalhostRoute(req, url.pathname);
|
|
17213
|
+
if (!startupProbeReady) throw makeHttpError(503, "Startup and tab restoration have not completed.");
|
|
17214
|
+
sendJson(res, 200, { ok: true, data: { schemaVersion: 1, packageName: WEBUI_PACKAGE, version: packageJson.version,
|
|
17215
|
+
bootIdentity, restoredTabCount: restoreTabs.length, runningTabCount: tabs.size,
|
|
17216
|
+
restoredProbeTabHealthy: tabs.get("probe-tab")?.rpc.isRunning() === true && Boolean(tabs.get("probe-tab")?.lastState) } });
|
|
17056
17217
|
return;
|
|
17057
17218
|
}
|
|
17058
17219
|
|
|
17059
17220
|
if (url.pathname === "/api/update/plan" && req.method === "POST") {
|
|
17060
17221
|
requireLocalhostRoute(req, url.pathname);
|
|
17222
|
+
if (process.env.PI_WEBUI_STARTUP_PROBE === "1") throw makeHttpError(409, "Isolated startup probes cannot plan updates.");
|
|
17061
17223
|
const validation = validateUpdatePlanRequest(await readJsonBody(req));
|
|
17062
17224
|
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
17063
|
-
const plan = await
|
|
17225
|
+
const plan = await createNativeServerPlan(validation.targets);
|
|
17064
17226
|
sendJson(res, 201, { ok: true, data: { plan } });
|
|
17065
17227
|
return;
|
|
17066
17228
|
}
|
|
17067
17229
|
|
|
17068
17230
|
if (url.pathname === "/api/update/apply" && req.method === "POST") {
|
|
17069
17231
|
requireLocalhostRoute(req, url.pathname);
|
|
17232
|
+
if (process.env.PI_WEBUI_STARTUP_PROBE === "1") throw makeHttpError(409, "Isolated startup probes cannot apply updates.");
|
|
17070
17233
|
const validation = validateUpdateApplyRequest(await readJsonBody(req));
|
|
17071
17234
|
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
17072
|
-
const data = await
|
|
17073
|
-
sendJson(res,
|
|
17074
|
-
if (data.state === "activating") setTimeout(() => { void shutdown("managed Web UI activation", { preserveSessions: true }); }, 20).unref();
|
|
17235
|
+
const data = await applyNativeServerPlan(validation.transactionId, validation.planDigest);
|
|
17236
|
+
sendJson(res, 202, { ok: true, data });
|
|
17075
17237
|
return;
|
|
17076
17238
|
}
|
|
17077
17239
|
|
|
17078
17240
|
const updateTransactionRoute = url.pathname.match(/^\/api\/update\/transactions\/([A-Za-z0-9._-]{1,128})$/);
|
|
17079
17241
|
if (updateTransactionRoute && req.method === "GET") {
|
|
17080
17242
|
requireLocalhost(req, "Viewing update transactions is only allowed from localhost");
|
|
17081
|
-
const
|
|
17082
|
-
if (!
|
|
17083
|
-
sendJson(res, 200, { ok: true, data:
|
|
17243
|
+
const job = await finalizeNativeJob(updateTransactionRoute[1]);
|
|
17244
|
+
if (!job) throw makeHttpError(404, "Update job was not found.");
|
|
17245
|
+
sendJson(res, 200, { ok: true, data: publicNativeJob(job) });
|
|
17084
17246
|
return;
|
|
17085
17247
|
}
|
|
17086
17248
|
|
|
17087
17249
|
if (url.pathname === "/api/update/rollback" && req.method === "POST") {
|
|
17088
17250
|
requireLocalhostRoute(req, url.pathname);
|
|
17089
|
-
|
|
17090
|
-
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
17091
|
-
const journal = await readUpdateJournal(agentDir, validation.transactionId);
|
|
17092
|
-
if (!journal) throw makeHttpError(404, "Update transaction was not found.");
|
|
17093
|
-
assertUpdatePlanDigest(journal.plan, validation.planDigest);
|
|
17094
|
-
const webuiTarget = journal.plan.targets.find((target) => target.id === "webui");
|
|
17095
|
-
if (journal.state !== "success" || !webuiTarget) throw makeHttpError(409, "Only a successfully activated Web UI transaction can be rolled back manually.");
|
|
17096
|
-
const currentPointer = await readRuntimePointer(agentDir, "current");
|
|
17097
|
-
if (!currentPointer || currentPointer.version !== webuiTarget.targetVersion) throw makeHttpError(409, "The active managed runtime no longer matches this rollback receipt.");
|
|
17098
|
-
const lock = await acquireInstallLock(agentDir);
|
|
17099
|
-
let pointer;
|
|
17100
|
-
let child;
|
|
17101
|
-
try {
|
|
17102
|
-
pointer = await rollbackRuntimePointer(agentDir);
|
|
17103
|
-
child = await spawnRestartServer(await restorableTabsForRestart(), await prepareRpcSupervisorHandoff());
|
|
17104
|
-
await transitionUpdateJournal(agentDir, journal.transactionId, "rolled-back", { outcome: "rolled-back", rollback: { manual: true, at: new Date().toISOString(), pointer } });
|
|
17105
|
-
} finally {
|
|
17106
|
-
await releaseInstallLock(lock);
|
|
17107
|
-
}
|
|
17108
|
-
sendJson(res, 202, { ok: true, data: { outcome: "rolled-back", pointer, nextWebuiPid: child.pid } });
|
|
17109
|
-
setTimeout(() => { void shutdown("manual update rollback", { preserveSessions: true }); }, 20).unref();
|
|
17110
|
-
return;
|
|
17251
|
+
throw makeHttpError(410, "Native package-manager updates cannot be rolled back by switching a managed runtime pointer.");
|
|
17111
17252
|
}
|
|
17112
17253
|
|
|
17113
17254
|
if ((url.pathname === "/api/component-update" || url.pathname === "/api/update") && req.method === "POST") {
|
|
@@ -17525,6 +17666,7 @@ const server = createServer(async (req, res) => {
|
|
|
17525
17666
|
const body = await readJsonBody(req);
|
|
17526
17667
|
const tab = getRequestedTab(req, url, body);
|
|
17527
17668
|
ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
|
|
17669
|
+
await assertNativeMutationAdmission();
|
|
17528
17670
|
const revision = optionalFeatureAuditCoordinator.current().revision;
|
|
17529
17671
|
const data = await optionalFeatureAuditCoordinator.runMutation(revision, async () => {
|
|
17530
17672
|
try {
|
|
@@ -17542,6 +17684,7 @@ const server = createServer(async (req, res) => {
|
|
|
17542
17684
|
const body = await readJsonBody(req);
|
|
17543
17685
|
const tab = getRequestedTab(req, url, body);
|
|
17544
17686
|
ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
|
|
17687
|
+
await assertNativeMutationAdmission();
|
|
17545
17688
|
const data = await runOptionalFeatureBatchMutation({
|
|
17546
17689
|
revision: body.revision,
|
|
17547
17690
|
featureIds: body.featureIds,
|
|
@@ -18072,17 +18215,35 @@ if (!isLocalHost(currentHost)) {
|
|
|
18072
18215
|
console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
|
|
18073
18216
|
}
|
|
18074
18217
|
|
|
18075
|
-
|
|
18076
|
-
|
|
18077
|
-
|
|
18078
|
-
await
|
|
18079
|
-
|
|
18080
|
-
|
|
18081
|
-
|
|
18082
|
-
|
|
18083
|
-
|
|
18084
|
-
|
|
18218
|
+
async function initializeNativeAdmission() {
|
|
18219
|
+
const root = await sharedUpdateRoot();
|
|
18220
|
+
const candidates = [packageRoot, configuredAgentNpmRoot()];
|
|
18221
|
+
const activePiRoot = (await canonicalPiRuntimeIdentity({ force: true }).catch(() => null))?.active?.packageRoot;
|
|
18222
|
+
if (activePiRoot) candidates.push(activePiRoot);
|
|
18223
|
+
const nativeContext = await nativeUpdateContext().catch(() => null);
|
|
18224
|
+
if (nativeContext?.pathPi?.eligible) candidates.push(nativeContext.pathPi.prefix);
|
|
18225
|
+
if (nativeContext?.npm?.prefix) candidates.push(nativeContext.npm.prefix);
|
|
18226
|
+
if (!webuiDevServer) candidates.push(packageOwnerRoot(packageRoot));
|
|
18227
|
+
const roots = [...new Set((await Promise.all(candidates.map((candidate) => realpath(candidate).catch(() => null)))).filter(Boolean))];
|
|
18228
|
+
const participant = await registerUpdateParticipant(root, { kind: "server", roots });
|
|
18229
|
+
process.env.PI_WEBUI_UPDATE_EFFECT_ROOTS = JSON.stringify(participant.canonicalRoots);
|
|
18230
|
+
nativeAdmissionState = { root, participant };
|
|
18231
|
+
setInterval(async () => {
|
|
18232
|
+
try {
|
|
18233
|
+
for (const effect of participant.canonicalRoots) {
|
|
18234
|
+
const lock = await effectLockForRoot(root, effect);
|
|
18235
|
+
if (!lock) continue;
|
|
18236
|
+
const idle = nativeAdmittedWork.idle && !optionalFeatureAuditCoordinator?.mutation && [...tabs.values()].every((tab) => !tab.activity?.isWorking && !tab.lastState?.isStreaming && !tab.lastState?.isCompacting &&
|
|
18237
|
+
!(tab.rpc?.pending?.size > 0) && !(tab.bashQueue?.length > 0) && !(tab.compactionQueue?.length > 0) &&
|
|
18238
|
+
pendingExtensionUiRequests(tab).length === 0 && (tab.browserPromptRequests?.size || 0) === 0);
|
|
18239
|
+
await acknowledgeUpdateFence(participant, { token: lock.token, effects: [effect] }, idle);
|
|
18240
|
+
}
|
|
18241
|
+
} catch (error) { console.warn(`update admission check failed: ${sanitizeError(error)}`); }
|
|
18242
|
+
}, 250).unref();
|
|
18085
18243
|
}
|
|
18244
|
+
await sweepRestoreFiles(agentDir).catch(() => {});
|
|
18245
|
+
// Startup package migrations need the same shared admission as interactive ones.
|
|
18246
|
+
await initializeNativeAdmission();
|
|
18086
18247
|
const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
|
|
18087
18248
|
if (options.migrationDryRun) {
|
|
18088
18249
|
console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);
|
|
@@ -18094,12 +18255,48 @@ if (options.migrationDryRun) {
|
|
|
18094
18255
|
}
|
|
18095
18256
|
}
|
|
18096
18257
|
|
|
18258
|
+
// The detached supervisor inherits registered roots before its first Pi child.
|
|
18097
18259
|
rpcSupervisor = await initializeRpcSupervisor();
|
|
18098
18260
|
if (rpcSupervisor?.state?.token) recoveryEndpointTokens.add(deriveSupervisorRecoveryToken(rpcSupervisor.state.token));
|
|
18099
18261
|
rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
|
|
18100
18262
|
installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
|
|
18101
18263
|
const initialTabs = await createInitialTabs();
|
|
18102
18264
|
await finishRpcSupervisorStartup(initialTabs);
|
|
18265
|
+
const restartTransaction = process.env.PI_WEBUI_NATIVE_RESTART_TRANSACTION;
|
|
18266
|
+
const restartToken = process.env.PI_WEBUI_NATIVE_RESTART_TOKEN;
|
|
18267
|
+
delete process.env.PI_WEBUI_NATIVE_RESTART_TRANSACTION;
|
|
18268
|
+
delete process.env.PI_WEBUI_NATIVE_RESTART_TOKEN;
|
|
18269
|
+
if (restartTransaction || restartToken) {
|
|
18270
|
+
const stateRoot = await sharedUpdateRoot();
|
|
18271
|
+
const job = restartTransaction ? await readSharedJob(stateRoot, restartTransaction) : null;
|
|
18272
|
+
const matches = job?.phase === "restart-pending" && job.lock?.token === restartToken &&
|
|
18273
|
+
job.verifiedTargets?.some((target) => target.status === "healthy" && target.installedRoot === realpathSync(packageRoot) &&
|
|
18274
|
+
target.version === packageJson.version);
|
|
18275
|
+
if (!matches || (!rpcSupervisor && restoreTabs.length > 0) ||
|
|
18276
|
+
restoreTabs.length !== initialTabs.length ||
|
|
18277
|
+
restoreTabs.some((descriptor) => !initialTabs.some((tab) => tab.id === descriptor.id))) {
|
|
18278
|
+
throw new Error("Native Web UI restart did not prove the expected runtime and restored sessions; update fence remains held.");
|
|
18279
|
+
}
|
|
18280
|
+
for (const descriptor of restoreTabs) {
|
|
18281
|
+
const tab = initialTabs.find((item) => item.id === descriptor.id);
|
|
18282
|
+
const response = await tab.rpc.send({ type: "get_state" }, 5_000);
|
|
18283
|
+
assertRestoredPiState(response, descriptor.sessionFile);
|
|
18284
|
+
if (!tab.rpc.isRunning()) throw new Error("Restored Pi child exited before session verification.");
|
|
18285
|
+
rememberTabState(tab, response.data);
|
|
18286
|
+
}
|
|
18287
|
+
await releaseEffectLocks(job.lock, { completionVerified: true });
|
|
18288
|
+
await persistSharedJob(stateRoot, { ...job, phase: job.outcome || "success", successorBootIdentity: bootIdentity });
|
|
18289
|
+
if (!initialTabs.length && options.cwdExplicit) await createTab();
|
|
18290
|
+
}
|
|
18291
|
+
startupProbeReady = true;
|
|
18292
|
+
setInterval(async () => {
|
|
18293
|
+
try {
|
|
18294
|
+
const jobsDir = path.join((await sharedUpdateRoot()), "jobs");
|
|
18295
|
+
for (const entry of (await readdir(jobsDir).catch((error) => error.code === "ENOENT" ? [] : Promise.reject(error))).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))) {
|
|
18296
|
+
await finalizeNativeJob(entry.slice(0, -5));
|
|
18297
|
+
}
|
|
18298
|
+
} catch (error) { console.warn(`Native update recovery needs attention: ${sanitizeError(error)}`); }
|
|
18299
|
+
}, 1_000).unref();
|
|
18103
18300
|
const initialTab = initialTabs[0] || null;
|
|
18104
18301
|
optionalFeatureStartupReady = true;
|
|
18105
18302
|
if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
|
|
@@ -18149,6 +18346,7 @@ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {})
|
|
|
18149
18346
|
server.closeIdleConnections?.();
|
|
18150
18347
|
});
|
|
18151
18348
|
clearTimeout(forceCloseTimer);
|
|
18349
|
+
if (nativeAdmissionState) await unregisterUpdateParticipant(nativeAdmissionState.participant).catch(() => {});
|
|
18152
18350
|
clearTimeout(forceExit);
|
|
18153
18351
|
process.exit(exitCode);
|
|
18154
18352
|
}
|