@firstpick/pi-package-webui 0.6.6 → 0.6.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.
@@ -17,6 +17,19 @@
17
17
  "currentBehavior": "Browser dialog exposes native TUI settings in concise sections with runtime/browser/reload/TUI badges; reload-needed settings can restart the active tab after saving.",
18
18
  "targetBehavior": "Keep native TUI setting coverage current; project/global source editing can be added as an advanced enhancement."
19
19
  },
20
+ {
21
+ "id": "/safety-guard-setup",
22
+ "kind": "slash-command",
23
+ "category": "native-command",
24
+ "title": "Safety guard setup",
25
+ "command": { "name": "safety-guard-setup", "description": "Configure command categories, protected-path checks, and preview context" },
26
+ "webStatus": "implemented",
27
+ "priority": "P1",
28
+ "sensitive": false,
29
+ "guards": ["confirmation"],
30
+ "currentBehavior": "Browser-native dialog and Pi TUI settings list edit the same persisted global guard schema, including independent context lines before and after matches.",
31
+ "targetBehavior": "Keep browser and TUI setup controls aligned with the canonical safety-guard config module and fail-safe defaults."
32
+ },
20
33
  {
21
34
  "id": "/git-workflow-setup",
22
35
  "kind": "slash-command",
@@ -1,55 +1,36 @@
1
- import { AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
1
+ import { ModelRuntime } from "@earendil-works/pi-coding-agent";
2
2
 
3
- export function createAuthContext() {
4
- const authStorage = AuthStorage.create();
5
- const modelRegistry = ModelRegistry.create(authStorage);
6
- return { authStorage, modelRegistry };
3
+ export async function createAuthContext() {
4
+ const modelRuntime = await ModelRuntime.create({ allowModelNetwork: false });
5
+ return { modelRuntime };
7
6
  }
8
7
 
9
- export function listLoginProviderOptions(modelRegistry) {
10
- const authStorage = modelRegistry.authStorage;
11
- const byId = new Map();
12
- for (const provider of authStorage.getOAuthProviders()) {
13
- byId.set(provider.id, {
14
- id: provider.id,
15
- name: provider.name,
16
- authType: "oauth",
17
- removable: authStorage.has(provider.id),
18
- status: modelRegistry.getProviderAuthStatus(provider.id),
19
- });
20
- }
21
- for (const model of modelRegistry.getAll()) {
22
- if (byId.has(model.provider)) continue;
23
- byId.set(model.provider, {
24
- id: model.provider,
25
- name: modelRegistry.getProviderDisplayName(model.provider),
26
- authType: "api_key",
27
- removable: authStorage.has(model.provider),
28
- status: modelRegistry.getProviderAuthStatus(model.provider),
29
- });
30
- }
31
- return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
8
+ export async function listLoginProviderOptions(modelRuntime) {
9
+ const storedProviderIds = new Set((await modelRuntime.listCredentials()).map((credential) => credential.providerId));
10
+ return modelRuntime.getProviders().map((provider) => ({
11
+ id: provider.id,
12
+ name: provider.name || provider.id,
13
+ authType: provider.auth?.oauth ? "oauth" : "api_key",
14
+ removable: storedProviderIds.has(provider.id),
15
+ status: modelRuntime.getProviderAuthStatus(provider.id),
16
+ })).sort((left, right) => left.name.localeCompare(right.name));
32
17
  }
33
18
 
34
- export function listLogoutProviderOptions(modelRegistry) {
35
- const authStorage = modelRegistry.authStorage;
36
- const options = [];
37
- for (const providerId of authStorage.list()) {
38
- const credential = authStorage.get(providerId);
39
- if (!credential) continue;
40
- options.push({
41
- id: providerId,
42
- name: modelRegistry.getProviderDisplayName(providerId),
43
- authType: credential.type,
44
- status: modelRegistry.getProviderAuthStatus(providerId),
45
- });
46
- }
19
+ export async function listLogoutProviderOptions(modelRuntime) {
20
+ const options = (await modelRuntime.listCredentials()).map((credential) => ({
21
+ id: credential.providerId,
22
+ name: modelRuntime.getProvider(credential.providerId)?.name || credential.providerId,
23
+ authType: credential.type,
24
+ status: modelRuntime.getProviderAuthStatus(credential.providerId),
25
+ }));
47
26
  return options.sort((left, right) => left.name.localeCompare(right.name));
48
27
  }
49
28
 
50
- export function authProvidersPayload(modelRegistry) {
51
- const loginProviders = listLoginProviderOptions(modelRegistry);
52
- const logoutProviders = listLogoutProviderOptions(modelRegistry);
29
+ export async function authProvidersPayload(modelRuntime) {
30
+ const [loginProviders, logoutProviders] = await Promise.all([
31
+ listLoginProviderOptions(modelRuntime),
32
+ listLogoutProviderOptions(modelRuntime),
33
+ ]);
53
34
  return {
54
35
  loginProviders,
55
36
  logoutProviders,
@@ -63,17 +44,15 @@ export function authProvidersPayload(modelRegistry) {
63
44
  };
64
45
  }
65
46
 
66
- export function logoutStoredProvider(modelRegistry, providerId) {
47
+ export async function logoutStoredProvider(modelRuntime, providerId) {
67
48
  const id = String(providerId || "").trim();
68
49
  if (!id) throw new Error("provider is required");
69
- const authStorage = modelRegistry.authStorage;
70
- if (!authStorage.has(id)) {
50
+ const credential = (await modelRuntime.listCredentials()).find((item) => item.providerId === id);
51
+ if (!credential) {
71
52
  throw new Error(`No stored credentials found for provider: ${id}`);
72
53
  }
73
- const credential = authStorage.get(id);
74
- authStorage.logout(id);
75
- modelRegistry.refresh();
76
- const name = modelRegistry.getProviderDisplayName(id);
54
+ const name = modelRuntime.getProvider(id)?.name || id;
55
+ await modelRuntime.logout(id);
77
56
  const message = credential?.type === "oauth"
78
57
  ? `Logged out of ${name}.`
79
58
  : `Removed stored API key for ${name}. Environment variables and models.json config are unchanged.`;
@@ -0,0 +1,61 @@
1
+ export const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
2
+
3
+ function privateCredentialStore(modelRuntime) {
4
+ // Compatibility adapter: ModelRuntime intentionally does not expose a
5
+ // force-refresh API. Its RuntimeCredentials store still provides the
6
+ // lock-safe modify() primitive used by normal OAuth resolution.
7
+ const credentials = modelRuntime?.credentials;
8
+ if (!credentials || typeof credentials.read !== "function" || typeof credentials.modify !== "function") {
9
+ throw new Error("Codex OAuth force refresh is unavailable in this Pi version.");
10
+ }
11
+ return credentials;
12
+ }
13
+
14
+ export async function resolveCodexUsageAuth(modelRuntime, providerId, options = {}) {
15
+ const now = options.now ?? Date.now();
16
+ const forceRefresh = options.forceRefresh === true;
17
+ const credentials = privateCredentialStore(modelRuntime);
18
+ const provider = modelRuntime.getProvider(providerId);
19
+ let stored = await credentials.read(providerId);
20
+ let refreshed = false;
21
+
22
+ if (stored?.type === "oauth") {
23
+ const oauth = provider?.auth?.oauth;
24
+ if (!oauth || typeof oauth.refresh !== "function") throw new Error("Codex OAuth refresh is unavailable.");
25
+ const rejectedAccess = forceRefresh ? stored.access : undefined;
26
+ const expires = Number(stored.expires);
27
+ const shouldRefresh = forceRefresh || !Number.isFinite(expires) || now + CODEX_TOKEN_REFRESH_SKEW_MS >= expires;
28
+
29
+ if (shouldRefresh) {
30
+ await credentials.modify(providerId, async (current) => {
31
+ if (current?.type !== "oauth") return undefined;
32
+ // Another process may have refreshed while this caller waited for the
33
+ // auth-file lock. Reuse that newer token rather than refreshing twice.
34
+ if (forceRefresh && current.access !== rejectedAccess) return undefined;
35
+ const currentExpires = Number(current.expires);
36
+ if (!forceRefresh && Number.isFinite(currentExpires) && now + CODEX_TOKEN_REFRESH_SKEW_MS < currentExpires) return undefined;
37
+ const next = await oauth.refresh(current, options.signal);
38
+ if (!next || next.type !== "oauth") throw new Error("Codex OAuth refresh returned no credential.");
39
+ refreshed = true;
40
+ return next;
41
+ });
42
+ stored = await credentials.read(providerId);
43
+ }
44
+
45
+ if (forceRefresh && stored?.type === "oauth" && stored.access === rejectedAccess) {
46
+ throw new Error("Codex OAuth refresh returned the rejected credential.");
47
+ }
48
+ return {
49
+ accessToken: stored?.type === "oauth" ? stored.access : undefined,
50
+ credential: stored,
51
+ refreshed: refreshed || (forceRefresh && stored?.type === "oauth" && stored.access !== rejectedAccess),
52
+ };
53
+ }
54
+
55
+ const resolved = await modelRuntime.getAuth(providerId);
56
+ return {
57
+ accessToken: resolved?.auth?.apiKey,
58
+ credential: stored,
59
+ refreshed: false,
60
+ };
61
+ }
@@ -0,0 +1,68 @@
1
+ const WINDOWS_RESERVED_DEVICE_NAMES = new Set([
2
+ "CON",
3
+ "PRN",
4
+ "AUX",
5
+ "NUL",
6
+ ...Array.from({ length: 9 }, (_, index) => `COM${index + 1}`),
7
+ ...Array.from({ length: 9 }, (_, index) => `LPT${index + 1}`),
8
+ ]);
9
+
10
+ function gitFailureText(result) {
11
+ return [result?.stderr, result?.stdout, result?.error].filter(Boolean).join("\n");
12
+ }
13
+
14
+ function extractGitIndexFailurePath(text) {
15
+ const patterns = [
16
+ /unable to index file ['"]([^'"\r\n]+)['"]/i,
17
+ /error:\s*([^:\r\n]+): failed to insert into database/i,
18
+ /short read while indexing\s+['"]?([^'"\r\n]+?)['"]?\s*$/im,
19
+ /invalid path ['"]([^'"\r\n]+)['"]/i,
20
+ ];
21
+ for (const pattern of patterns) {
22
+ const match = String(text || "").match(pattern);
23
+ if (match?.[1]?.trim()) return match[1].trim();
24
+ }
25
+ return "";
26
+ }
27
+
28
+ export function classifyWindowsReservedGitPath(value) {
29
+ const pathname = String(value || "").trim();
30
+ if (!pathname) return null;
31
+ for (const rawComponent of pathname.replace(/\\/g, "/").split("/")) {
32
+ const component = rawComponent.replace(/[ .]+$/g, "");
33
+ const deviceName = component.split(".", 1)[0].toUpperCase();
34
+ if (WINDOWS_RESERVED_DEVICE_NAMES.has(deviceName)) {
35
+ return { path: pathname, component, deviceName };
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+
41
+ export function findWindowsReservedGitPath(paths) {
42
+ const values = typeof paths === "string" ? paths.split("\0") : paths;
43
+ for (const pathname of values || []) {
44
+ const match = classifyWindowsReservedGitPath(pathname);
45
+ if (match) return match;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ export function windowsReservedGitPathFailure(value) {
51
+ const match = value && typeof value === "object" && value.path
52
+ ? value
53
+ : classifyWindowsReservedGitPath(value);
54
+ if (!match) return null;
55
+ const shownPath = JSON.stringify(String(match.path));
56
+ return {
57
+ code: "INVALID_WORKTREE_PATH",
58
+ error: `Git cannot index the Windows-reserved path ${shownPath}.`,
59
+ hint: `Delete or rename ${shownPath} in the working tree, then retry. If Windows treats it as a device, use an extended-length (\\\\?\\...) path or a POSIX-compatible tool. Review the staged set before continuing because an earlier failed git add may already have staged files.`,
60
+ };
61
+ }
62
+
63
+ export function classifyGitPathFailure(result) {
64
+ const text = gitFailureText(result);
65
+ if (!/(?:short read while indexing|failed to insert into database|unable to index file|invalid path)/i.test(text)) return null;
66
+ const pathname = extractGitIndexFailurePath(text);
67
+ return pathname ? windowsReservedGitPathFailure(pathname) : null;
68
+ }
@@ -22,7 +22,7 @@ export function supportedGitWorkflowThinkingLevels(model) {
22
22
  });
23
23
  }
24
24
 
25
- const WEBUI_SETTINGS_VERSION = 2;
25
+ const WEBUI_SETTINGS_VERSION = 3;
26
26
  const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
27
27
 
28
28
  function cleanBoundedString(value, maxLength = 512) {
@@ -111,11 +111,36 @@ export function webuiSettingsFile(env = process.env) {
111
111
  return path.join(configRoot, "pi-webui", "settings.json");
112
112
  }
113
113
 
114
+ function normalizeNameList(value) {
115
+ if (!Array.isArray(value)) return null;
116
+ const names = [];
117
+ const seen = new Set();
118
+ for (const item of value) {
119
+ const name = cleanBoundedString(item, 256);
120
+ if (!name || seen.has(name)) continue;
121
+ seen.add(name);
122
+ names.push(name);
123
+ }
124
+ return names;
125
+ }
126
+
127
+ export function normalizeResourceDefaults(value) {
128
+ return {
129
+ tools: {
130
+ enabledTools: normalizeNameList(value?.tools?.enabledTools),
131
+ },
132
+ skills: {
133
+ enabledSkills: normalizeNameList(value?.skills?.enabledSkills),
134
+ },
135
+ };
136
+ }
137
+
114
138
  export function normalizeWebuiSettings(value) {
115
139
  return {
116
140
  version: WEBUI_SETTINGS_VERSION,
117
141
  remoteAuthEnabled: value?.remoteAuthEnabled === true,
118
142
  gitWorkflow: normalizeGitWorkflowPreferences(value?.gitWorkflow),
143
+ resourceDefaults: normalizeResourceDefaults(value?.resourceDefaults),
119
144
  };
120
145
  }
121
146
 
@@ -136,6 +161,14 @@ export async function writeWebuiSettings(patch, storageFile = webuiSettingsFile(
136
161
  gitWorkflow: patch?.gitWorkflow
137
162
  ? mergeGitWorkflowPreferences(current.gitWorkflow, patch.gitWorkflow)
138
163
  : current.gitWorkflow,
164
+ resourceDefaults: patch?.resourceDefaults
165
+ ? {
166
+ ...current.resourceDefaults,
167
+ ...patch.resourceDefaults,
168
+ tools: { ...current.resourceDefaults.tools, ...(patch.resourceDefaults.tools || {}) },
169
+ skills: { ...current.resourceDefaults.skills, ...(patch.resourceDefaults.skills || {}) },
170
+ }
171
+ : current.resourceDefaults,
139
172
  });
140
173
  await mkdir(path.dirname(storageFile), { recursive: true });
141
174
  const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
@@ -0,0 +1,13 @@
1
+ export function nativeExportDownloadPayload({ localRequest, exportedPath, download, responseData }) {
2
+ const downloadLines = `Download: ${download.fileName}\nOpen it in your browser when prompted.\nOpen URL: ${download.openUrl || download.url}\nDownload URL: ${download.url}\nLink expires: ${download.expiresAt}`;
3
+ return {
4
+ status: "succeeded",
5
+ level: "info",
6
+ message: localRequest
7
+ ? `Exported current session to HTML.\nSaved to: ${exportedPath}\n${downloadLines}`
8
+ : `Exported current session to HTML.\n${downloadLines}`,
9
+ ...(localRequest ? { serverPath: exportedPath, result: responseData } : {}),
10
+ download,
11
+ refresh: ["state"],
12
+ };
13
+ }
@@ -0,0 +1,105 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ function pathApiForPlatform(platform) {
5
+ return platform === "win32" ? path.win32 : path.posix;
6
+ }
7
+
8
+ function npmCliPathForDirectory(directory, pathApi) {
9
+ return pathApi.join(directory, "node_modules", "npm", "bin", "npm-cli.js");
10
+ }
11
+
12
+ function npmCliPathForShim(shimPath, pathApi) {
13
+ const baseName = pathApi.basename(shimPath);
14
+ if (!/^npm(?:\.(?:cmd|ps1))?$/i.test(baseName)) return "";
15
+ return npmCliPathForDirectory(pathApi.dirname(shimPath), pathApi);
16
+ }
17
+
18
+ function isJavaScriptPath(filePath) {
19
+ return /\.(?:cjs|mjs|js)$/i.test(String(filePath || ""));
20
+ }
21
+
22
+ function envPathValue(env) {
23
+ return env.PATH || env.Path || env.path || "";
24
+ }
25
+
26
+ function pathEntries(env, pathApi) {
27
+ return String(envPathValue(env))
28
+ .split(pathApi.delimiter)
29
+ .map((entry) => entry.trim().replace(/^"|"$/g, ""))
30
+ .filter(Boolean);
31
+ }
32
+
33
+ function existingPath(candidates, exists) {
34
+ for (const candidate of candidates) {
35
+ try {
36
+ if (candidate && exists(candidate)) return candidate;
37
+ } catch {
38
+ // Continue to the next candidate when a path cannot be inspected.
39
+ }
40
+ }
41
+ return "";
42
+ }
43
+
44
+ /**
45
+ * Resolve npm without relying on Windows CreateProcess to discover npm.cmd.
46
+ * The returned display command intentionally remains npm-oriented while the
47
+ * executable command may run npm-cli.js through the current Node executable.
48
+ */
49
+ export function resolveNpmCommandInvocation(args = [], runtime = {}) {
50
+ const env = runtime.env ?? process.env;
51
+ const execPath = runtime.execPath ?? process.execPath;
52
+ const platform = runtime.platform ?? process.platform;
53
+ const exists = runtime.existsSync ?? existsSync;
54
+ const pathApi = pathApiForPlatform(platform);
55
+ const requestedArgs = Array.isArray(args) ? args.map(String) : [];
56
+ const configured = String(env.PI_WEBUI_NPM_BIN || "").trim();
57
+
58
+ if (configured) {
59
+ const configuredCli = existingPath([
60
+ isJavaScriptPath(configured) ? configured : "",
61
+ npmCliPathForShim(configured, pathApi),
62
+ ], exists);
63
+ if (configuredCli) {
64
+ return {
65
+ command: execPath,
66
+ args: [configuredCli, ...requestedArgs],
67
+ displayCommand: configured,
68
+ displayArgs: requestedArgs,
69
+ source: "configured-cli",
70
+ };
71
+ }
72
+ return {
73
+ command: configured,
74
+ args: requestedArgs,
75
+ displayCommand: configured,
76
+ displayArgs: requestedArgs,
77
+ source: "configured-command",
78
+ };
79
+ }
80
+
81
+ const npmExecPath = String(env.npm_execpath || "").trim();
82
+ const candidates = [
83
+ isJavaScriptPath(npmExecPath) ? npmExecPath : "",
84
+ npmCliPathForDirectory(pathApi.dirname(execPath), pathApi),
85
+ ...pathEntries(env, pathApi).map((entry) => npmCliPathForDirectory(entry, pathApi)),
86
+ ];
87
+ const npmCli = existingPath(candidates, exists);
88
+ if (npmCli) {
89
+ return {
90
+ command: execPath,
91
+ args: [npmCli, ...requestedArgs],
92
+ displayCommand: "npm",
93
+ displayArgs: requestedArgs,
94
+ source: "node-cli",
95
+ };
96
+ }
97
+
98
+ return {
99
+ command: "npm",
100
+ args: requestedArgs,
101
+ displayCommand: "npm",
102
+ displayArgs: requestedArgs,
103
+ source: "path-fallback",
104
+ };
105
+ }
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ const WINDOWS_TREE_KILL_TIMEOUT_MS = 5_000;
5
+
6
+ function directKill(target, signal) {
7
+ try {
8
+ return target?.kill?.(signal) ?? false;
9
+ } catch {
10
+ return false;
11
+ }
12
+ }
13
+
14
+ function windowsTaskkillCommand() {
15
+ const windowsRoot = process.env.SystemRoot || process.env.WINDIR;
16
+ return windowsRoot ? path.join(windowsRoot, "System32", "taskkill.exe") : "taskkill.exe";
17
+ }
18
+
19
+ /**
20
+ * Terminate a spawned process and its descendants.
21
+ *
22
+ * POSIX children must be spawned detached so their PID is also their process
23
+ * group ID. Windows has no equivalent Node signal API, so taskkill /T /F is
24
+ * used instead of child.kill(), which only terminates the direct child.
25
+ */
26
+ export function terminateProcessTree(target, signal = "SIGTERM") {
27
+ if (!target || target.exitCode !== null || target.signalCode !== null) return false;
28
+ const pid = Number(target.pid);
29
+
30
+ if (process.platform === "win32" && Number.isInteger(pid) && pid > 0) {
31
+ try {
32
+ const result = spawnSync(windowsTaskkillCommand(), ["/PID", String(pid), "/T", "/F"], {
33
+ windowsHide: true,
34
+ stdio: "ignore",
35
+ timeout: WINDOWS_TREE_KILL_TIMEOUT_MS,
36
+ });
37
+ if (!result.error && result.status === 0) return true;
38
+ } catch {
39
+ // Fall back to direct-child termination below.
40
+ }
41
+ return directKill(target, "SIGKILL");
42
+ }
43
+
44
+ if (Number.isInteger(pid) && pid > 0) {
45
+ try {
46
+ process.kill(-pid, signal);
47
+ return true;
48
+ } catch {
49
+ // Fall back when the child is not a process-group leader.
50
+ }
51
+ }
52
+ return directKill(target, signal);
53
+ }
@@ -0,0 +1,20 @@
1
+ export function piUpdateHelpSupportsAll(output) {
2
+ return /(?:^|[^A-Za-z0-9_-])--all(?:$|[^A-Za-z0-9_-])/.test(String(output || ""));
3
+ }
4
+
5
+ export function piUpdateCommandSteps({ all = false, supportsAll = false } = {}) {
6
+ if (!all) return [{ label: "Pi CLI", args: ["update", "--self"] }];
7
+ if (supportsAll) return [{ label: "Pi CLI and configured packages", args: ["update", "--all"] }];
8
+
9
+ // Explicit flags remain compatible with Pi releases that predate `--all`.
10
+ return [
11
+ { label: "Pi CLI", args: ["update", "--self"] },
12
+ { label: "configured Pi packages", args: ["update", "--extensions"] },
13
+ ];
14
+ }
15
+
16
+ export function piUpdateCommandText(options = {}) {
17
+ return piUpdateCommandSteps(options)
18
+ .map((step) => `pi ${step.args.join(" ")}`)
19
+ .join(" && ");
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.6.6",
3
+ "version": "0.6.8",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
@@ -72,7 +72,7 @@
72
72
  "@firstpick/pi-extension-tools": "^0.1.6",
73
73
  "@firstpick/pi-extension-workflows": "^0.1.2",
74
74
  "@firstpick/pi-package-remote-webui": "^0.1.5",
75
- "@firstpick/pi-prompts-git-pr": "^0.1.2",
75
+ "@firstpick/pi-prompts-git-pr": "^0.1.3",
76
76
  "@firstpick/pi-themes-bundle": "^0.1.4"
77
77
  },
78
78
  "files": [