@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
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, link, mkdir, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const TERMINAL_STATES = new Set(["success", "partial", "failed", "rolled-back"]);
|
|
6
|
+
const INTERRUPTIBLE_STATES = new Set(["applying", "verifying", "activating"]);
|
|
7
|
+
const TRANSITIONS = Object.freeze({
|
|
8
|
+
planned: new Set(["applying", "failed"]),
|
|
9
|
+
applying: new Set(["verifying", "failed", "partial"]),
|
|
10
|
+
verifying: new Set(["activating", "success", "partial", "failed"]),
|
|
11
|
+
activating: new Set(["success", "partial", "failed", "rolled-back"]),
|
|
12
|
+
success: new Set(["rolled-back"]), partial: new Set(), failed: new Set(), "rolled-back": new Set(),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export function updateStatePaths(agentDir) {
|
|
16
|
+
const root = path.join(path.resolve(agentDir), "webui");
|
|
17
|
+
return Object.freeze({
|
|
18
|
+
root,
|
|
19
|
+
updatesDir: path.join(root, "updates"),
|
|
20
|
+
locksDir: path.join(root, "locks"),
|
|
21
|
+
installLock: path.join(root, "locks", "install.lock"),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function journalPath(agentDir, transactionId) {
|
|
26
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(String(transactionId || ""))) throw new TypeError("invalid transaction id");
|
|
27
|
+
return path.join(updateStatePaths(agentDir).updatesDir, `${transactionId}.json`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function writePrivateTemporary(filePath, value) {
|
|
31
|
+
await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
32
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
33
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
34
|
+
try {
|
|
35
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
36
|
+
await handle.sync();
|
|
37
|
+
} finally {
|
|
38
|
+
await handle.close();
|
|
39
|
+
}
|
|
40
|
+
await chmod(temporary, 0o600).catch(() => undefined);
|
|
41
|
+
return temporary;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function atomicJson(filePath, value) {
|
|
45
|
+
const temporary = await writePrivateTemporary(filePath, value);
|
|
46
|
+
try {
|
|
47
|
+
await rename(temporary, filePath);
|
|
48
|
+
await chmod(filePath, 0o600).catch(() => undefined);
|
|
49
|
+
} finally {
|
|
50
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function atomicCreateJson(filePath, value) {
|
|
55
|
+
const temporary = await writePrivateTemporary(filePath, value);
|
|
56
|
+
try {
|
|
57
|
+
await link(temporary, filePath);
|
|
58
|
+
await chmod(filePath, 0o600).catch(() => undefined);
|
|
59
|
+
} finally {
|
|
60
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function readUpdateJournal(agentDir, transactionId) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(await readFile(journalPath(agentDir, transactionId), "utf8"));
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error?.code === "ENOENT") return null;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function createUpdateJournal(agentDir, plan, { now = () => new Date() } = {}) {
|
|
74
|
+
if (!plan?.transactionId || !plan?.digest) throw new TypeError("persisted plan with transactionId and digest is required");
|
|
75
|
+
const filePath = journalPath(agentDir, plan.transactionId);
|
|
76
|
+
const timestamp = now().toISOString();
|
|
77
|
+
const journal = { schemaVersion: 1, transactionId: plan.transactionId, planDigest: plan.digest, state: "planned", createdAt: timestamp, updatedAt: timestamp, plan, receipts: [], history: [{ state: "planned", at: timestamp }] };
|
|
78
|
+
try {
|
|
79
|
+
await atomicCreateJson(filePath, journal);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error?.code === "EEXIST") throw Object.assign(new Error("Update journal already exists."), { code: "UPDATE_JOURNAL_EXISTS" });
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
return journal;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function transitionUpdateJournal(agentDir, transactionId, nextState, patch = {}, { now = () => new Date() } = {}) {
|
|
88
|
+
const current = await readUpdateJournal(agentDir, transactionId);
|
|
89
|
+
if (!current) throw Object.assign(new Error("Update journal not found."), { code: "UPDATE_JOURNAL_NOT_FOUND" });
|
|
90
|
+
if (!TRANSITIONS[current.state]?.has(nextState)) throw Object.assign(new Error(`Invalid update transition ${current.state} -> ${nextState}.`), { code: "UPDATE_JOURNAL_TRANSITION" });
|
|
91
|
+
const at = now().toISOString();
|
|
92
|
+
const next = { ...current, ...patch, schemaVersion: 1, transactionId: current.transactionId, planDigest: current.planDigest, plan: current.plan, state: nextState, updatedAt: at, history: [...(current.history || []), { state: nextState, at }] };
|
|
93
|
+
await atomicJson(journalPath(agentDir, transactionId), next);
|
|
94
|
+
return next;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function processAlive(pid) {
|
|
98
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error?.code === "EPERM"; }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function acquireInstallLock(agentDir, {
|
|
102
|
+
pid = process.pid,
|
|
103
|
+
now = () => new Date(),
|
|
104
|
+
staleAfterMs = 15 * 60_000,
|
|
105
|
+
isProcessAlive = processAlive,
|
|
106
|
+
} = {}) {
|
|
107
|
+
const paths = updateStatePaths(agentDir);
|
|
108
|
+
await mkdir(paths.locksDir, { recursive: true, mode: 0o700 });
|
|
109
|
+
const token = randomUUID();
|
|
110
|
+
const record = { schemaVersion: 1, token, pid, acquiredAt: now().toISOString() };
|
|
111
|
+
|
|
112
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
113
|
+
try {
|
|
114
|
+
const handle = await open(paths.installLock, "wx", 0o600);
|
|
115
|
+
await handle.writeFile(`${JSON.stringify(record)}\n`, "utf8");
|
|
116
|
+
await handle.sync();
|
|
117
|
+
await handle.close();
|
|
118
|
+
return Object.freeze({ ...record, path: paths.installLock });
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error?.code !== "EEXIST") throw error;
|
|
121
|
+
let existing = null;
|
|
122
|
+
let age = 0;
|
|
123
|
+
try {
|
|
124
|
+
existing = JSON.parse(await readFile(paths.installLock, "utf8"));
|
|
125
|
+
age = now().getTime() - new Date(existing.acquiredAt).getTime();
|
|
126
|
+
} catch {
|
|
127
|
+
const info = await stat(paths.installLock);
|
|
128
|
+
age = now().getTime() - info.mtimeMs;
|
|
129
|
+
}
|
|
130
|
+
const definitelyDead = Number.isInteger(existing?.pid) && existing.pid > 0 && !isProcessAlive(existing.pid);
|
|
131
|
+
const malformedAndOld = !existing && age > staleAfterMs;
|
|
132
|
+
if (age > staleAfterMs && (definitelyDead || malformedAndOld)) {
|
|
133
|
+
await rm(paths.installLock, { force: true });
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
throw Object.assign(new Error("Another update process owns the install lock."), { code: "UPDATE_LOCKED", owner: existing });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
throw Object.assign(new Error("Unable to acquire the install lock safely."), { code: "UPDATE_LOCKED" });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function transferInstallLock(lock, pid, { now = () => new Date() } = {}) {
|
|
143
|
+
if (!lock?.path || !lock?.token || !Number.isInteger(pid) || pid <= 0) throw new TypeError("lock token and live destination pid are required");
|
|
144
|
+
const current = JSON.parse(await readFile(lock.path, "utf8"));
|
|
145
|
+
if (current.token !== lock.token) throw Object.assign(new Error("Install lock ownership changed before transfer."), { code: "UPDATE_LOCK_OWNERSHIP_CHANGED" });
|
|
146
|
+
const next = { ...current, pid, transferredAt: now().toISOString() };
|
|
147
|
+
await atomicJson(lock.path, next);
|
|
148
|
+
return Object.freeze({ ...next, path: lock.path });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function releaseInstallLock(lock) {
|
|
152
|
+
if (!lock?.path || !lock?.token) return false;
|
|
153
|
+
let current;
|
|
154
|
+
try { current = JSON.parse(await readFile(lock.path, "utf8")); } catch { return false; }
|
|
155
|
+
if (current.token !== lock.token) return false;
|
|
156
|
+
await rm(lock.path, { force: true });
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function reconcileInterruptedUpdates(agentDir, { recover, now = () => new Date() } = {}) {
|
|
161
|
+
const paths = updateStatePaths(agentDir);
|
|
162
|
+
let entries;
|
|
163
|
+
try { entries = await readdir(paths.updatesDir); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
|
|
164
|
+
const results = [];
|
|
165
|
+
for (const entry of entries.filter((name) => name.endsWith(".json")).sort()) {
|
|
166
|
+
const transactionId = entry.slice(0, -5);
|
|
167
|
+
const journal = await readUpdateJournal(agentDir, transactionId);
|
|
168
|
+
if (!journal || TERMINAL_STATES.has(journal.state) || !INTERRUPTIBLE_STATES.has(journal.state)) continue;
|
|
169
|
+
let recovery = { state: "failed", error: "Update interrupted before completion." };
|
|
170
|
+
if (typeof recover === "function") recovery = await recover(journal) || recovery;
|
|
171
|
+
const nextState = journal.state === "activating" && recovery.state === "rolled-back" ? "rolled-back" : "failed";
|
|
172
|
+
results.push(await transitionUpdateJournal(agentDir, transactionId, nextState, { ...recovery, state: nextState, reconciled: true }, { now }));
|
|
173
|
+
}
|
|
174
|
+
return results;
|
|
175
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
const REFUSALS = Object.freeze({
|
|
4
|
+
pnpm: "This package is owned by pnpm. Update it manually with the owning pnpm installation.",
|
|
5
|
+
yarn: "This package is owned by Yarn. Update it manually with the owning Yarn installation.",
|
|
6
|
+
source: "Source checkouts are never mutated automatically. Pull and rebuild this checkout manually.",
|
|
7
|
+
linked: "Linked packages are never mutated automatically. Update the link target manually.",
|
|
8
|
+
unknown: "Package ownership could not be proven. Update the package manually with its owning tool.",
|
|
9
|
+
opaque: "The installation root is opaque or outside its declared owner root; automatic update is refused.",
|
|
10
|
+
nested: "Only exact top-level packages may be updated automatically; transitive packages are refused.",
|
|
11
|
+
optional: "Optional packages require explicit Pi-owned registration before automatic update.",
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
function bounded(value, max = 320) {
|
|
15
|
+
const text = String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
|
16
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function inside(root, candidate) {
|
|
20
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
21
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function refusal(code, manager, detail = "") {
|
|
25
|
+
return Object.freeze({
|
|
26
|
+
accepted: false,
|
|
27
|
+
code,
|
|
28
|
+
manager: manager || "unknown",
|
|
29
|
+
guidance: bounded(detail || REFUSALS[code] || REFUSALS.unknown),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Fail-closed package ownership classification for exact top-level targets. */
|
|
34
|
+
export function classifyPackageOwner({
|
|
35
|
+
manager = "unknown",
|
|
36
|
+
packageRoot = "",
|
|
37
|
+
ownerRoot = "",
|
|
38
|
+
topLevel = true,
|
|
39
|
+
linked = false,
|
|
40
|
+
sourceCheckout = false,
|
|
41
|
+
optional = false,
|
|
42
|
+
piOwned = false,
|
|
43
|
+
} = {}) {
|
|
44
|
+
const normalizedManager = String(manager || "unknown").trim().toLowerCase();
|
|
45
|
+
if (sourceCheckout) return refusal("source", normalizedManager);
|
|
46
|
+
if (linked) return refusal("linked", normalizedManager);
|
|
47
|
+
if (!topLevel) return refusal("nested", normalizedManager);
|
|
48
|
+
if (optional && !piOwned) return refusal("optional", normalizedManager);
|
|
49
|
+
if (normalizedManager === "pnpm" || normalizedManager === "yarn") return refusal(normalizedManager, normalizedManager);
|
|
50
|
+
if (!["npm", "bun", "pi"].includes(normalizedManager)) return refusal("unknown", normalizedManager);
|
|
51
|
+
if (!packageRoot || !ownerRoot) return refusal("opaque", normalizedManager);
|
|
52
|
+
try {
|
|
53
|
+
if (!inside(ownerRoot, packageRoot)) return refusal("opaque", normalizedManager);
|
|
54
|
+
} catch {
|
|
55
|
+
return refusal("opaque", normalizedManager);
|
|
56
|
+
}
|
|
57
|
+
return Object.freeze({
|
|
58
|
+
accepted: true,
|
|
59
|
+
code: "owned",
|
|
60
|
+
manager: normalizedManager,
|
|
61
|
+
packageRoot: path.resolve(packageRoot),
|
|
62
|
+
ownerRoot: path.resolve(ownerRoot),
|
|
63
|
+
scope: optional ? "pi-owned-optional" : "core",
|
|
64
|
+
topLevel: true,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function ownershipRefusalGuidance(code) {
|
|
69
|
+
return bounded(REFUSALS[code] || REFUSALS.unknown);
|
|
70
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { classifyPackageOwner } from "./owners.mjs";
|
|
3
|
+
|
|
4
|
+
const EXACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
|
|
5
|
+
|
|
6
|
+
function clean(value) {
|
|
7
|
+
return String(value ?? "").trim();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function canonicalValue(value) {
|
|
11
|
+
if (Array.isArray(value)) return value.map(canonicalValue);
|
|
12
|
+
if (!value || typeof value !== "object") return value;
|
|
13
|
+
return Object.fromEntries(Object.keys(value).sort().filter((key) => value[key] !== undefined).map((key) => [key, canonicalValue(value[key])]));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function canonicalPlanJson(value) {
|
|
17
|
+
return JSON.stringify(canonicalValue(value));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function digestUpdatePlan(plan) {
|
|
21
|
+
const { digest: _digest, ...unsigned } = plan || {};
|
|
22
|
+
return createHash("sha256").update(canonicalPlanJson(unsigned)).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function exactVersion(value, label) {
|
|
26
|
+
const normalized = clean(value).replace(/^v/i, "");
|
|
27
|
+
if (!EXACT_VERSION.test(normalized)) throw new TypeError(`${label} must resolve to an exact version`);
|
|
28
|
+
return normalized;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function registryUrl(value, label) {
|
|
32
|
+
const normalized = clean(value);
|
|
33
|
+
let parsed;
|
|
34
|
+
try { parsed = new URL(normalized); } catch { throw new TypeError(`${label} must be an absolute HTTP(S) registry URL`); }
|
|
35
|
+
if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.hash) {
|
|
36
|
+
throw new TypeError(`${label} must be a credential-free HTTP(S) registry URL`);
|
|
37
|
+
}
|
|
38
|
+
return parsed.href;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function commandRecord(command) {
|
|
42
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) throw new TypeError("target command must be an object");
|
|
43
|
+
const executable = clean(command.command);
|
|
44
|
+
if (!executable || !Array.isArray(command.args)) throw new TypeError("target command requires command and an argument array");
|
|
45
|
+
return Object.freeze({ command: executable, args: Object.freeze(command.args.map(String)) });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Resolve moving tags exactly once and bind all apply inputs into one digest. */
|
|
49
|
+
export async function createUpdatePlan({
|
|
50
|
+
transactionId = randomUUID(),
|
|
51
|
+
createdAt = new Date().toISOString(),
|
|
52
|
+
registry = "",
|
|
53
|
+
identities = [],
|
|
54
|
+
candidates = [],
|
|
55
|
+
resolveExactTarget,
|
|
56
|
+
} = {}) {
|
|
57
|
+
if (typeof resolveExactTarget !== "function") throw new TypeError("resolveExactTarget is required");
|
|
58
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(clean(transactionId))) throw new TypeError("transactionId is invalid");
|
|
59
|
+
const createdTimestamp = new Date(createdAt);
|
|
60
|
+
if (!Number.isFinite(createdTimestamp.getTime())) throw new TypeError("createdAt is invalid");
|
|
61
|
+
const identityRecords = identities.map((identity) => Object.freeze(canonicalValue(identity)));
|
|
62
|
+
const identityIds = new Set(identityRecords.map((identity) => clean(identity.canonicalId)).filter(Boolean));
|
|
63
|
+
if (identityIds.size !== identityRecords.length) throw new TypeError("every plan identity requires a unique canonicalId");
|
|
64
|
+
const targets = [];
|
|
65
|
+
const refusals = [];
|
|
66
|
+
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
const id = clean(candidate?.id);
|
|
69
|
+
if (!id) throw new TypeError("every candidate requires an id");
|
|
70
|
+
const owner = classifyPackageOwner(candidate.owner);
|
|
71
|
+
if (!owner.accepted) {
|
|
72
|
+
refusals.push(Object.freeze({ id, packageName: clean(candidate.packageName), ...owner }));
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const resolved = await resolveExactTarget(Object.freeze({
|
|
76
|
+
id,
|
|
77
|
+
packageName: clean(candidate.packageName),
|
|
78
|
+
requested: clean(candidate.requested || "latest"),
|
|
79
|
+
registry: clean(candidate.registry || registry),
|
|
80
|
+
}));
|
|
81
|
+
const targetVersion = exactVersion(resolved?.version, `${id} target`);
|
|
82
|
+
const currentVersion = exactVersion(candidate.currentVersion, `${id} current version`);
|
|
83
|
+
const targetRegistry = registryUrl(resolved?.registry || candidate.registry || registry, `${id} registry`);
|
|
84
|
+
const packageName = clean(candidate.packageName);
|
|
85
|
+
const identityId = clean(candidate.identityId);
|
|
86
|
+
if (!packageName) throw new TypeError(`${id} packageName is required`);
|
|
87
|
+
if (!identityIds.has(identityId)) throw new TypeError(`${id} identityId must reference a canonical plan identity`);
|
|
88
|
+
if (targetVersion === currentVersion) continue;
|
|
89
|
+
targets.push(Object.freeze({
|
|
90
|
+
id,
|
|
91
|
+
kind: clean(candidate.kind || "package"),
|
|
92
|
+
packageName,
|
|
93
|
+
identityId,
|
|
94
|
+
currentVersion,
|
|
95
|
+
targetVersion,
|
|
96
|
+
registry: targetRegistry,
|
|
97
|
+
strategy: clean(candidate.strategy || owner.manager),
|
|
98
|
+
owner,
|
|
99
|
+
command: commandRecord(await candidate.commandForVersion(targetVersion, targetRegistry)),
|
|
100
|
+
metadata: Object.freeze(canonicalValue(resolved?.metadata || {})),
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const unsigned = Object.freeze({
|
|
105
|
+
schemaVersion: 1,
|
|
106
|
+
transactionId: clean(transactionId),
|
|
107
|
+
createdAt: createdTimestamp.toISOString(),
|
|
108
|
+
registry: registry ? registryUrl(registry, "plan registry") : "",
|
|
109
|
+
identities: Object.freeze(identityRecords),
|
|
110
|
+
targets: Object.freeze(targets),
|
|
111
|
+
refusals: Object.freeze(refusals),
|
|
112
|
+
});
|
|
113
|
+
const digest = digestUpdatePlan(unsigned);
|
|
114
|
+
return Object.freeze({ ...unsigned, digest });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function assertUpdatePlanDigest(plan, suppliedDigest) {
|
|
118
|
+
const expected = digestUpdatePlan(plan);
|
|
119
|
+
if (!/^[a-f0-9]{64}$/.test(clean(suppliedDigest)) || suppliedDigest !== plan?.digest || suppliedDigest !== expected) {
|
|
120
|
+
const error = new Error("Update plan digest does not match the persisted exact-target plan.");
|
|
121
|
+
error.code = "UPDATE_PLAN_DIGEST_MISMATCH";
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function assertPlanIdentity(planTarget, activeIdentity) {
|
|
128
|
+
if (!planTarget?.identityId || planTarget.identityId !== activeIdentity?.canonicalId) {
|
|
129
|
+
const error = new Error(`Active identity changed before applying ${planTarget?.id || "update target"}.`);
|
|
130
|
+
error.code = "UPDATE_IDENTITY_CHANGED";
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { resolveCommandDirectory, resolvePiCommandInvocation } from "../npm-command.mjs";
|
|
4
|
+
|
|
5
|
+
const VERSION_PATTERN = /(?:^|\s)v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)(?=\s|$)/m;
|
|
6
|
+
|
|
7
|
+
function clean(value) {
|
|
8
|
+
return String(value ?? "").trim();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function parseRuntimeVersion(value) {
|
|
12
|
+
return clean(value).match(VERSION_PATTERN)?.[1] || "";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function pathApi(platform) {
|
|
16
|
+
return platform === "win32" ? path.win32 : path.posix;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function canonicalize(filePath, runtime) {
|
|
20
|
+
if (!filePath) return "";
|
|
21
|
+
const realpath = runtime.realpathSync ?? realpathSync;
|
|
22
|
+
try {
|
|
23
|
+
return realpath(filePath);
|
|
24
|
+
} catch {
|
|
25
|
+
return pathApi(runtime.platform ?? process.platform).resolve(filePath);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function resolvedExecutablePath(command, runtime) {
|
|
30
|
+
const api = pathApi(runtime.platform ?? process.platform);
|
|
31
|
+
const value = clean(command).replace(/^"|"$/g, "");
|
|
32
|
+
if (api.isAbsolute(value) || value.includes("/") || value.includes("\\")) return value;
|
|
33
|
+
const directory = resolveCommandDirectory(value, runtime);
|
|
34
|
+
return directory ? api.join(directory, value) : value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function cliFromInvocation(invocation) {
|
|
38
|
+
const first = invocation.args?.[0] || "";
|
|
39
|
+
return /(?:^|[\\/])cli\.(?:c?js|mjs)$/i.test(first) ? first : "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function packageRootFromCli(cliPath, platform) {
|
|
43
|
+
if (!cliPath) return "";
|
|
44
|
+
const api = pathApi(platform);
|
|
45
|
+
const normalized = api.normalize(cliPath);
|
|
46
|
+
return api.basename(api.dirname(normalized)).toLowerCase() === "dist"
|
|
47
|
+
? api.dirname(api.dirname(normalized))
|
|
48
|
+
: api.dirname(normalized);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function explicitResolution(command, runtime) {
|
|
52
|
+
const platform = runtime.platform ?? process.platform;
|
|
53
|
+
const api = pathApi(platform);
|
|
54
|
+
const exists = runtime.existsSync ?? existsSync;
|
|
55
|
+
const requested = clean(command).replace(/^"|"$/g, "");
|
|
56
|
+
if (!requested) return { ok: false, reason: "No explicit Pi executable was supplied." };
|
|
57
|
+
const isPath = api.isAbsolute(requested) || requested.includes("/") || requested.includes("\\");
|
|
58
|
+
const directory = resolveCommandDirectory(requested, runtime);
|
|
59
|
+
if (!isPath && !directory) {
|
|
60
|
+
return { ok: false, reason: "The explicit Pi command is opaque or cannot be resolved to one executable." };
|
|
61
|
+
}
|
|
62
|
+
if (isPath) {
|
|
63
|
+
try {
|
|
64
|
+
if (!exists(requested) && !directory) return { ok: false, reason: "The explicit Pi executable does not exist." };
|
|
65
|
+
} catch {
|
|
66
|
+
return { ok: false, reason: "The explicit Pi executable cannot be inspected safely." };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { ok: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function probePi({ command, source, runCommand, runtime, timeoutMs, probeVersion }) {
|
|
73
|
+
const invocation = resolvePiCommandInvocation(command, [], runtime);
|
|
74
|
+
const cliPath = cliFromInvocation(invocation);
|
|
75
|
+
let version = "";
|
|
76
|
+
if (probeVersion) {
|
|
77
|
+
const result = await runCommand(invocation.command, [...invocation.args, "--version"], {
|
|
78
|
+
timeoutMs,
|
|
79
|
+
maxOutputLength: 4_000,
|
|
80
|
+
});
|
|
81
|
+
version = result?.exitCode === 0 && !result?.timedOut && !result?.error
|
|
82
|
+
? parseRuntimeVersion(`${result.stdout || ""}\n${result.stderr || ""}`)
|
|
83
|
+
: "";
|
|
84
|
+
if (!version) return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const canonicalCli = canonicalize(cliPath, runtime);
|
|
88
|
+
const canonicalExecutable = canonicalize(resolvedExecutablePath(invocation.command, runtime), runtime);
|
|
89
|
+
const canonicalRequested = canonicalize(resolvedExecutablePath(command, runtime), runtime);
|
|
90
|
+
const identityPath = canonicalCli || (source === "explicit" ? canonicalRequested : canonicalExecutable);
|
|
91
|
+
return Object.freeze({
|
|
92
|
+
kind: "pi",
|
|
93
|
+
source,
|
|
94
|
+
version,
|
|
95
|
+
canonicalId: `pi:${identityPath}`,
|
|
96
|
+
executable: canonicalExecutable,
|
|
97
|
+
cliPath: canonicalCli,
|
|
98
|
+
packageRoot: packageRootFromCli(canonicalCli, runtime.platform ?? process.platform)
|
|
99
|
+
|| (source === "explicit" && canonicalRequested ? pathApi(runtime.platform ?? process.platform).dirname(canonicalRequested) : ""),
|
|
100
|
+
invocation: Object.freeze({ command: invocation.command, args: Object.freeze([...invocation.args]) }),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Resolve the same Pi runtime used for tabs and updates. Bundled Pi wins over
|
|
106
|
+
* PATH unless an exact explicit executable was supplied. PATH is reported
|
|
107
|
+
* separately and is never selected merely because it is newer.
|
|
108
|
+
*/
|
|
109
|
+
export async function resolveCanonicalPiRuntime({
|
|
110
|
+
explicitCommand = "",
|
|
111
|
+
bundledCli = "",
|
|
112
|
+
pathCommand = "pi",
|
|
113
|
+
runCommand,
|
|
114
|
+
timeoutMs = 10_000,
|
|
115
|
+
probeVersion = true,
|
|
116
|
+
runtime = {},
|
|
117
|
+
} = {}) {
|
|
118
|
+
if (typeof runCommand !== "function") throw new TypeError("runCommand is required");
|
|
119
|
+
const exists = runtime.existsSync ?? existsSync;
|
|
120
|
+
const explicit = clean(explicitCommand);
|
|
121
|
+
|
|
122
|
+
if (explicit) {
|
|
123
|
+
const resolution = explicitResolution(explicit, runtime);
|
|
124
|
+
if (!resolution.ok) {
|
|
125
|
+
return Object.freeze({ active: null, path: null, refusal: Object.freeze({ code: "explicit-pi-unresolved", message: resolution.reason }) });
|
|
126
|
+
}
|
|
127
|
+
const active = await probePi({ command: explicit, source: "explicit", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null);
|
|
128
|
+
return Object.freeze({
|
|
129
|
+
active,
|
|
130
|
+
path: null,
|
|
131
|
+
refusal: active ? null : Object.freeze({ code: "explicit-pi-unverifiable", message: "The exact explicit Pi executable did not report a supported version." }),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let bundledAvailable = false;
|
|
136
|
+
try { bundledAvailable = Boolean(bundledCli && exists(bundledCli)); } catch {}
|
|
137
|
+
const active = bundledAvailable
|
|
138
|
+
? await probePi({ command: bundledCli, source: "bundled", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null)
|
|
139
|
+
: await probePi({ command: pathCommand, source: "path", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null);
|
|
140
|
+
const pathIdentity = bundledAvailable
|
|
141
|
+
? await probePi({ command: pathCommand, source: "path", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null)
|
|
142
|
+
: active;
|
|
143
|
+
|
|
144
|
+
return Object.freeze({
|
|
145
|
+
active,
|
|
146
|
+
path: pathIdentity,
|
|
147
|
+
refusal: active ? null : Object.freeze({ code: "pi-runtime-unverifiable", message: "No supported active Pi runtime could be verified." }),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function resolveWebuiRuntimeIdentity({ packageRoot, packageName, version, owner } = {}, runtime = {}) {
|
|
152
|
+
const root = canonicalize(packageRoot, runtime);
|
|
153
|
+
const normalizedVersion = clean(version).replace(/^v/i, "");
|
|
154
|
+
if (!root || !packageName || !normalizedVersion) throw new TypeError("packageRoot, packageName, and version are required");
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
kind: "webui",
|
|
157
|
+
source: "active-package",
|
|
158
|
+
packageName: clean(packageName),
|
|
159
|
+
version: normalizedVersion,
|
|
160
|
+
packageRoot: root,
|
|
161
|
+
owner: owner ? Object.freeze({ ...owner }) : null,
|
|
162
|
+
canonicalId: `webui:${root}`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function sameRuntimeIdentity(left, right) {
|
|
167
|
+
return Boolean(left?.canonicalId && right?.canonicalId && left.canonicalId === right.canonicalId);
|
|
168
|
+
}
|