@firstpick/pi-package-webui 0.6.7 → 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.
package/bin/pi-webui.mjs CHANGED
@@ -11,8 +11,10 @@ import { StringDecoder } from "node:string_decoder";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { promisify } from "node:util";
13
13
  import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
14
- import { AuthStorage, SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
14
+ import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
+ import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
+ import { nativeExportDownloadPayload } from "../lib/native-export-payload.mjs";
16
18
  import {
17
19
  collectOpenSessionFiles,
18
20
  deleteSessionFile,
@@ -21,7 +23,14 @@ import {
21
23
  validateSessionDelete,
22
24
  } from "../lib/session-actions.mjs";
23
25
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
26
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
27
+ import {
28
+ classifyGitPathFailure,
29
+ findWindowsReservedGitPath,
30
+ windowsReservedGitPathFailure,
31
+ } from "../lib/git-command-errors.mjs";
24
32
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
33
+ import { resolveNpmCommandInvocation } from "../lib/npm-command.mjs";
25
34
  import {
26
35
  GIT_WORKFLOW_DEFAULT_VARIANTS,
27
36
  GIT_WORKFLOW_DELIVERY_MODES,
@@ -110,7 +119,6 @@ const CORE_UPDATE_PACKAGE_NAMES = [PI_CODING_AGENT_PACKAGE, WEBUI_PACKAGE];
110
119
  const PACKAGE_UPDATE_TIMEOUT_MS = 15 * 60 * 1000;
111
120
  const PACKAGE_UPDATE_OUTPUT_MAX_CHARS = 120_000;
112
121
  const CODEX_USAGE_TIMEOUT_MS = 15 * 1000;
113
- const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
114
122
  const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
115
123
  const OPENAI_CODEX_USAGE_ENDPOINT = process.env.PI_WEBUI_CODEX_USAGE_URL || "https://chatgpt.com/backend-api/wham/usage";
116
124
  const CLAUDE_USAGE_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_WEBUI_CLAUDE_USAGE_TIMEOUT_MS || "30000", 10) || 30000);
@@ -1610,10 +1618,9 @@ async function installOptionalFeaturePackage(featureId) {
1610
1618
  });
1611
1619
  }
1612
1620
 
1613
- const npmCommand = process.env.PI_WEBUI_NPM_BIN || "npm";
1614
- const args = ["install", "--prefix", installRoot, packageName];
1615
- const command = formatCommandForDisplay(npmCommand, args);
1616
- const result = await runCommand(npmCommand, args, {
1621
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, packageName]);
1622
+ const command = npmCommand.displayCommand;
1623
+ const result = await runCommand(npmCommand.command, npmCommand.args, {
1617
1624
  cwd: installRoot,
1618
1625
  timeoutMs: 5 * 60 * 1000,
1619
1626
  maxOutputLength: 80000,
@@ -1777,6 +1784,65 @@ async function saveRemoteAuthPreference(enabled) {
1777
1784
  return persistedRemoteAuthEnabled;
1778
1785
  }
1779
1786
 
1787
+ let safetyGuardConfigModulePromise;
1788
+
1789
+ async function safetyGuardConfigModule() {
1790
+ if (!safetyGuardConfigModulePromise) {
1791
+ safetyGuardConfigModulePromise = (async () => {
1792
+ const specifiers = [
1793
+ "@firstpick/pi-extension-safety-guard/src/config.mjs",
1794
+ new URL("../../pi-extension-safety-guard/src/config.mjs", import.meta.url).href,
1795
+ ];
1796
+ const failures = [];
1797
+ for (const specifier of specifiers) {
1798
+ try {
1799
+ return await import(specifier);
1800
+ } catch (error) {
1801
+ failures.push(error instanceof Error ? error.message : String(error));
1802
+ }
1803
+ }
1804
+ throw makeHttpError(503, `Safety guard setup support is unavailable. Update @firstpick/pi-extension-safety-guard and restart Web UI. ${failures.at(-1) || ""}`.trim());
1805
+ })().catch((error) => {
1806
+ safetyGuardConfigModulePromise = undefined;
1807
+ throw error;
1808
+ });
1809
+ }
1810
+ return safetyGuardConfigModulePromise;
1811
+ }
1812
+
1813
+ async function safetyGuardConfigData() {
1814
+ const settingsModule = await safetyGuardConfigModule();
1815
+ const config = settingsModule.readSafetyGuardConfig();
1816
+ return {
1817
+ config,
1818
+ defaults: settingsModule.defaultSafetyGuardConfig(),
1819
+ categories: [...settingsModule.SAFETY_GUARD_CATEGORIES],
1820
+ contextLines: {
1821
+ min: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MIN,
1822
+ max: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MAX,
1823
+ },
1824
+ version: settingsModule.SAFETY_GUARD_CONFIG_VERSION,
1825
+ path: settingsModule.safetyGuardConfigFile(),
1826
+ };
1827
+ }
1828
+
1829
+ async function saveSafetyGuardConfigData(body = {}) {
1830
+ const settingsModule = await safetyGuardConfigModule();
1831
+ const submitted = body.config && typeof body.config === "object" ? body.config : body;
1832
+ try {
1833
+ settingsModule.assertSafetyGuardConfigPatch(submitted);
1834
+ } catch (error) {
1835
+ throw makeHttpError(400, error instanceof Error ? error.message : String(error));
1836
+ }
1837
+
1838
+ try {
1839
+ const config = settingsModule.writeSafetyGuardConfig(submitted);
1840
+ return { ...(await safetyGuardConfigData()), config };
1841
+ } catch (error) {
1842
+ throw makeHttpError(500, error instanceof Error ? error.message : String(error));
1843
+ }
1844
+ }
1845
+
1780
1846
  function gitWorkflowModelKey(model) {
1781
1847
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1782
1848
  }
@@ -2970,18 +3036,7 @@ function scheduleAppRunnerBroadcast(tab) {
2970
3036
 
2971
3037
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
2972
3038
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2973
- try {
2974
- if (process.platform !== "win32" && run.pid) process.kill(-run.pid, signal);
2975
- else run.child.kill(signal);
2976
- return true;
2977
- } catch {
2978
- try {
2979
- run.child.kill(signal);
2980
- return true;
2981
- } catch {
2982
- return false;
2983
- }
2984
- }
3039
+ return terminateProcessTree(run.child, signal);
2985
3040
  }
2986
3041
 
2987
3042
  function appRunnerStdinWritable(run) {
@@ -2991,7 +3046,10 @@ function appRunnerStdinWritable(run) {
2991
3046
 
2992
3047
  function interruptAppRunnerChild(run) {
2993
3048
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2994
- if (appRunnerStdinWritable(run) && (run.executionMode === "pty" || process.platform === "win32")) {
3049
+ // Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
3050
+ // complete tree there so npm/bash wrappers cannot leave orphaned servers.
3051
+ if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
3052
+ if (appRunnerStdinWritable(run) && run.executionMode === "pty") {
2995
3053
  try {
2996
3054
  run.child.stdin.write("\x03", "utf8");
2997
3055
  return true;
@@ -3117,14 +3175,15 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
3117
3175
  const run = tab?.appRunner;
3118
3176
  if (!run || run.status !== "running") return false;
3119
3177
  run.stopping = true;
3120
- appendAppRunnerLine(run, `# ${reason}; sending ${force ? "SIGKILL" : "Ctrl+C"}`);
3178
+ const action = process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
3179
+ appendAppRunnerLine(run, `# ${reason}; ${action}`);
3121
3180
  if (force) terminateAppRunnerChild(run, "SIGKILL");
3122
3181
  else interruptAppRunnerChild(run);
3123
3182
  if (!force) {
3124
3183
  clearTimeout(run.stopTimer);
3125
3184
  run.stopTimer = setTimeout(() => {
3126
3185
  if (run.status === "running") {
3127
- appendAppRunnerLine(run, "# app runner did not stop after Ctrl+C; sending SIGKILL");
3186
+ appendAppRunnerLine(run, "# app runner did not stop within the grace period; forcing process-tree termination");
3128
3187
  terminateAppRunnerChild(run, "SIGKILL");
3129
3188
  scheduleAppRunnerBroadcast(tab);
3130
3189
  }
@@ -3382,38 +3441,24 @@ function normalizeCodexUsagePayload(rawPayload) {
3382
3441
  }
3383
3442
 
3384
3443
  async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3385
- const authStorage = AuthStorage.create();
3386
- const stored = authStorage.get(OPENAI_CODEX_PROVIDER_ID);
3387
- const storedExpires = numericValue(stored?.expires);
3388
- const shouldRefresh = stored?.type === "oauth" && (forceRefresh || storedExpires === undefined || Date.now() + CODEX_TOKEN_REFRESH_SKEW_MS >= storedExpires);
3389
- let accessToken;
3390
- let refreshed = false;
3391
-
3392
- if (shouldRefresh) {
3393
- try {
3394
- const refreshResult = await authStorage.refreshOAuthTokenWithLock(OPENAI_CODEX_PROVIDER_ID);
3395
- if (refreshResult?.apiKey) {
3396
- accessToken = refreshResult.apiKey;
3397
- refreshed = forceRefresh || refreshResult.newCredentials?.access !== stored?.access;
3398
- }
3399
- } catch (error) {
3400
- if (forceRefresh || !storedExpires || Date.now() >= storedExpires) {
3401
- throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
3402
- }
3403
- console.warn(`OpenAI Codex token refresh warning: ${sanitizeError(error)}`);
3404
- }
3444
+ const { modelRuntime } = await authContext();
3445
+ let resolved;
3446
+ try {
3447
+ resolved = await resolveCodexUsageAuth(modelRuntime, OPENAI_CODEX_PROVIDER_ID, { forceRefresh });
3448
+ } catch {
3449
+ // Client-facing auth failures must not include provider stack traces,
3450
+ // refresh tokens, or raw upstream error details.
3451
+ throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
3405
3452
  }
3406
3453
 
3454
+ const accessToken = resolved.accessToken;
3407
3455
  if (!accessToken) {
3408
- accessToken = await authStorage.getApiKey(OPENAI_CODEX_PROVIDER_ID, { includeFallback: false });
3409
- }
3410
- if (!accessToken) {
3411
- const status = authStorage.getAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3456
+ const status = modelRuntime.getProviderAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3412
3457
  if (status.configured) throw makeHttpError(401, "OpenAI Codex OAuth token is expired or unavailable. Run /login to refresh credentials.");
3413
3458
  throw makeHttpError(401, "OpenAI Codex OAuth is not configured. Run /login and choose ChatGPT Plus/Pro (Codex Subscription).");
3414
3459
  }
3415
3460
 
3416
- const latest = authStorage.get(OPENAI_CODEX_PROVIDER_ID) || stored || {};
3461
+ const latest = resolved.credential || {};
3417
3462
  const accountId = latest.accountId || codexAccountIdFromAccessToken(accessToken);
3418
3463
  if (!accountId) {
3419
3464
  throw makeHttpError(401, "OpenAI Codex account id is unavailable. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) again.");
@@ -3422,7 +3467,7 @@ async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3422
3467
  return {
3423
3468
  accessToken,
3424
3469
  accountId,
3425
- refreshed,
3470
+ refreshed: resolved.refreshed,
3426
3471
  source: latest.type === "oauth" ? "stored-oauth" : "api-key",
3427
3472
  expiresAt: numericValue(latest.expires) ? new Date(numericValue(latest.expires)).toISOString() : undefined,
3428
3473
  };
@@ -3468,7 +3513,7 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
3468
3513
  try {
3469
3514
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3470
3515
  } catch (error) {
3471
- if (error?.openaiStatus === 401 && !credentials.refreshed) {
3516
+ if (error?.openaiStatus === 401) {
3472
3517
  credentials = await getOpenAICodexUsageCredentials({ forceRefresh: true });
3473
3518
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3474
3519
  } else {
@@ -4635,15 +4680,30 @@ async function runGitMutationCommand(args, options = {}) {
4635
4680
  function gitMutationPayload(result) {
4636
4681
  const payload = gitWorkflowCommandPayload(result);
4637
4682
  if (!payload.ok) {
4683
+ let pathFailure = null;
4638
4684
  if (isGitLockFailure(result)) {
4639
4685
  payload.code = "REPO_BUSY";
4640
4686
  payload.hint = "Another git process is using this repository. Retry once it finishes.";
4687
+ } else {
4688
+ pathFailure = classifyGitPathFailure(result);
4689
+ if (pathFailure) Object.assign(payload, pathFailure);
4641
4690
  }
4642
- payload.error = String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4691
+ payload.error = pathFailure?.error || String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4643
4692
  }
4644
4693
  return payload;
4645
4694
  }
4646
4695
 
4696
+ async function gitAddAllPayload(cwd) {
4697
+ await getGitRoot(cwd);
4698
+ if (platform() === "win32") {
4699
+ const untrackedText = await runGitReadCommand(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
4700
+ const invalidPath = findWindowsReservedGitPath(untrackedText);
4701
+ const pathFailure = windowsReservedGitPathFailure(invalidPath);
4702
+ if (pathFailure) return { ok: false, ...pathFailure };
4703
+ }
4704
+ return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
4705
+ }
4706
+
4647
4707
  async function runGuardedGitMutation(args, options = {}) {
4648
4708
  try {
4649
4709
  return gitMutationPayload(await runGitMutationCommand(args, options));
@@ -4875,6 +4935,72 @@ async function readGitOperationSnapshot(cwd) {
4875
4935
  };
4876
4936
  }
4877
4937
 
4938
+ function gitConflictResolutionAgentPrompt(operation) {
4939
+ const conflicts = (operation.conflicts || []).map((conflict) => `- ${conflict.status || "UU"} ${JSON.stringify(String(conflict.path || ""))}`);
4940
+ const summary = operation.summary || {};
4941
+ return [
4942
+ `Resolve the current Git ${operation.operation} conflicts in this working tree.`,
4943
+ "",
4944
+ `Repository root: ${JSON.stringify(String(operation.root || ""))}`,
4945
+ `Branch: ${operation.branch || "detached or unknown"}`,
4946
+ `Working tree: ${summary.staged || 0} staged, ${summary.unstaged || 0} unstaged, ${conflicts.length} conflicted`,
4947
+ "Conflicted files:",
4948
+ ...conflicts,
4949
+ "",
4950
+ "Requirements:",
4951
+ "- Inspect git status plus the staged, unstaged, and unmerged diffs before editing.",
4952
+ "- Resolve only the currently unmerged files and preserve the intended changes from both sides.",
4953
+ "- Stage each resolved file with git add.",
4954
+ `- Do not continue, skip, abort, commit, reset, or push the ${operation.operation}.`,
4955
+ "- Verify git diff --name-only --diff-filter=U is empty, then report what you resolved and any uncertainty.",
4956
+ ].join("\n");
4957
+ }
4958
+
4959
+ async function openGitConflictResolutionAgentTab(sourceTab) {
4960
+ const operation = await readGitOperationSnapshot(sourceTab.cwd);
4961
+ if (!operation.operation || operation.operation === "bisect") throw makeHttpError(409, "No conflict-resolution Git operation is in progress");
4962
+ if (!operation.conflicts?.length) throw makeHttpError(409, "No unmerged files remain to send to an agent");
4963
+
4964
+ const targetTab = await createTab({
4965
+ title: `Resolve ${operation.operation} conflicts`,
4966
+ titleSource: "explicit",
4967
+ conversationStarted: true,
4968
+ cwd: operation.root,
4969
+ });
4970
+ const command = { type: "prompt", message: gitConflictResolutionAgentPrompt(operation) };
4971
+ markTabWorking(targetTab);
4972
+ let response;
4973
+ try {
4974
+ response = await targetTab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
4975
+ } catch (error) {
4976
+ markTabIdle(targetTab);
4977
+ throw error;
4978
+ }
4979
+ if (response.success === false) {
4980
+ markTabIdle(targetTab);
4981
+ throw makeHttpError(502, response.error || "The conflict-resolution agent rejected the handoff prompt");
4982
+ }
4983
+ recordEvent({
4984
+ type: "webui_git_conflict_agent_started",
4985
+ sourceTabId: sourceTab.id,
4986
+ tabId: targetTab.id,
4987
+ cwd: operation.root,
4988
+ operation: operation.operation,
4989
+ conflicts: operation.conflicts.length,
4990
+ });
4991
+ return {
4992
+ sourceTabId: sourceTab.id,
4993
+ tab: tabMeta(targetTab),
4994
+ tabs: listTabs(),
4995
+ operation: {
4996
+ operation: operation.operation,
4997
+ root: operation.root,
4998
+ branch: operation.branch,
4999
+ conflicts: operation.conflicts.map(({ path: conflictPath, status }) => ({ path: conflictPath, status })),
5000
+ },
5001
+ };
5002
+ }
5003
+
4878
5004
  async function gitOperationStageFile(cwd, body = {}) {
4879
5005
  const root = await getGitRoot(cwd);
4880
5006
  const kind = await detectGitOperationKind(root);
@@ -6111,8 +6237,7 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6111
6237
  return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
6112
6238
  }
6113
6239
  case "/api/git-workflow/add":
6114
- await getGitRoot(cwd);
6115
- return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
6240
+ return gitAddAllPayload(cwd);
6116
6241
  case "/api/git-workflow/branch": {
6117
6242
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
6118
6243
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -8105,17 +8230,23 @@ function packageInstallSpecs(packageNames) {
8105
8230
  return packageNames.map((packageName) => `${packageName}@latest`);
8106
8231
  }
8107
8232
 
8108
- function npmCommandName() {
8109
- return process.env.PI_WEBUI_NPM_BIN || "npm";
8233
+ function resolvedNpmCommand(args) {
8234
+ const invocation = resolveNpmCommandInvocation(args);
8235
+ return {
8236
+ command: invocation.command,
8237
+ args: invocation.args,
8238
+ displayCommand: formatCommandForDisplay(invocation.displayCommand, invocation.displayArgs),
8239
+ };
8110
8240
  }
8111
8241
 
8112
8242
  function npmPrefixUpdateTask(label, installRoot, packageNames) {
8113
8243
  if (!packageNames.length) return null;
8114
- const npmCommand = npmCommandName();
8244
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)]);
8115
8245
  return {
8116
8246
  label,
8117
- command: npmCommand,
8118
- args: ["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)],
8247
+ command: npmCommand.command,
8248
+ args: npmCommand.args,
8249
+ displayCommand: npmCommand.displayCommand,
8119
8250
  cwd: installRoot,
8120
8251
  };
8121
8252
  }
@@ -8170,8 +8301,8 @@ async function projectPackageRootUpdateTasks() {
8170
8301
  }
8171
8302
 
8172
8303
  async function npmGlobalNodeModulesRoot() {
8173
- const npmCommand = npmCommandName();
8174
- const result = await runCommand(npmCommand, ["root", "-g"], { timeoutMs: 5000, maxOutputLength: 8000 });
8304
+ const npmCommand = resolvedNpmCommand(["root", "-g"]);
8305
+ const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
8175
8306
  if (result.exitCode !== 0 || result.timedOut || result.error) return null;
8176
8307
  return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
8177
8308
  }
@@ -8180,11 +8311,12 @@ async function npmGlobalPackageRootUpdateTask() {
8180
8311
  const nodeModulesRoot = await npmGlobalNodeModulesRoot();
8181
8312
  const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
8182
8313
  if (!packages.length) return null;
8183
- const npmCommand = npmCommandName();
8314
+ const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)]);
8184
8315
  return {
8185
8316
  label: "global npm package root",
8186
- command: npmCommand,
8187
- args: ["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)],
8317
+ command: npmCommand.command,
8318
+ args: npmCommand.args,
8319
+ displayCommand: npmCommand.displayCommand,
8188
8320
  cwd: nodeModulesRoot ? path.dirname(nodeModulesRoot) : process.cwd(),
8189
8321
  };
8190
8322
  }
@@ -8590,8 +8722,46 @@ async function sendWebuiHelperCommand(tab, action, payload = {}, timeoutMs = WEB
8590
8722
  }
8591
8723
  }
8592
8724
 
8593
- async function getToolConfigData(tab) {
8594
- return sendWebuiHelperCommand(tab, "tools-state");
8725
+ function requireResourceScope(value) {
8726
+ const scope = String(value || "session").trim().toLowerCase();
8727
+ if (scope !== "session" && scope !== "global") throw makeHttpError(400, "Resource scope must be session or global");
8728
+ return scope;
8729
+ }
8730
+
8731
+ function selectedResourceNames(body, enabledKey, disabledKey, resources, label) {
8732
+ const allNames = new Set((resources || []).map((resource) => String(resource.name || "").trim()).filter(Boolean));
8733
+ if (Array.isArray(body?.[enabledKey])) {
8734
+ return [...new Set(body[enabledKey].map((name) => String(name || "").trim()).filter((name) => allNames.has(name)))];
8735
+ }
8736
+ if (Array.isArray(body?.[disabledKey])) {
8737
+ const disabled = new Set(body[disabledKey].map((name) => String(name || "").trim()));
8738
+ return [...allNames].filter((name) => !disabled.has(name));
8739
+ }
8740
+ throw makeHttpError(400, `${label} update requires ${enabledKey} or ${disabledKey}`);
8741
+ }
8742
+
8743
+ function preserveUnavailableGlobalNames(selectedNames, resources, previousNames) {
8744
+ if (!Array.isArray(previousNames)) return selectedNames;
8745
+ const available = new Set((resources || []).map((resource) => resource.name));
8746
+ return [...new Set([...selectedNames, ...previousNames.filter((name) => !available.has(name))])];
8747
+ }
8748
+
8749
+ function globalResourcePayload(key, resources, configuredNames) {
8750
+ const configured = Array.isArray(configuredNames);
8751
+ const enabled = new Set(configured ? configuredNames : resources.filter((resource) => resource.enabled !== false).map((resource) => resource.name));
8752
+ return {
8753
+ scope: "global",
8754
+ configured,
8755
+ [key]: resources.map((resource) => ({ ...resource, enabled: enabled.has(resource.name) })),
8756
+ };
8757
+ }
8758
+
8759
+ async function getToolConfigData(tab, requestedScope = "session") {
8760
+ const scope = requireResourceScope(requestedScope);
8761
+ const runtime = await sendWebuiHelperCommand(tab, "tools-state");
8762
+ if (scope === "session") return { ...runtime, scope };
8763
+ const defaults = (await readWebuiSettings()).resourceDefaults.tools.enabledTools;
8764
+ return globalResourcePayload("tools", runtime.tools || [], defaults);
8595
8765
  }
8596
8766
 
8597
8767
  let packageManagerModulePromise;
@@ -8784,88 +8954,56 @@ async function saveSkillFileData(tab, body = {}) {
8784
8954
  };
8785
8955
  }
8786
8956
 
8787
- function getResourcePatternForSkill(tab, skill) {
8788
- const info = skill.sourceInfo || {};
8789
- const baseDir = info.baseDir || (info.scope === "project" ? path.join(tab?.cwd || options.cwd, ".pi") : agentDir);
8790
- return path.relative(baseDir, skill.filePath);
8791
- }
8792
-
8793
8957
  async function setToolConfigData(tab, body) {
8794
- return sendWebuiHelperCommand(tab, "tools-set", {
8795
- enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
8796
- disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
8797
- });
8798
- }
8958
+ const scope = requireResourceScope(body?.scope);
8959
+ if (scope === "session") {
8960
+ return {
8961
+ ...(await sendWebuiHelperCommand(tab, "tools-set", {
8962
+ enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
8963
+ disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
8964
+ })),
8965
+ scope,
8966
+ };
8967
+ }
8799
8968
 
8800
- async function getSkillConfigDataFromRuntime(tab) {
8801
- return sendWebuiHelperCommand(tab, "skills-state");
8969
+ const runtime = await sendWebuiHelperCommand(tab, "tools-state");
8970
+ const currentSettings = await readWebuiSettings();
8971
+ const selectedTools = selectedResourceNames(body, "enabledTools", "disabledTools", runtime.tools, "Tool");
8972
+ const enabledTools = preserveUnavailableGlobalNames(selectedTools, runtime.tools, currentSettings.resourceDefaults.tools.enabledTools);
8973
+ await writeWebuiSettings({ resourceDefaults: { tools: { enabledTools } } });
8974
+ return globalResourcePayload("tools", runtime.tools || [], enabledTools);
8802
8975
  }
8803
8976
 
8804
- function desiredSkillEnabledFromBody(skillName, body) {
8805
- if (Array.isArray(body.enabledSkills)) return body.enabledSkills.map(String).includes(skillName);
8806
- if (Array.isArray(body.disabledSkills)) return !body.disabledSkills.map(String).includes(skillName);
8807
- throw makeHttpError(400, "Skill update requires enabledSkills or disabledSkills");
8977
+ async function getSkillConfigData(tab, requestedScope = "session") {
8978
+ const scope = requireResourceScope(requestedScope);
8979
+ const runtime = await getSkillConfigDataFromRuntime(tab);
8980
+ if (scope === "session") return { ...runtime, scope };
8981
+ const defaults = (await readWebuiSettings()).resourceDefaults.skills.enabledSkills;
8982
+ return globalResourcePayload("skills", runtime.skills || [], defaults);
8808
8983
  }
8809
8984
 
8810
- function updatePatternListForResource(current, pattern, enabled) {
8811
- const updated = (current || []).filter((item) => {
8812
- const text = String(item || "");
8813
- const stripped = text.startsWith("!") || text.startsWith("+") || text.startsWith("-") ? text.slice(1) : text;
8814
- return stripped !== pattern;
8815
- });
8816
- updated.push(`${enabled ? "+" : "-"}${pattern}`);
8817
- return updated;
8818
- }
8819
-
8820
- function setSkillPathsForScope(settingsManager, scope, updated) {
8821
- if (scope === "project") settingsManager.setProjectSkillPaths(updated);
8822
- else settingsManager.setSkillPaths(updated);
8823
- }
8824
-
8825
- function toggleConfiguredSkill(tab, settingsManager, skill, enabled) {
8826
- const info = skill.sourceInfo || {};
8827
- const scope = info.scope === "project" ? "project" : "user";
8828
- if (info.origin === "package") {
8829
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8830
- const packages = [...(settings.packages || [])];
8831
- const packageIndex = packages.findIndex((item) => (typeof item === "string" ? item : item?.source) === info.source);
8832
- if (packageIndex < 0) return false;
8833
- let packageEntry = packages[packageIndex];
8834
- if (typeof packageEntry === "string") {
8835
- packageEntry = { source: packageEntry };
8836
- packages[packageIndex] = packageEntry;
8837
- }
8838
- const pattern = path.relative(info.baseDir || path.dirname(skill.filePath), skill.filePath);
8839
- packageEntry.skills = updatePatternListForResource(packageEntry.skills || [], pattern, enabled);
8840
- if (scope === "project") settingsManager.setProjectPackages(packages);
8841
- else settingsManager.setPackages(packages);
8842
- return true;
8843
- }
8844
-
8845
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8846
- const pattern = getResourcePatternForSkill(tab, skill);
8847
- setSkillPathsForScope(settingsManager, scope, updatePatternListForResource(settings.skills || [], pattern, enabled));
8848
- return true;
8985
+ async function getSkillConfigDataFromRuntime(tab) {
8986
+ return sendWebuiHelperCommand(tab, "skills-state");
8849
8987
  }
8850
8988
 
8851
8989
  async function setSkillConfigData(tab, body) {
8852
- const { skills, settingsManager } = await resolveSkillResources(tab);
8853
- let configChanged = false;
8854
- for (const skill of skills) {
8855
- const desiredEnabled = desiredSkillEnabledFromBody(skill.name, body);
8856
- if (skill.configEnabled !== desiredEnabled && toggleConfiguredSkill(tab, settingsManager, skill, desiredEnabled)) configChanged = true;
8857
- }
8858
-
8859
- const runtimeOnly = skills.length === 0;
8860
- if (runtimeOnly) {
8861
- await sendWebuiHelperCommand(tab, "skills-set", {
8862
- enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
8863
- disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
8864
- });
8990
+ const scope = requireResourceScope(body?.scope);
8991
+ if (scope === "session") {
8992
+ return {
8993
+ ...(await sendWebuiHelperCommand(tab, "skills-set", {
8994
+ enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
8995
+ disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
8996
+ })),
8997
+ scope,
8998
+ };
8865
8999
  }
8866
9000
 
8867
- const activeTab = configChanged ? await restartTabRpc(tab, "skills-config") : tab;
8868
- return getMergedSkillConfigData(activeTab);
9001
+ const runtime = await getSkillConfigDataFromRuntime(tab);
9002
+ const currentSettings = await readWebuiSettings();
9003
+ const selectedSkills = selectedResourceNames(body, "enabledSkills", "disabledSkills", runtime.skills, "Skill");
9004
+ const enabledSkills = preserveUnavailableGlobalNames(selectedSkills, runtime.skills, currentSettings.resourceDefaults.skills.enabledSkills);
9005
+ await writeWebuiSettings({ resourceDefaults: { skills: { enabledSkills } } });
9006
+ return globalResourcePayload("skills", runtime.skills || [], enabledSkills);
8869
9007
  }
8870
9008
 
8871
9009
  function settingsManagerForTab(tab) {
@@ -10159,7 +10297,12 @@ async function switchTabSession(tab, sessionPath) {
10159
10297
  let authContextCache;
10160
10298
 
10161
10299
  function authContext() {
10162
- if (!authContextCache) authContextCache = createAuthContext();
10300
+ if (!authContextCache) {
10301
+ authContextCache = createAuthContext().catch((error) => {
10302
+ authContextCache = undefined;
10303
+ throw error;
10304
+ });
10305
+ }
10163
10306
  return authContextCache;
10164
10307
  }
10165
10308
 
@@ -10192,13 +10335,13 @@ async function deleteSessionData(tab, body) {
10192
10335
  };
10193
10336
  }
10194
10337
 
10195
- function getAuthProvidersData() {
10196
- return authProvidersPayload(authContext().modelRegistry);
10338
+ async function getAuthProvidersData() {
10339
+ return authProvidersPayload((await authContext()).modelRuntime);
10197
10340
  }
10198
10341
 
10199
- function logoutAuthProviderData(body) {
10342
+ async function logoutAuthProviderData(body) {
10200
10343
  if (body.confirmed !== true) throw makeHttpError(409, "Logout requires explicit confirmation (confirmed: true).");
10201
- return logoutStoredProvider(authContext().modelRegistry, body.provider || body.providerId);
10344
+ return logoutStoredProvider((await authContext()).modelRuntime, body.provider || body.providerId);
10202
10345
  }
10203
10346
 
10204
10347
  async function navigateSessionTree(tab, body) {
@@ -10274,14 +10417,12 @@ async function handleNativeExportCommand(tab, args, req) {
10274
10417
  fileName: `${nativeExportBaseName(tab, state)}.html`,
10275
10418
  contentType: MIME_TYPES.get(".html"),
10276
10419
  });
10277
- return respondNative("export", {
10278
- status: "succeeded",
10279
- level: "info",
10280
- message: `Exported current session to HTML.\nDownload: ${download.fileName}\nOpen it in your browser when prompted.\nOpen URL: ${download.openUrl || download.url}\nDownload URL: ${download.url}\nLink expires: ${download.expiresAt}`,
10420
+ return respondNative("export", nativeExportDownloadPayload({
10421
+ localRequest: isLocalRequest(req),
10422
+ exportedPath,
10281
10423
  download,
10282
- result: response.data,
10283
- refresh: ["state"],
10284
- });
10424
+ responseData: response.data,
10425
+ }));
10285
10426
  }
10286
10427
 
10287
10428
  if (!isLocalRequest(req)) {
@@ -11482,14 +11623,14 @@ const server = createServer(async (req, res) => {
11482
11623
  }
11483
11624
 
11484
11625
  if (url.pathname === "/api/auth-providers" && req.method === "GET") {
11485
- sendJson(res, 200, { ok: true, data: getAuthProvidersData() });
11626
+ sendJson(res, 200, { ok: true, data: await getAuthProvidersData() });
11486
11627
  return;
11487
11628
  }
11488
11629
 
11489
11630
  if (url.pathname === "/api/auth-logout" && req.method === "POST") {
11490
11631
  requireLocalhostRoute(req, url.pathname);
11491
11632
  const body = await readJsonBody(req);
11492
- sendJson(res, 200, { ok: true, data: logoutAuthProviderData(body) });
11633
+ sendJson(res, 200, { ok: true, data: await logoutAuthProviderData(body) });
11493
11634
  return;
11494
11635
  }
11495
11636
 
@@ -11575,7 +11716,7 @@ const server = createServer(async (req, res) => {
11575
11716
 
11576
11717
  if (url.pathname === "/api/tools" && req.method === "GET") {
11577
11718
  const tab = getRequestedTab(req, url);
11578
- sendJson(res, 200, { ok: true, data: await getToolConfigData(tab) });
11719
+ sendJson(res, 200, { ok: true, data: await getToolConfigData(tab, url.searchParams.get("scope")) });
11579
11720
  return;
11580
11721
  }
11581
11722
 
@@ -11589,7 +11730,7 @@ const server = createServer(async (req, res) => {
11589
11730
 
11590
11731
  if (url.pathname === "/api/skills" && req.method === "GET") {
11591
11732
  const tab = getRequestedTab(req, url);
11592
- sendJson(res, 200, { ok: true, data: await getMergedSkillConfigData(tab) });
11733
+ sendJson(res, 200, { ok: true, data: await getSkillConfigData(tab, url.searchParams.get("scope")) });
11593
11734
  return;
11594
11735
  }
11595
11736
 
@@ -11616,6 +11757,20 @@ const server = createServer(async (req, res) => {
11616
11757
  return;
11617
11758
  }
11618
11759
 
11760
+ if (url.pathname === "/api/safety-guard/config" && req.method === "GET") {
11761
+ getRequestedTab(req, url);
11762
+ sendJson(res, 200, { ok: true, data: await safetyGuardConfigData() });
11763
+ return;
11764
+ }
11765
+
11766
+ if (url.pathname === "/api/safety-guard/config" && req.method === "POST") {
11767
+ const body = await readJsonBody(req);
11768
+ const tab = getRequestedTab(req, url, body);
11769
+ ensureNaturalConversationRouteAllowed(tab, "safety guard setup changes are blocked");
11770
+ sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(body) });
11771
+ return;
11772
+ }
11773
+
11619
11774
  if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11620
11775
  const tab = getRequestedTab(req, url);
11621
11776
  sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
@@ -11856,6 +12011,7 @@ const server = createServer(async (req, res) => {
11856
12011
  "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11857
12012
  "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11858
12013
  "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
12014
+ "/api/git-operation/resolve-with-agent": (_cwd, _body, tab) => openGitConflictResolutionAgentTab(tab),
11859
12015
  "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11860
12016
  "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11861
12017
  "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
@@ -11874,7 +12030,7 @@ const server = createServer(async (req, res) => {
11874
12030
  const tab = getRequestedTab(req, url, body);
11875
12031
  ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11876
12032
  try {
11877
- const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
12033
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body, tab);
11878
12034
  sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11879
12035
  } catch (error) {
11880
12036
  gitActionError(error);