@firstpick/pi-package-webui 0.8.6 → 0.8.8

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.
Files changed (90) hide show
  1. package/README.md +18 -606
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +562 -524
  5. package/index.ts +8 -5
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +17 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-preferences.mjs +16 -1
  11. package/lib/subagent-launch-slots.mjs +14 -2
  12. package/lib/trust-boundaries.mjs +3 -0
  13. package/lib/update/executor.mjs +99 -0
  14. package/lib/update/journal.mjs +175 -0
  15. package/lib/update/owners.mjs +70 -0
  16. package/lib/update/plan.mjs +134 -0
  17. package/lib/update/resolver.mjs +168 -0
  18. package/lib/update/supervisor.mjs +238 -0
  19. package/lib/update/verify.mjs +52 -0
  20. package/lib/update-commands.mjs +25 -13
  21. package/lib/webui-workspaces.mjs +17 -1
  22. package/package.json +4 -4
  23. package/public/app.js +1543 -109
  24. package/public/index.html +146 -48
  25. package/public/middle-button-drag-scroll.mjs +154 -0
  26. package/public/sampling-parameter-controls.mjs +361 -0
  27. package/public/service-worker.js +3 -1
  28. package/public/styles.css +512 -1
  29. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  30. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  31. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  32. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  33. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  34. package/tests/browser/update-reconnect.spec.mjs +92 -0
  35. package/tests/codex-fast-mode-static.test.mjs +2 -2
  36. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  37. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  38. package/tests/component-update-api-static.test.mjs +22 -61
  39. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  40. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  41. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  42. package/tests/fast-mode-client-static.test.mjs +1 -1
  43. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  44. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  45. package/tests/fixtures/fake-pi.mjs +68 -1
  46. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  47. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  48. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  49. package/tests/http-endpoints-harness.test.mjs +68 -18
  50. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  51. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  52. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  53. package/tests/mobile-foundation-static.test.mjs +4 -4
  54. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  55. package/tests/mobile-static.test.mjs +217 -24
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +13 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/prompt-routing-tab-status.test.mjs +8 -0
  60. package/tests/questionnaire-dialog.test.mjs +3 -3
  61. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  62. package/tests/rpc-supervisor-host.test.mjs +11 -2
  63. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  64. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  65. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  66. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  67. package/tests/sampling-parameter-controls.test.mjs +241 -0
  68. package/tests/session-sampling-helper.test.mjs +228 -0
  69. package/tests/session-sampling-http.test.mjs +168 -0
  70. package/tests/session-sampling-ui-static.test.mjs +370 -0
  71. package/tests/session-summary-core.test.mjs +24 -11
  72. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  73. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  74. package/tests/staged-content-hash-contract.test.mjs +52 -11
  75. package/tests/subagent-launch-slots.test.mjs +18 -1
  76. package/tests/theme-customizer-static.test.mjs +1 -1
  77. package/tests/ui-layout-settings.test.mjs +18 -1
  78. package/tests/update-api-harness.test.mjs +111 -0
  79. package/tests/update-commands.test.mjs +15 -45
  80. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  81. package/tests/update-journal-harness.test.mjs +59 -0
  82. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  83. package/tests/update-owners.test.mjs +27 -0
  84. package/tests/update-plan.test.mjs +58 -0
  85. package/tests/update-resolver.test.mjs +56 -0
  86. package/tests/update-supervisor-harness.test.mjs +57 -0
  87. package/tests/update-tab-restore-harness.test.mjs +24 -0
  88. package/tests/update-verify.test.mjs +31 -0
  89. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  90. package/webui-rpc-helper.mjs +119 -0
package/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawn, type ChildProcessByStdio } from "node:child_process";
2
2
  import path from "node:path";
3
+ import { homedir } from "node:os";
3
4
  import type { Readable } from "node:stream";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
@@ -7,6 +8,7 @@ import { delay, takeValue, tokenizeArgs } from "@firstpick/pi-utils";
7
8
  import { detachChildProcess as releaseStartedChild, isProcessRunning, terminateChildProcess as terminateFailedChild } from "@firstpick/pi-utils/process";
8
9
  import { fetchJsonWithTimeout as fetchJsonWithTimeoutBase } from "@firstpick/pi-utils/http";
9
10
  import { registerSubagentGate } from "./lib/subagent-gate.mjs";
11
+ import { createRestoreFile } from "./lib/update/supervisor.mjs";
10
12
  import {
11
13
  gitWorkflowPreferencesSummary,
12
14
  readGitWorkflowPreferences,
@@ -16,7 +18,8 @@ import {
16
18
 
17
19
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
20
  const packageRoot = __dirname;
19
- const webuiBin = path.join(packageRoot, "bin", "pi-webui.mjs");
21
+ const webuiBin = path.join(packageRoot, "bin", "pi-webui-launcher.mjs");
22
+ const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
20
23
 
21
24
  const DEFAULT_HOST = "127.0.0.1";
22
25
  const DEFAULT_PORT = 31415;
@@ -216,7 +219,7 @@ function restorableTabsFromStatus(tabs: unknown, options: StartWebuiOptions): Re
216
219
  if (!options.noSession) restoreTab.sessionFile = boundedString(state.sessionFile || tab.sessionFile, 4096);
217
220
 
218
221
  restored.push(restoreTab);
219
- if (restored.length >= 30) break;
222
+ if (restored.length >= 256) break;
220
223
  }
221
224
  return restored;
222
225
  }
@@ -247,7 +250,7 @@ function mergeRestorableTabsFromStatusSources(sources: unknown[], options: Start
247
250
  const keys = restorableTabKeys(tab);
248
251
  const existingIndex = keys.map((key) => keyToIndex.get(key)).find((index): index is number => index !== undefined);
249
252
  if (existingIndex === undefined) {
250
- if (merged.length >= 30) continue;
253
+ if (merged.length >= 256) continue;
251
254
  const index = merged.length;
252
255
  merged.push(tab);
253
256
  for (const key of keys) keyToIndex.set(key, index);
@@ -258,7 +261,7 @@ function mergeRestorableTabsFromStatusSources(sources: unknown[], options: Start
258
261
  }
259
262
  }
260
263
 
261
- return merged.slice(0, 30);
264
+ return merged.slice(0, 256);
262
265
  }
263
266
 
264
267
  async function fetchRestorableTabs(url: string, existing: ExistingWebui, options: StartWebuiOptions): Promise<RestorableWebuiTab[]> {
@@ -463,7 +466,7 @@ async function startWebui(options: StartWebuiOptions, ctx: ExtensionCommandConte
463
466
  if (options.piArgs.length > 0) args.push("--", ...options.piArgs);
464
467
 
465
468
  const env = { ...process.env };
466
- if (restoreTabs.length > 0) env.PI_WEBUI_RESTORE_TABS = JSON.stringify(restoreTabs);
469
+ if (restoreTabs.length > 0) env.PI_WEBUI_RESTORE_FILE = (await createRestoreFile(agentDir, restoreTabs)).file;
467
470
 
468
471
  const child = spawn(process.execPath, args, {
469
472
  cwd: ctx.cwd,
@@ -37,6 +37,27 @@ export function validateComponentUpdateRequest(body) {
37
37
  return { ok: true, target: body.target };
38
38
  }
39
39
 
40
+ export function validateUpdatePlanRequest(body) {
41
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "Request body must be an object." };
42
+ const keys = Object.keys(body).sort();
43
+ if (keys.some((key) => !["targets"].includes(key)) || !Array.isArray(body.targets) || body.targets.length < 1 || body.targets.length > 2) {
44
+ return { ok: false, error: "targets must contain one or both exact values: pi, webui." };
45
+ }
46
+ const targets = [...new Set(body.targets)];
47
+ if (targets.length !== body.targets.length || targets.some((target) => !TARGET_SET.has(target))) return { ok: false, error: "targets contains an unsupported or duplicate target." };
48
+ return { ok: true, targets };
49
+ }
50
+
51
+ export function validateUpdateApplyRequest(body) {
52
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "Request body must be an object." };
53
+ const keys = Object.keys(body).sort();
54
+ if (keys.join(",") !== "planDigest,transactionId") return { ok: false, error: "Apply accepts only transactionId and planDigest." };
55
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(String(body.transactionId || "")) || !/^[a-f0-9]{64}$/.test(String(body.planDigest || ""))) {
56
+ return { ok: false, error: "transactionId or planDigest is invalid." };
57
+ }
58
+ return { ok: true, transactionId: body.transactionId, planDigest: body.planDigest };
59
+ }
60
+
40
61
  function initialState(target) {
41
62
  return {
42
63
  target,
@@ -249,6 +249,21 @@ async function readSettingsLockRecords(lockDirectory) {
249
249
  }));
250
250
  }
251
251
 
252
+ async function renameWithWindowsRetry(source, target) {
253
+ let lastError;
254
+ for (let attempt = 0; attempt < 12; attempt += 1) {
255
+ try {
256
+ await rename(source, target);
257
+ return;
258
+ } catch (error) {
259
+ lastError = error;
260
+ if (process.platform !== "win32" || !["EACCES", "EBUSY", "EPERM"].includes(error?.code)) throw error;
261
+ await delay(25 * (attempt + 1));
262
+ }
263
+ }
264
+ throw lastError;
265
+ }
266
+
252
267
  async function writeSettingsLockRecord(recordFile, value) {
253
268
  const temporaryFile = `${recordFile}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
254
269
  let handle;
@@ -258,7 +273,7 @@ async function writeSettingsLockRecord(recordFile, value) {
258
273
  await handle.sync();
259
274
  await handle.close();
260
275
  handle = undefined;
261
- await rename(temporaryFile, recordFile);
276
+ await renameWithWindowsRetry(temporaryFile, recordFile);
262
277
  } catch (error) {
263
278
  await handle?.close().catch(() => {});
264
279
  await rm(temporaryFile, { force: true }).catch(() => {});
@@ -360,7 +375,7 @@ async function writePrivateAtomicSettings(storageFile, value) {
360
375
  await handle.sync();
361
376
  await handle.close();
362
377
  handle = undefined;
363
- await rename(temporaryFile, storageFile);
378
+ await renameWithWindowsRetry(temporaryFile, storageFile);
364
379
  await syncDirectoryBestEffort(path.dirname(storageFile));
365
380
  } catch (error) {
366
381
  await handle?.close().catch(() => {});
@@ -7,6 +7,7 @@ const entries = [
7
7
  ["releaseAur", "@firstpick/pi-extension-release-aur", "^0.1.8"],
8
8
  ["aurReview", "@firstpick/pi-extension-aur-review", "^0.1.1"],
9
9
  ["workflows", "@firstpick/pi-extension-workflows", "^0.1.7"],
10
+ ["featureSystemPrompt", "@firstpick/pi-extension-feature-system-prompt", "^0.1.3"],
10
11
  ["safetyGuard", "@firstpick/pi-extension-safety-guard", "^0.2.6"],
11
12
  ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills", "^0.1.9"],
12
13
  ["todoProgressWidget", "@firstpick/pi-extension-todo-progress", "^0.2.9"],
@@ -0,0 +1,160 @@
1
+ import { SAMPLING_PARAMETER_KEYS } from "../public/sampling-parameter-controls.mjs";
2
+
3
+ export { SAMPLING_PARAMETER_KEYS };
4
+
5
+ export const BUILTIN_SAMPLING_APIS = Object.freeze([
6
+ "openai-completions",
7
+ "openai-responses",
8
+ "azure-openai-responses",
9
+ "openai-codex-responses",
10
+ "anthropic-messages",
11
+ "google-generative-ai",
12
+ "google-vertex",
13
+ "bedrock-converse-stream",
14
+ "mistral-conversations",
15
+ "pi-messages",
16
+ ]);
17
+
18
+ const LABELS = Object.freeze({
19
+ temperature: "Temperature",
20
+ top_p: "Top P",
21
+ frequency_penalty: "Frequency Penalty",
22
+ presence_penalty: "Presence Penalty",
23
+ seed: "Seed",
24
+ top_k: "Top K",
25
+ min_p: "Min P",
26
+ });
27
+
28
+ const API_KEYS = Object.freeze({
29
+ "openai-completions": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed"],
30
+ "openai-responses": ["temperature", "top_p"],
31
+ "azure-openai-responses": ["temperature", "top_p"],
32
+ "openai-codex-responses": ["temperature"],
33
+ "anthropic-messages": ["temperature"],
34
+ "google-generative-ai": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "top_k"],
35
+ "google-vertex": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "top_k"],
36
+ "bedrock-converse-stream": ["temperature", "top_p"],
37
+ "mistral-conversations": ["temperature"],
38
+ "pi-messages": ["temperature"],
39
+ });
40
+
41
+ function plainObject(value) {
42
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
43
+ const prototype = Object.getPrototypeOf(value);
44
+ return prototype === Object.prototype || prototype === null;
45
+ }
46
+
47
+ function activeAnthropicThinking(model, thinkingLevel) {
48
+ return model?.reasoning === true && typeof thinkingLevel === "string" && thinkingLevel !== "off";
49
+ }
50
+
51
+ function unsupportedReason(api, key) {
52
+ if (!api || !Object.hasOwn(API_KEYS, api)) {
53
+ return `${LABELS[key]} is disabled because this provider has not declared support.`;
54
+ }
55
+ return `${api} does not declare ${LABELS[key]} support.`;
56
+ }
57
+
58
+ /** Resolve deterministic, per-key support from the active model contract. */
59
+ export function resolveSamplingParameterCapabilities(model, { thinkingLevel } = {}) {
60
+ const api = typeof model?.api === "string" ? model.api : null;
61
+ const declared = Object.hasOwn(API_KEYS, api) ? new Set(API_KEYS[api]) : new Set();
62
+ const defaults = plainObject(model?.samplingParams) ? model.samplingParams : {};
63
+ const parameters = {};
64
+
65
+ for (const key of SAMPLING_PARAMETER_KEYS) {
66
+ let supported = declared.has(key);
67
+ let source = supported ? "api" : "unsupported";
68
+ let reason = supported ? `Supported by ${api}.` : unsupportedReason(api, key);
69
+
70
+ if (api === "openai-completions" && (key === "top_k" || key === "min_p") && Object.hasOwn(defaults, key)) {
71
+ supported = true;
72
+ source = "model";
73
+ reason = `Supported by ${api} because the active model declares ${LABELS[key]}.`;
74
+ }
75
+
76
+ if (api === "anthropic-messages" && key === "temperature" && supported) {
77
+ if (model?.compat?.supportsTemperature === false) {
78
+ supported = false;
79
+ source = "unsupported";
80
+ reason = "Temperature is disabled because the active Anthropic model marks it unsupported.";
81
+ } else if (activeAnthropicThinking(model, thinkingLevel)) {
82
+ supported = false;
83
+ source = "unsupported";
84
+ reason = "Temperature is disabled while Anthropic extended thinking is active.";
85
+ }
86
+ }
87
+
88
+ parameters[key] = { supported, reason, source };
89
+ }
90
+
91
+ return parameters;
92
+ }
93
+
94
+ export function filterSupportedSamplingParameters(values, parameters) {
95
+ if (!plainObject(values)) return {};
96
+ const filtered = {};
97
+ for (const key of SAMPLING_PARAMETER_KEYS) {
98
+ if (parameters?.[key]?.supported === true && Object.hasOwn(values, key)) filtered[key] = values[key];
99
+ }
100
+ return filtered;
101
+ }
102
+
103
+ function mergeNested(payload, property, additions) {
104
+ const existing = plainObject(payload[property]) ? payload[property] : {};
105
+ return { ...payload, [property]: { ...existing, ...additions } };
106
+ }
107
+
108
+ function anthropicPayloadHasThinking(payload) {
109
+ const type = plainObject(payload.thinking) ? payload.thinking.type : undefined;
110
+ return type === "enabled" || type === "adaptive";
111
+ }
112
+
113
+ /** Apply already-stored values to an API-native provider payload without mutating it. */
114
+ export function applySupportedSamplingParameters(payload, model, values, { thinkingLevel } = {}) {
115
+ if (!plainObject(payload)) return undefined;
116
+ const api = typeof model?.api === "string" ? model.api : null;
117
+ const parameters = resolveSamplingParameterCapabilities(model, { thinkingLevel });
118
+ const supported = filterSupportedSamplingParameters(values, parameters);
119
+ if (Object.keys(supported).length === 0) return undefined;
120
+
121
+ if (api === "anthropic-messages" && anthropicPayloadHasThinking(payload)) {
122
+ delete supported.temperature;
123
+ if (Object.keys(supported).length === 0) return undefined;
124
+ }
125
+
126
+ switch (api) {
127
+ case "openai-completions":
128
+ case "openai-responses":
129
+ case "azure-openai-responses":
130
+ case "openai-codex-responses":
131
+ case "anthropic-messages":
132
+ case "mistral-conversations":
133
+ return { ...payload, ...supported };
134
+ case "google-generative-ai":
135
+ case "google-vertex":
136
+ return mergeNested(payload, "config", {
137
+ ...(Object.hasOwn(supported, "temperature") && { temperature: supported.temperature }),
138
+ ...(Object.hasOwn(supported, "top_p") && { topP: supported.top_p }),
139
+ ...(Object.hasOwn(supported, "top_k") && { topK: supported.top_k }),
140
+ ...(Object.hasOwn(supported, "frequency_penalty") && { frequencyPenalty: supported.frequency_penalty }),
141
+ ...(Object.hasOwn(supported, "presence_penalty") && { presencePenalty: supported.presence_penalty }),
142
+ ...(Object.hasOwn(supported, "seed") && { seed: supported.seed }),
143
+ });
144
+ case "bedrock-converse-stream":
145
+ return mergeNested(payload, "inferenceConfig", {
146
+ ...(Object.hasOwn(supported, "temperature") && { temperature: supported.temperature }),
147
+ ...(Object.hasOwn(supported, "top_p") && { topP: supported.top_p }),
148
+ });
149
+ case "pi-messages":
150
+ return mergeNested(payload, "options", {
151
+ ...(Object.hasOwn(supported, "temperature") && { temperature: supported.temperature }),
152
+ });
153
+ default:
154
+ return undefined;
155
+ }
156
+ }
157
+
158
+ export function samplingApiSupportsAnyParameter(model, options) {
159
+ return Object.values(resolveSamplingParameterCapabilities(model, options)).some((capability) => capability.supported);
160
+ }
@@ -206,6 +206,21 @@ async function withConfigLock(storageFile, operation) {
206
206
  }
207
207
  }
208
208
 
209
+ async function renameWithRetry(source, target) {
210
+ let lastError;
211
+ for (let attempt = 0; attempt < 12; attempt += 1) {
212
+ try {
213
+ await rename(source, target);
214
+ return;
215
+ } catch (error) {
216
+ lastError = error;
217
+ if (process.platform !== "win32" || !["EACCES", "EBUSY", "EPERM"].includes(error?.code)) throw error;
218
+ await delay(25 * (attempt + 1));
219
+ }
220
+ }
221
+ throw lastError;
222
+ }
223
+
209
224
  async function writePrivateAtomic(storageFile, value) {
210
225
  await mkdir(path.dirname(storageFile), { recursive: true, mode: 0o700 });
211
226
  const temporaryFile = path.join(path.dirname(storageFile), `.${path.basename(storageFile)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);
@@ -216,7 +231,7 @@ async function writePrivateAtomic(storageFile, value) {
216
231
  await handle.sync();
217
232
  await handle.close();
218
233
  handle = undefined;
219
- await rename(temporaryFile, storageFile);
234
+ await renameWithRetry(temporaryFile, storageFile);
220
235
  const persisted = await open(storageFile, "r+");
221
236
  await persisted.chmod(0o600);
222
237
  await persisted.close();
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { lstat, realpath } from "node:fs/promises";
3
+ import { homedir } from "node:os";
3
4
  import path from "node:path";
4
5
 
5
6
  export const SUBAGENT_LAUNCH_SLOTS_VERSION = 1;
@@ -252,7 +253,7 @@ export function validateSubagentLaunchSlotRoles(value, models = []) {
252
253
  return normalizeSubagentLaunchSlotRoles(value);
253
254
  }
254
255
 
255
- export async function resolveSubagentLaunchSlotProjectKey(cwd) {
256
+ export async function resolveSubagentLaunchSlotProjectKey(cwd, { globalPiRoot = path.join(homedir(), ".pi") } = {}) {
256
257
  const fallback = path.resolve(String(cwd || process.cwd()));
257
258
  let current;
258
259
  try {
@@ -261,11 +262,22 @@ export async function resolveSubagentLaunchSlotProjectKey(cwd) {
261
262
  return fallback;
262
263
  }
263
264
  const canonicalCwd = current;
265
+ const pathKey = (value) => process.platform === "win32" ? path.normalize(value).toLowerCase() : path.normalize(value);
266
+ const globalPiRoots = new Set();
267
+ for (const candidate of [path.join(homedir(), ".pi"), globalPiRoot]) {
268
+ try {
269
+ globalPiRoots.add(pathKey(await realpath(candidate)));
270
+ } catch {
271
+ globalPiRoots.add(pathKey(path.resolve(candidate)));
272
+ }
273
+ }
264
274
 
265
275
  while (true) {
266
276
  for (const marker of [".pi", ".git"]) {
277
+ const markerPath = path.join(current, marker);
278
+ if (marker === ".pi" && globalPiRoots.has(pathKey(markerPath))) continue;
267
279
  try {
268
- await lstat(path.join(current, marker));
280
+ await lstat(markerPath);
269
281
  return current;
270
282
  } catch (error) {
271
283
  if (error?.code !== "ENOENT") throw error;
@@ -21,6 +21,9 @@ export const LOCALHOST_ONLY_POST_ROUTES = new Map([
21
21
  ["/api/restart", "Restart is only allowed from localhost"],
22
22
  ["/api/update", "Updating Pi from the Web UI is only allowed from localhost"],
23
23
  ["/api/component-update", "Component updates are only allowed from localhost"],
24
+ ["/api/update/plan", "Creating update plans is only allowed from localhost"],
25
+ ["/api/update/apply", "Applying updates is only allowed from localhost"],
26
+ ["/api/update/rollback", "Rolling back updates is only allowed from localhost"],
24
27
  ["/api/shutdown", "Shutdown is only allowed from localhost"],
25
28
  ["/api/optional-feature-install", "Installing optional Web UI features is only allowed from localhost"],
26
29
  ["/api/skill-file", "Saving skill files is only allowed from localhost"],
@@ -0,0 +1,99 @@
1
+ import { spawn } from "node:child_process";
2
+ import { terminateProcessTree } from "../process-tree.mjs";
3
+ import { failedTargetReceipt, reduceUpdateReceipts } from "./verify.mjs";
4
+
5
+ function boundedAppend(current, chunk, maxLength) {
6
+ const next = current + String(chunk || "");
7
+ return next.length <= maxLength ? next : next.slice(next.length - maxLength);
8
+ }
9
+
10
+ /** Spawn with argument arrays, terminate the whole tree on timeout, and await closure. */
11
+ export function executeCommand(command, args = [], {
12
+ cwd,
13
+ env,
14
+ timeoutMs = 120_000,
15
+ closeTimeoutMs = 10_000,
16
+ maxOutputLength = 16_000,
17
+ spawnImpl = spawn,
18
+ terminateTree = terminateProcessTree,
19
+ platform = process.platform,
20
+ } = {}) {
21
+ if (!command || !Array.isArray(args)) throw new TypeError("command and argument array are required");
22
+ return new Promise((resolve) => {
23
+ const startedAt = Date.now();
24
+ let stdout = "";
25
+ let stderr = "";
26
+ let timedOut = false;
27
+ let settled = false;
28
+ let terminationError = "";
29
+ let closeTimer;
30
+ const child = spawnImpl(String(command), args.map(String), {
31
+ cwd,
32
+ env,
33
+ shell: false,
34
+ windowsHide: true,
35
+ detached: platform !== "win32",
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ });
38
+
39
+ child.stdout?.on("data", (chunk) => { stdout = boundedAppend(stdout, chunk, maxOutputLength); });
40
+ child.stderr?.on("data", (chunk) => { stderr = boundedAppend(stderr, chunk, maxOutputLength); });
41
+
42
+ const finish = (exitCode, signal, error = null, closureTimedOut = false) => {
43
+ if (settled) return;
44
+ settled = true;
45
+ clearTimeout(timeout);
46
+ clearTimeout(closeTimer);
47
+ resolve(Object.freeze({
48
+ command: String(command), args: Object.freeze(args.map(String)), exitCode,
49
+ signal: signal || null, timedOut, closureTimedOut,
50
+ stdout, stderr, error: error ? String(error.message || error) : terminationError,
51
+ durationMs: Date.now() - startedAt,
52
+ }));
53
+ };
54
+
55
+ child.once("error", (error) => finish(null, null, error));
56
+ child.once("close", (code, signal) => finish(code, signal));
57
+ const timeout = setTimeout(() => {
58
+ timedOut = true;
59
+ try {
60
+ if (!terminateTree(child, "SIGKILL")) terminationError = "Process-tree termination could not be confirmed.";
61
+ } catch (error) {
62
+ terminationError = String(error?.message || error);
63
+ }
64
+ closeTimer = setTimeout(() => {
65
+ try { child.kill?.("SIGKILL"); } catch {}
66
+ finish(null, "SIGKILL", null, true);
67
+ }, Math.max(100, closeTimeoutMs));
68
+ closeTimer.unref?.();
69
+ }, Math.max(1, timeoutMs));
70
+ timeout.unref?.();
71
+ });
72
+ }
73
+
74
+ /** Execute immutable plan targets in order through an injectable runner seam. */
75
+ export async function executePlanTargets(plan, {
76
+ runner = executeCommand,
77
+ verifyTarget,
78
+ beforeTarget,
79
+ stopOnFailure = false,
80
+ } = {}) {
81
+ if (typeof verifyTarget !== "function") throw new TypeError("verifyTarget is required");
82
+ const receipts = [];
83
+ for (const target of plan?.targets || []) {
84
+ try {
85
+ if (beforeTarget) await beforeTarget(target);
86
+ const commandResult = await runner(target.command.command, target.command.args, { target });
87
+ if (commandResult.exitCode !== 0 || commandResult.timedOut || commandResult.error) {
88
+ receipts.push(failedTargetReceipt(target, commandResult.timedOut ? "Update command timed out." : "Update command failed.", { command: commandResult }));
89
+ if (stopOnFailure) break;
90
+ continue;
91
+ }
92
+ receipts.push(await verifyTarget(target, commandResult));
93
+ } catch (error) {
94
+ receipts.push(failedTargetReceipt(target, String(error?.message || error)));
95
+ if (stopOnFailure) break;
96
+ }
97
+ }
98
+ return reduceUpdateReceipts(receipts);
99
+ }
@@ -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
+ }