@firstpick/pi-package-webui 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -56,6 +56,32 @@
56
56
  "currentBehavior": "Catalog-gated exact command routing and the Options menu open a browser-native reviewed policy editor backed by localhost-only revision-protected GET/POST routes; it never starts an agent turn.",
57
57
  "targetBehavior": "Keep browser and Pi TUI setup aligned with the canonical strict policy validator, deny defaults, explicit normalized review, and stale-write protection."
58
58
  },
59
+ {
60
+ "id": "/summary",
61
+ "kind": "slash-command",
62
+ "category": "native-command",
63
+ "title": "Session summary viewer and refresh",
64
+ "command": { "name": "summary", "description": "Open the latest Markdown session summary or generate one" },
65
+ "webStatus": "implemented",
66
+ "priority": "P1",
67
+ "sensitive": true,
68
+ "guards": ["confirmation"],
69
+ "currentBehavior": "Catalog-gated header and composer actions open a non-blocking sanitized Markdown overlay; an unconfigured first click opens setup, and configured refreshes use the active tab only while preserving the latest successful result on failure.",
70
+ "targetBehavior": "Keep browser and TUI summary display branch-aware, bounded, tab-scoped, and explicit about configured provider usage."
71
+ },
72
+ {
73
+ "id": "/summary-setup",
74
+ "kind": "slash-command",
75
+ "category": "native-command",
76
+ "title": "Session summary setup",
77
+ "command": { "name": "summary-setup", "description": "Configure persistent session titles and Markdown summaries" },
78
+ "webStatus": "implemented",
79
+ "priority": "P1",
80
+ "sensitive": true,
81
+ "guards": ["confirmation"],
82
+ "currentBehavior": "Catalog-gated exact routing and Common Pi options open a browser-native model, reasoning, prompts, cadence, automatic-generation, privacy-scope, and context-injection editor; a disclosure confirmation is required before private global persistence and immediate first generation.",
83
+ "targetBehavior": "Keep browser and Pi TUI setup aligned with the canonical session-summary preference schema, fixed privacy scope, and explicit privacy/cost confirmation."
84
+ },
59
85
  {
60
86
  "id": "/model",
61
87
  "kind": "slash-command",
@@ -0,0 +1,29 @@
1
+ const entries = [
2
+ ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete", "^0.2.2"],
3
+ ["fishUserBash", "@firstpick/pi-extension-fish-user-bash", "^0.2.2"],
4
+ ["btwCommand", "@firstpick/pi-extension-btw", "^0.1.4"],
5
+ ["gitWorkflow", "@firstpick/pi-prompts-git-pr", "^0.1.5"],
6
+ ["releaseNpm", "@firstpick/pi-extension-release-npm", "^0.4.4"],
7
+ ["releaseAur", "@firstpick/pi-extension-release-aur", "^0.1.8"],
8
+ ["aurReview", "@firstpick/pi-extension-aur-review", "^0.1.1"],
9
+ ["workflows", "@firstpick/pi-extension-workflows", "^0.1.7"],
10
+ ["safetyGuard", "@firstpick/pi-extension-safety-guard", "^0.2.6"],
11
+ ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills", "^0.1.9"],
12
+ ["todoProgressWidget", "@firstpick/pi-extension-todo-progress", "^0.2.9"],
13
+ ["tuiToolsCommand", "@firstpick/pi-extension-tools", "^0.1.7"],
14
+ ["remoteWebui", "@firstpick/pi-package-remote-webui", "^0.1.8"],
15
+ ["questionnaire", "@firstpick/pi-package-questionnaire", "^0.1.0"],
16
+ ["naturalConversation", "@firstpick/pi-package-natural-conversation", "^0.1.4"],
17
+ ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status", "^0.4.3"],
18
+ ["statsCommand", "@firstpick/pi-extension-stats", "^0.2.9"],
19
+ ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode", "^0.1.0"],
20
+ ["themeBundle", "@firstpick/pi-themes-bundle", "^0.1.5"],
21
+ ];
22
+
23
+ export const OPTIONAL_FEATURE_CATALOG = Object.freeze(entries.map(([featureId, packageName, expectedSpec]) => Object.freeze({
24
+ featureId,
25
+ packageName,
26
+ expectedSpec,
27
+ })));
28
+
29
+ export const OPTIONAL_FEATURE_BY_ID = new Map(OPTIONAL_FEATURE_CATALOG.map((feature) => [feature.featureId, feature]));
@@ -0,0 +1,410 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export const OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION = 1;
6
+ export const OPTIONAL_FEATURE_AUDIT_DEADLINE_MS = 10_000;
7
+ export const OPTIONAL_FEATURE_AUDIT_PHASES = Object.freeze([
8
+ "checking", "ready", "action-required", "migrating", "partial", "complete", "degraded",
9
+ ]);
10
+ export const OPTIONAL_FEATURE_AUDIT_STATES = Object.freeze([
11
+ "registered", "local-resource", "legacy-migratable", "missing", "update-available", "conflict", "disabled", "unknown",
12
+ ]);
13
+
14
+ function plainObject(value) {
15
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
16
+ }
17
+
18
+ function normalizedFeatureInventory(value) {
19
+ const features = {};
20
+ for (const [featureId, raw] of Object.entries(plainObject(value))) {
21
+ if (!featureId || featureId.length > 160) continue;
22
+ const feature = plainObject(raw);
23
+ features[featureId] = {
24
+ available: feature.available === true,
25
+ enabled: feature.enabled === true,
26
+ sourceKind: String(feature.sourceKind || "unknown").slice(0, 80),
27
+ installedVersion: String(feature.installedVersion || "").slice(0, 120),
28
+ };
29
+ }
30
+ return features;
31
+ }
32
+
33
+ function normalizedRecord(value) {
34
+ const record = plainObject(value);
35
+ const last = plainObject(record.lastSuccessfulAudit);
36
+ const pending = plainObject(record.pendingUpgrade);
37
+ const dismissed = plainObject(record.dismissedMigration);
38
+ return {
39
+ schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION,
40
+ ...(last.completedAt ? {
41
+ lastSuccessfulAudit: {
42
+ webuiVersion: String(last.webuiVersion || "").slice(0, 120),
43
+ completedAt: String(last.completedAt || "").slice(0, 80),
44
+ features: normalizedFeatureInventory(last.features),
45
+ },
46
+ } : {}),
47
+ ...(pending.startedAt ? {
48
+ pendingUpgrade: {
49
+ fromVersion: String(pending.fromVersion || "").slice(0, 120),
50
+ startedAt: String(pending.startedAt || "").slice(0, 80),
51
+ featureIds: [...new Set((Array.isArray(pending.featureIds) ? pending.featureIds : []).filter((id) => typeof id === "string").slice(0, 256))],
52
+ },
53
+ } : {}),
54
+ ...(dismissed.dismissedAt ? {
55
+ dismissedMigration: {
56
+ revision: String(dismissed.revision || "").slice(0, 160),
57
+ dismissedAt: String(dismissed.dismissedAt || "").slice(0, 80),
58
+ featureIds: [...new Set((Array.isArray(dismissed.featureIds) ? dismissed.featureIds : []).filter((id) => typeof id === "string").slice(0, 256))],
59
+ },
60
+ } : {}),
61
+ };
62
+ }
63
+
64
+ export class OptionalFeatureMigrationStore {
65
+ constructor({ filePath }) {
66
+ if (!filePath) throw new Error("OptionalFeatureMigrationStore requires filePath");
67
+ this.filePath = path.resolve(filePath);
68
+ this.writeQueue = Promise.resolve();
69
+ }
70
+
71
+ async read() {
72
+ try {
73
+ return normalizedRecord(JSON.parse(await readFile(this.filePath, "utf8")));
74
+ } catch (error) {
75
+ if (error?.code === "ENOENT") return { schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION };
76
+ throw new Error(`Optional feature migration state is unreadable: ${error?.code || error?.name || "invalid-json"}`);
77
+ }
78
+ }
79
+
80
+ #enqueueWrite(operation) {
81
+ const task = this.writeQueue.then(operation, operation);
82
+ this.writeQueue = task.catch(() => {});
83
+ return task;
84
+ }
85
+
86
+ async #write(record) {
87
+ const normalized = normalizedRecord(record);
88
+ const parent = path.dirname(this.filePath);
89
+ await mkdir(parent, { recursive: true, mode: 0o700 });
90
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
91
+ try {
92
+ await writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
93
+ await rename(temporary, this.filePath);
94
+ await chmod(this.filePath, 0o600).catch(() => {});
95
+ } finally {
96
+ await rm(temporary, { force: true }).catch(() => {});
97
+ }
98
+ return normalized;
99
+ }
100
+
101
+ write(record) {
102
+ return this.#enqueueWrite(() => this.#write(record));
103
+ }
104
+
105
+ update(mutator) {
106
+ return this.#enqueueWrite(async () => this.#write(await mutator(await this.read())));
107
+ }
108
+
109
+ dismiss({ revision, featureIds, now = new Date() }) {
110
+ return this.update((record) => ({
111
+ ...record,
112
+ dismissedMigration: {
113
+ revision,
114
+ dismissedAt: now.toISOString(),
115
+ featureIds,
116
+ },
117
+ }));
118
+ }
119
+
120
+ markPendingUpgrade({ fromVersion, featureIds, now = new Date() }) {
121
+ return this.update((record) => ({
122
+ ...record,
123
+ pendingUpgrade: {
124
+ fromVersion,
125
+ startedAt: now.toISOString(),
126
+ featureIds,
127
+ },
128
+ }));
129
+ }
130
+
131
+ completeMigration() {
132
+ return this.update((record) => {
133
+ delete record.pendingUpgrade;
134
+ delete record.dismissedMigration;
135
+ return record;
136
+ });
137
+ }
138
+ }
139
+
140
+ function featureSourceKind(state) {
141
+ if (state === "registered" || state === "update-available") return "pi-package";
142
+ if (state === "local-resource") return "top-level-resource";
143
+ if (state === "legacy-migratable") return "legacy-webui-bundled";
144
+ return "none";
145
+ }
146
+
147
+ export function classifyOptionalFeature(status, previousFeature) {
148
+ const previous = plainObject(previousFeature);
149
+ const previouslyAvailable = previous.available === true;
150
+ const previouslyEnabled = previous.enabled === true;
151
+ let state;
152
+ if (status?.resourceConflict) state = "conflict";
153
+ else if (status?.disabled === true || (previouslyAvailable && previous.enabled === false && !status?.configured && !status?.locallyConfigured)) state = "disabled";
154
+ else if (status?.updateAvailable && (status?.configured || status?.locallyConfigured)) state = "update-available";
155
+ else if (status?.configured && status?.installed) state = "registered";
156
+ else if (status?.locallyConfigured) state = "local-resource";
157
+ else if (status?.legacyEvidence === true || previouslyAvailable) state = "legacy-migratable";
158
+ else if (status?.auditUnknown === true || (status?.installed && !status?.configured && !status?.locallyConfigured)) state = "unknown";
159
+ else state = "missing";
160
+ return {
161
+ ...status,
162
+ state,
163
+ sourceKind: featureSourceKind(state),
164
+ previouslyAvailable,
165
+ previouslyEnabled,
166
+ selectedByDefault: state === "legacy-migratable" && previouslyEnabled,
167
+ };
168
+ }
169
+
170
+ function installKindFor(record, statuses, webuiVersion) {
171
+ if (record.pendingUpgrade?.startedAt) return "upgrade";
172
+ if (record.lastSuccessfulAudit?.completedAt && record.lastSuccessfulAudit.webuiVersion !== webuiVersion) return "upgrade";
173
+ if (statuses.some((status) => status.legacyEvidence === true)) return "upgrade";
174
+ if (statuses.some((status) => status.auditUnknown === true)) return "unknown";
175
+ return "fresh";
176
+ }
177
+
178
+ function snapshotSummary(features) {
179
+ return {
180
+ ready: features.filter(({ state }) => ["registered", "local-resource", "update-available"].includes(state)).length,
181
+ migratable: features.filter(({ state }) => state === "legacy-migratable").length,
182
+ missing: features.filter(({ state }) => state === "missing").length,
183
+ conflicts: features.filter(({ state }) => state === "conflict").length,
184
+ disabled: features.filter(({ state }) => state === "disabled").length,
185
+ unknown: features.filter(({ state }) => state === "unknown").length,
186
+ };
187
+ }
188
+
189
+ function stableRevision(payload) {
190
+ return `sha256:${createHash("sha256").update(JSON.stringify(payload)).digest("hex")}`;
191
+ }
192
+
193
+ function sanitizedDiagnostic(error) {
194
+ const code = String(error?.code || error?.name || "audit-failed").replace(/[^a-zA-Z0-9_.-]/g, "").slice(0, 80);
195
+ return { kind: code || "audit-failed", message: "Optional feature audit could not establish a safe resource configuration. Recheck from localhost." };
196
+ }
197
+
198
+ function withDeadline(promise, deadlineAt) {
199
+ const remainingMs = Math.max(0, deadlineAt - Date.now());
200
+ return new Promise((resolve, reject) => {
201
+ const timer = setTimeout(() => {
202
+ const error = new Error("Optional feature audit exceeded its startup deadline");
203
+ error.code = "audit-timeout";
204
+ reject(error);
205
+ }, remainingMs);
206
+ timer.unref?.();
207
+ Promise.resolve(promise).then(
208
+ (value) => {
209
+ clearTimeout(timer);
210
+ resolve(value);
211
+ },
212
+ (error) => {
213
+ clearTimeout(timer);
214
+ reject(error);
215
+ },
216
+ );
217
+ });
218
+ }
219
+
220
+ function browserFeature(feature) {
221
+ const {
222
+ installedRoot: _installedRoot,
223
+ topLevelResources: _topLevelResources,
224
+ configuredPackages: _configuredPackages,
225
+ legacyPath: _legacyPath,
226
+ ...safe
227
+ } = feature;
228
+ return safe;
229
+ }
230
+
231
+ function deepFreeze(value) {
232
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
233
+ Object.freeze(value);
234
+ for (const child of Object.values(value)) deepFreeze(child);
235
+ return value;
236
+ }
237
+
238
+ function migrationDismissalApplies(features, record) {
239
+ const actionableIds = features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId).sort();
240
+ const dismissedIds = [...new Set(record.dismissedMigration?.featureIds || [])].sort();
241
+ return actionableIds.length > 0
242
+ && actionableIds.length === dismissedIds.length
243
+ && actionableIds.every((featureId, index) => featureId === dismissedIds[index]);
244
+ }
245
+
246
+ function phaseFor(features, record) {
247
+ const actionable = features.filter(({ state }) => state === "legacy-migratable");
248
+ const dismissalApplies = migrationDismissalApplies(features, record);
249
+ if (features.some(({ state }) => state === "conflict") || (actionable.length && !dismissalApplies)) return "action-required";
250
+ return "ready";
251
+ }
252
+
253
+ function auditInventory(features, webuiVersion, completedAt) {
254
+ const inventory = {};
255
+ for (const feature of features) {
256
+ inventory[feature.featureId] = {
257
+ available: ["registered", "local-resource", "legacy-migratable", "update-available", "disabled"].includes(feature.state),
258
+ enabled: !["missing", "disabled", "unknown"].includes(feature.state),
259
+ sourceKind: feature.sourceKind,
260
+ installedVersion: feature.installedVersion || "",
261
+ };
262
+ }
263
+ return { webuiVersion, completedAt, features: inventory };
264
+ }
265
+
266
+ export class OptionalFeatureAuditCoordinator {
267
+ constructor({ catalog, collectStatuses, store, webuiVersion, deadlineMs = OPTIONAL_FEATURE_AUDIT_DEADLINE_MS, onEvent = () => {}, now = () => new Date() }) {
268
+ this.catalog = catalog;
269
+ this.collectStatuses = collectStatuses;
270
+ this.store = store;
271
+ this.webuiVersion = webuiVersion;
272
+ this.deadlineMs = deadlineMs;
273
+ this.onEvent = onEvent;
274
+ this.now = now;
275
+ this.inFlight = null;
276
+ this.mutation = null;
277
+ this.snapshot = deepFreeze({
278
+ phase: "checking",
279
+ revision: "pending",
280
+ installKind: "unknown",
281
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: 0 },
282
+ features: [],
283
+ progress: null,
284
+ completedAt: null,
285
+ diagnostic: null,
286
+ });
287
+ }
288
+
289
+ current() {
290
+ return this.snapshot;
291
+ }
292
+
293
+ publish(next, event = "snapshot") {
294
+ this.snapshot = deepFreeze(next);
295
+ this.onEvent({ type: "webui_optional_feature_migration", event, snapshot: this.snapshot });
296
+ return this.snapshot;
297
+ }
298
+
299
+ recheck({ reason = "manual" } = {}) {
300
+ if (this.inFlight) return this.inFlight;
301
+ this.publish({ ...this.snapshot, phase: "checking", progress: null, diagnostic: null }, "checking");
302
+ const task = this.#runAudit(reason).finally(() => {
303
+ if (this.inFlight === task) this.inFlight = null;
304
+ });
305
+ this.inFlight = task;
306
+ return task;
307
+ }
308
+
309
+ async #runAudit(reason) {
310
+ const deadlineAt = Date.now() + this.deadlineMs;
311
+ try {
312
+ const statuses = await withDeadline(Promise.resolve().then(() => this.collectStatuses()), deadlineAt);
313
+ const record = await withDeadline(this.store.read(), deadlineAt);
314
+ const previous = record.lastSuccessfulAudit?.features || {};
315
+ const features = statuses.map((status) => classifyOptionalFeature(status, previous[status.featureId]));
316
+ const installKind = installKindFor(record, statuses, this.webuiVersion);
317
+ const revisionPayload = {
318
+ schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION,
319
+ installKind,
320
+ features: features.map(({ featureId, state, installedVersion, previouslyAvailable, previouslyEnabled, selectedByDefault }) => ({
321
+ featureId, state, installedVersion: installedVersion || "", previouslyAvailable, previouslyEnabled, selectedByDefault,
322
+ })),
323
+ };
324
+ const revision = stableRevision(revisionPayload);
325
+ const completedAt = this.now().toISOString();
326
+ const dismissed = migrationDismissalApplies(features, record);
327
+ const selectedFeatures = features.map((feature) => ({ ...feature, selectedByDefault: dismissed ? false : feature.selectedByDefault }));
328
+ const nextRecord = await withDeadline(
329
+ this.store.update((latest) => ({ ...latest, lastSuccessfulAudit: auditInventory(selectedFeatures, this.webuiVersion, completedAt) })),
330
+ deadlineAt,
331
+ );
332
+ return this.publish({
333
+ phase: phaseFor(selectedFeatures, nextRecord),
334
+ revision,
335
+ installKind,
336
+ summary: snapshotSummary(selectedFeatures),
337
+ features: selectedFeatures.map(browserFeature),
338
+ progress: null,
339
+ completedAt,
340
+ diagnostic: null,
341
+ reason,
342
+ }, "audit-complete");
343
+ } catch (error) {
344
+ const revision = stableRevision({ degraded: true, kind: error?.code || error?.name || "audit-failed", nonce: randomUUID() });
345
+ return this.publish({
346
+ phase: "degraded",
347
+ revision,
348
+ installKind: "unknown",
349
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: this.catalog.length },
350
+ features: this.catalog.map(({ featureId, packageName, expectedSpec }) => ({
351
+ featureId, packageName, expectedSpec, state: "unknown", sourceKind: "none", previouslyAvailable: false, previouslyEnabled: false, selectedByDefault: false,
352
+ })),
353
+ progress: null,
354
+ completedAt: this.now().toISOString(),
355
+ diagnostic: sanitizedDiagnostic(error),
356
+ reason,
357
+ }, "degraded");
358
+ }
359
+ }
360
+
361
+ assertRevision(revision) {
362
+ if (["checking", "degraded"].includes(this.snapshot.phase) || typeof revision !== "string" || revision !== this.snapshot.revision) {
363
+ const error = new Error("Optional feature audit revision is stale or not actionable; refetch /api/optional-features and retry");
364
+ error.statusCode = 409;
365
+ throw error;
366
+ }
367
+ }
368
+
369
+ assertIdle() {
370
+ if (this.mutation) {
371
+ const error = new Error("An optional feature mutation is already in progress");
372
+ error.statusCode = 409;
373
+ throw error;
374
+ }
375
+ }
376
+
377
+ async dismiss(revision) {
378
+ this.assertIdle();
379
+ this.assertRevision(revision);
380
+ const featureIds = this.snapshot.features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId);
381
+ await this.store.dismiss({ revision, featureIds, now: this.now() });
382
+ return this.publish({
383
+ ...this.snapshot,
384
+ phase: this.snapshot.summary.conflicts > 0 ? "action-required" : "ready",
385
+ features: this.snapshot.features.map((feature) => ({ ...feature, selectedByDefault: false })),
386
+ }, "dismissed");
387
+ }
388
+
389
+ async runMutation(revision, operation) {
390
+ this.assertRevision(revision);
391
+ this.assertIdle();
392
+ const task = Promise.resolve().then(operation).finally(() => {
393
+ if (this.mutation === task) this.mutation = null;
394
+ });
395
+ this.mutation = task;
396
+ return task;
397
+ }
398
+
399
+ setProgress(progress) {
400
+ const phase = progress?.phase || "migrating";
401
+ return this.publish({ ...this.snapshot, phase, progress: progress ? { ...progress } : null }, "progress");
402
+ }
403
+
404
+ excludedPackageNames() {
405
+ if (this.snapshot.phase === "checking" || this.snapshot.phase === "degraded") {
406
+ return new Set(this.catalog.map(({ packageName }) => packageName));
407
+ }
408
+ return new Set(this.snapshot.features.filter(({ state }) => state === "conflict").map(({ packageName }) => packageName));
409
+ }
410
+ }