@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.
package/bin/pi-webui.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
3
  import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
4
- import { createReadStream } from "node:fs";
4
+ import { createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
7
  import { access, copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
@@ -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,6 +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";
32
+ import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
33
+ import { resolveNpmCommandInvocation } from "../lib/npm-command.mjs";
24
34
  import {
25
35
  GIT_WORKFLOW_DEFAULT_VARIANTS,
26
36
  GIT_WORKFLOW_DELIVERY_MODES,
@@ -109,7 +119,6 @@ const CORE_UPDATE_PACKAGE_NAMES = [PI_CODING_AGENT_PACKAGE, WEBUI_PACKAGE];
109
119
  const PACKAGE_UPDATE_TIMEOUT_MS = 15 * 60 * 1000;
110
120
  const PACKAGE_UPDATE_OUTPUT_MAX_CHARS = 120_000;
111
121
  const CODEX_USAGE_TIMEOUT_MS = 15 * 1000;
112
- const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
113
122
  const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
114
123
  const OPENAI_CODEX_USAGE_ENDPOINT = process.env.PI_WEBUI_CODEX_USAGE_URL || "https://chatgpt.com/backend-api/wham/usage";
115
124
  const CLAUDE_USAGE_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_WEBUI_CLAUDE_USAGE_TIMEOUT_MS || "30000", 10) || 30000);
@@ -259,6 +268,11 @@ const MIME_TYPES = new Map([
259
268
  [".css", "text/css; charset=utf-8"],
260
269
  [".svg", "image/svg+xml"],
261
270
  [".png", "image/png"],
271
+ [".jpg", "image/jpeg"],
272
+ [".jpeg", "image/jpeg"],
273
+ [".pdf", "application/pdf"],
274
+ [".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
275
+ [".json", "application/json; charset=utf-8"],
262
276
  [".webp", "image/webp"],
263
277
  [".webmanifest", "application/manifest+json; charset=utf-8"],
264
278
  ]);
@@ -1010,6 +1024,163 @@ async function sendNativeDownload(res, token, { inline = false } = {}) {
1010
1024
  });
1011
1025
  }
1012
1026
 
1027
+ const documentArtifactTokens = new Map();
1028
+ const DEFAULT_DOCUMENT_ARTIFACT_ROOT = path.join(tmpdir(), "pi-extension-docx");
1029
+ const DOCUMENT_ARTIFACT_MANIFEST_LIMIT_BYTES = 2 * 1024 * 1024;
1030
+ const DOCUMENT_ARTIFACT_PAGE_LIMIT = 10_000;
1031
+
1032
+ function documentArtifactRoots() {
1033
+ return [...new Set([DEFAULT_DOCUMENT_ARTIFACT_ROOT, ...String(process.env.PI_WEBUI_ARTIFACT_ROOTS || "").split(path.delimiter).map((item) => item.trim()).filter(Boolean)].map((item) => path.resolve(item)))];
1034
+ }
1035
+
1036
+ function documentArtifactPath(filePath) {
1037
+ if (typeof filePath !== "string" || !path.isAbsolute(filePath)) throw new Error("artifact path is unavailable");
1038
+ const info = statSync(filePath, { throwIfNoEntry: false });
1039
+ if (!info?.isFile()) throw new Error("artifact file is unavailable");
1040
+ const real = realpathSync(filePath);
1041
+ const root = documentArtifactRoots().map((candidate) => { try { return realpathSync(candidate); } catch { return null; } }).find((candidate) => candidate && (candidate === real || pathInside(candidate, real)));
1042
+ if (!root) throw new Error("artifact path is outside configured roots");
1043
+ return { path: real, root, size: info.size };
1044
+ }
1045
+
1046
+ function pruneDocumentArtifactTokens(now = Date.now()) {
1047
+ for (const [token, item] of documentArtifactTokens) if (!item || item.expiresAt <= now) documentArtifactTokens.delete(token);
1048
+ }
1049
+
1050
+ const PRIVATE_ARTIFACT_KEYS = new Set(["manifestPath", "downloadPath", "outputPath", "sourcePath", "stagedPath", "pdfPath", "workspace", "recoveryPath", "artifactPath", "fullOutputPath"]);
1051
+ function sanitizeArtifactMetadata(value, depth = 0) {
1052
+ if (depth > 20) return "[depth limit]";
1053
+ if (Array.isArray(value)) return value.map((item) => sanitizeArtifactMetadata(item, depth + 1));
1054
+ if (!value || typeof value !== "object") return typeof value === "string" && value.length > 100_000 ? `${value.slice(0, 100_000)}…` : value;
1055
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !PRIVATE_ARTIFACT_KEYS.has(key)).map(([key, item]) => [key, sanitizeArtifactMetadata(item, depth + 1)]));
1056
+ }
1057
+
1058
+ function artifactSessionIdentity(tab) {
1059
+ return normalizedRestoreString(tab?.lastState?.sessionId || tabRestorableSessionFile(tab), 4096) || null;
1060
+ }
1061
+
1062
+ function publicDocumentArtifact(record) {
1063
+ const tabQuery = `tab=${encodeURIComponent(record.tabId)}`;
1064
+ const base = `/api/artifacts/${encodeURIComponent(record.token)}`;
1065
+ return {
1066
+ schema: "pi.artifact/v1",
1067
+ kind: "document",
1068
+ id: record.id,
1069
+ revisionId: record.revisionId,
1070
+ title: record.title,
1071
+ mimeType: record.mimeType,
1072
+ pageCount: record.pageCount,
1073
+ expiresAt: new Date(record.expiresAt).toISOString(),
1074
+ manifestUrl: `${base}/manifest?${tabQuery}`,
1075
+ downloadUrl: record.downloadPath ? `${base}/download?${tabQuery}` : undefined,
1076
+ };
1077
+ }
1078
+
1079
+ function registerDocumentArtifact(tab, artifact) {
1080
+ if (!artifact || artifact.schema !== "pi.artifact/v1" || artifact.kind !== "document" || typeof artifact.id !== "string" || !artifact.id.trim()) throw new Error("invalid pi.artifact/v1 document envelope");
1081
+ pruneDocumentArtifactTokens();
1082
+ const sessionIdentity = artifactSessionIdentity(tab), existing = [...documentArtifactTokens.values()].find((item) => item.tabId === tab.id && item.sessionIdentity === sessionIdentity && item.id === artifact.id && item.revisionId === (artifact.revisionId || undefined));
1083
+ if (existing) return publicDocumentArtifact(existing);
1084
+ const manifestFile = documentArtifactPath(artifact.manifestPath);
1085
+ if (manifestFile.size > DOCUMENT_ARTIFACT_MANIFEST_LIMIT_BYTES) throw new Error("artifact manifest is too large");
1086
+ let manifest;
1087
+ try { manifest = JSON.parse(readFileSync(manifestFile.path, "utf8")); } catch { throw new Error("artifact manifest is malformed"); }
1088
+ const declared = manifest?.artifact;
1089
+ if (declared?.schema !== "pi.artifact/v1" || declared?.kind !== "document" || declared?.id !== artifact.id || (declared?.revisionId || undefined) !== (artifact.revisionId || undefined)) throw new Error("artifact manifest identity mismatch");
1090
+ const downloadPath = artifact.downloadPath ? documentArtifactPath(artifact.downloadPath).path : undefined;
1091
+ const rawPages = Array.isArray(manifest.pages) ? manifest.pages : [];
1092
+ if (rawPages.length > DOCUMENT_ARTIFACT_PAGE_LIMIT) throw new Error("artifact page count exceeds the registry limit");
1093
+ const pages = rawPages.map((page, index) => {
1094
+ const pageNum = Number(page?.pageNum);
1095
+ if (!Number.isInteger(pageNum) || pageNum < 1) throw new Error(`artifact page ${index + 1} is invalid`);
1096
+ const image = documentArtifactPath(page.outputPath);
1097
+ if (MIME_TYPES.get(path.extname(image.path).toLowerCase()) !== "image/png") throw new Error(`artifact page ${pageNum} is not PNG`);
1098
+ return { pageNum, width: Number(page.width) || undefined, height: Number(page.height) || undefined, bytes: image.size, path: image.path };
1099
+ });
1100
+ const declaredExpiry = Date.parse(String(artifact.expiresAt || declared?.expiresAt || "")), now = Date.now();
1101
+ if (!Number.isFinite(declaredExpiry) || declaredExpiry <= now) throw new Error("artifact is expired");
1102
+ const token = randomUUID(), expiresAt = Math.min(declaredExpiry, now + NATIVE_DOWNLOAD_TOKEN_TTL_MS);
1103
+ const record = {
1104
+ token,
1105
+ tabId: tab.id,
1106
+ sessionIdentity,
1107
+ id: artifact.id,
1108
+ revisionId: artifact.revisionId || undefined,
1109
+ title: safeDownloadFileName(artifact.title || declared?.title || "document.docx", "document.docx"),
1110
+ mimeType: String(artifact.mimeType || declared?.mimeType || "application/octet-stream"),
1111
+ pageCount: Number(artifact.pageCount ?? declared?.pageCount ?? pages.length) || pages.length,
1112
+ manifest: {
1113
+ sourceSha256: typeof manifest.sourceSha256 === "string" ? manifest.sourceSha256 : undefined,
1114
+ renderer: manifest.renderer && typeof manifest.renderer === "object" ? sanitizeArtifactMetadata(manifest.renderer) : undefined,
1115
+ warnings: Array.isArray(manifest.warnings) ? sanitizeArtifactMetadata(manifest.warnings.slice(0, 100)) : [],
1116
+ outline: Array.isArray(manifest.outline) ? sanitizeArtifactMetadata(manifest.outline.slice(0, 10_000)) : [],
1117
+ comments: Array.isArray(manifest.comments) ? sanitizeArtifactMetadata(manifest.comments.slice(0, 10_000)) : [],
1118
+ revisions: Array.isArray(manifest.revisions) ? sanitizeArtifactMetadata(manifest.revisions.slice(0, 10_000)) : [],
1119
+ diff: manifest.diff && typeof manifest.diff === "object" ? sanitizeArtifactMetadata(manifest.diff) : undefined,
1120
+ },
1121
+ manifestPath: manifestFile.path,
1122
+ downloadPath,
1123
+ pages,
1124
+ expiresAt,
1125
+ };
1126
+ documentArtifactTokens.set(token, record);
1127
+ return publicDocumentArtifact(record);
1128
+ }
1129
+
1130
+ function rewriteArtifactInResult(tab, result) {
1131
+ if (!result || typeof result !== "object") return result;
1132
+ const details = result.details;
1133
+ if (!details || typeof details !== "object" || details.artifact?.schema !== "pi.artifact/v1") return result;
1134
+ let artifact;
1135
+ try { artifact = registerDocumentArtifact(tab, details.artifact); }
1136
+ catch { artifact = { schema: "pi.artifact/v1", kind: "document", id: String(details.artifact?.id || "unavailable"), title: safeDownloadFileName(details.artifact?.title || "Document"), unavailable: true }; }
1137
+ return { ...result, details: { ...details, artifact } };
1138
+ }
1139
+
1140
+ function rewriteArtifactsForTab(tab, payload) {
1141
+ if (!payload || typeof payload !== "object") return payload;
1142
+ let next = payload;
1143
+ if (payload.result) next = { ...next, result: rewriteArtifactInResult(tab, payload.result) };
1144
+ if (payload.partialResult) next = { ...next, partialResult: rewriteArtifactInResult(tab, payload.partialResult) };
1145
+ if (payload.message?.role === "toolResult") next = { ...next, message: rewriteArtifactInResult(tab, payload.message) };
1146
+ if (Array.isArray(payload.data?.messages)) next = { ...next, data: { ...payload.data, messages: payload.data.messages.map((message) => message?.role === "toolResult" ? rewriteArtifactInResult(tab, message) : message) } };
1147
+ return next;
1148
+ }
1149
+
1150
+ function documentArtifactRecord(req, url, token) {
1151
+ pruneDocumentArtifactTokens();
1152
+ const record = documentArtifactTokens.get(token);
1153
+ if (!record) throw makeHttpError(404, "Artifact token expired or not found");
1154
+ const tab = getRequestedTab(req, url);
1155
+ if (tab.id !== record.tabId || (record.sessionIdentity && artifactSessionIdentity(tab) !== record.sessionIdentity)) throw makeHttpError(404, "Artifact token expired or not found");
1156
+ return record;
1157
+ }
1158
+
1159
+ async function sendDocumentArtifactFile(req, res, filePath, { contentType, fileName, inline = false } = {}) {
1160
+ const resolved = documentArtifactPath(filePath), range = String(req.headers.range || "").trim();
1161
+ let start = 0, end = resolved.size - 1, status = 200;
1162
+ if (range) {
1163
+ const match = range.match(/^bytes=(\d*)-(\d*)$/);
1164
+ if (!match) throw makeHttpError(416, "Unsupported artifact byte range");
1165
+ if (match[1]) start = Number(match[1]);
1166
+ if (match[2]) end = Number(match[2]);
1167
+ if (!match[1] && match[2]) { const suffix = Number(match[2]); start = Math.max(0, resolved.size - suffix); end = resolved.size - 1; }
1168
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || start >= resolved.size) throw makeHttpError(416, "Artifact byte range is unsatisfiable");
1169
+ end = Math.min(end, resolved.size - 1); status = 206;
1170
+ }
1171
+ const headers = {
1172
+ "content-type": contentType || MIME_TYPES.get(path.extname(resolved.path).toLowerCase()) || "application/octet-stream",
1173
+ "content-length": String(Math.max(0, end - start + 1)),
1174
+ "cache-control": "private, no-store",
1175
+ "x-content-type-options": "nosniff",
1176
+ "accept-ranges": "bytes",
1177
+ };
1178
+ if (status === 206) headers["content-range"] = `bytes ${start}-${end}/${resolved.size}`;
1179
+ if (fileName) headers["content-disposition"] = inline ? contentDispositionInline(fileName) : contentDispositionAttachment(fileName);
1180
+ res.writeHead(status, headers);
1181
+ await new Promise((resolve, reject) => { const stream = createReadStream(resolved.path, { start, end }); stream.on("error", reject); res.on("error", reject); res.on("close", resolve); stream.on("end", resolve); stream.pipe(res); });
1182
+ }
1183
+
1013
1184
  const ACTION_FEEDBACK_REACTIONS = new Set(["up", "down", "question"]);
1014
1185
 
1015
1186
  function trimFeedbackField(value, maxLength) {
@@ -1447,10 +1618,9 @@ async function installOptionalFeaturePackage(featureId) {
1447
1618
  });
1448
1619
  }
1449
1620
 
1450
- const npmCommand = process.env.PI_WEBUI_NPM_BIN || "npm";
1451
- const args = ["install", "--prefix", installRoot, packageName];
1452
- const command = formatCommandForDisplay(npmCommand, args);
1453
- 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, {
1454
1624
  cwd: installRoot,
1455
1625
  timeoutMs: 5 * 60 * 1000,
1456
1626
  maxOutputLength: 80000,
@@ -1614,6 +1784,65 @@ async function saveRemoteAuthPreference(enabled) {
1614
1784
  return persistedRemoteAuthEnabled;
1615
1785
  }
1616
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
+
1617
1846
  function gitWorkflowModelKey(model) {
1618
1847
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1619
1848
  }
@@ -2807,18 +3036,7 @@ function scheduleAppRunnerBroadcast(tab) {
2807
3036
 
2808
3037
  function terminateAppRunnerChild(run, signal = "SIGTERM") {
2809
3038
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2810
- try {
2811
- if (process.platform !== "win32" && run.pid) process.kill(-run.pid, signal);
2812
- else run.child.kill(signal);
2813
- return true;
2814
- } catch {
2815
- try {
2816
- run.child.kill(signal);
2817
- return true;
2818
- } catch {
2819
- return false;
2820
- }
2821
- }
3039
+ return terminateProcessTree(run.child, signal);
2822
3040
  }
2823
3041
 
2824
3042
  function appRunnerStdinWritable(run) {
@@ -2828,7 +3046,10 @@ function appRunnerStdinWritable(run) {
2828
3046
 
2829
3047
  function interruptAppRunnerChild(run) {
2830
3048
  if (!run?.child || run.child.exitCode !== null || run.child.signalCode !== null) return false;
2831
- 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") {
2832
3053
  try {
2833
3054
  run.child.stdin.write("\x03", "utf8");
2834
3055
  return true;
@@ -2954,14 +3175,15 @@ function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } =
2954
3175
  const run = tab?.appRunner;
2955
3176
  if (!run || run.status !== "running") return false;
2956
3177
  run.stopping = true;
2957
- 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}`);
2958
3180
  if (force) terminateAppRunnerChild(run, "SIGKILL");
2959
3181
  else interruptAppRunnerChild(run);
2960
3182
  if (!force) {
2961
3183
  clearTimeout(run.stopTimer);
2962
3184
  run.stopTimer = setTimeout(() => {
2963
3185
  if (run.status === "running") {
2964
- 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");
2965
3187
  terminateAppRunnerChild(run, "SIGKILL");
2966
3188
  scheduleAppRunnerBroadcast(tab);
2967
3189
  }
@@ -3219,38 +3441,24 @@ function normalizeCodexUsagePayload(rawPayload) {
3219
3441
  }
3220
3442
 
3221
3443
  async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3222
- const authStorage = AuthStorage.create();
3223
- const stored = authStorage.get(OPENAI_CODEX_PROVIDER_ID);
3224
- const storedExpires = numericValue(stored?.expires);
3225
- const shouldRefresh = stored?.type === "oauth" && (forceRefresh || storedExpires === undefined || Date.now() + CODEX_TOKEN_REFRESH_SKEW_MS >= storedExpires);
3226
- let accessToken;
3227
- let refreshed = false;
3228
-
3229
- if (shouldRefresh) {
3230
- try {
3231
- const refreshResult = await authStorage.refreshOAuthTokenWithLock(OPENAI_CODEX_PROVIDER_ID);
3232
- if (refreshResult?.apiKey) {
3233
- accessToken = refreshResult.apiKey;
3234
- refreshed = forceRefresh || refreshResult.newCredentials?.access !== stored?.access;
3235
- }
3236
- } catch (error) {
3237
- if (forceRefresh || !storedExpires || Date.now() >= storedExpires) {
3238
- throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
3239
- }
3240
- console.warn(`OpenAI Codex token refresh warning: ${sanitizeError(error)}`);
3241
- }
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.");
3242
3452
  }
3243
3453
 
3454
+ const accessToken = resolved.accessToken;
3244
3455
  if (!accessToken) {
3245
- accessToken = await authStorage.getApiKey(OPENAI_CODEX_PROVIDER_ID, { includeFallback: false });
3246
- }
3247
- if (!accessToken) {
3248
- const status = authStorage.getAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3456
+ const status = modelRuntime.getProviderAuthStatus(OPENAI_CODEX_PROVIDER_ID);
3249
3457
  if (status.configured) throw makeHttpError(401, "OpenAI Codex OAuth token is expired or unavailable. Run /login to refresh credentials.");
3250
3458
  throw makeHttpError(401, "OpenAI Codex OAuth is not configured. Run /login and choose ChatGPT Plus/Pro (Codex Subscription).");
3251
3459
  }
3252
3460
 
3253
- const latest = authStorage.get(OPENAI_CODEX_PROVIDER_ID) || stored || {};
3461
+ const latest = resolved.credential || {};
3254
3462
  const accountId = latest.accountId || codexAccountIdFromAccessToken(accessToken);
3255
3463
  if (!accountId) {
3256
3464
  throw makeHttpError(401, "OpenAI Codex account id is unavailable. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) again.");
@@ -3259,7 +3467,7 @@ async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
3259
3467
  return {
3260
3468
  accessToken,
3261
3469
  accountId,
3262
- refreshed,
3470
+ refreshed: resolved.refreshed,
3263
3471
  source: latest.type === "oauth" ? "stored-oauth" : "api-key",
3264
3472
  expiresAt: numericValue(latest.expires) ? new Date(numericValue(latest.expires)).toISOString() : undefined,
3265
3473
  };
@@ -3305,7 +3513,7 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
3305
3513
  try {
3306
3514
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3307
3515
  } catch (error) {
3308
- if (error?.openaiStatus === 401 && !credentials.refreshed) {
3516
+ if (error?.openaiStatus === 401) {
3309
3517
  credentials = await getOpenAICodexUsageCredentials({ forceRefresh: true });
3310
3518
  rawPayload = await fetchOpenAICodexUsagePayload(credentials);
3311
3519
  } else {
@@ -4472,15 +4680,30 @@ async function runGitMutationCommand(args, options = {}) {
4472
4680
  function gitMutationPayload(result) {
4473
4681
  const payload = gitWorkflowCommandPayload(result);
4474
4682
  if (!payload.ok) {
4683
+ let pathFailure = null;
4475
4684
  if (isGitLockFailure(result)) {
4476
4685
  payload.code = "REPO_BUSY";
4477
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);
4478
4690
  }
4479
- 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();
4480
4692
  }
4481
4693
  return payload;
4482
4694
  }
4483
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
+
4484
4707
  async function runGuardedGitMutation(args, options = {}) {
4485
4708
  try {
4486
4709
  return gitMutationPayload(await runGitMutationCommand(args, options));
@@ -4712,6 +4935,72 @@ async function readGitOperationSnapshot(cwd) {
4712
4935
  };
4713
4936
  }
4714
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
+
4715
5004
  async function gitOperationStageFile(cwd, body = {}) {
4716
5005
  const root = await getGitRoot(cwd);
4717
5006
  const kind = await detectGitOperationKind(root);
@@ -5948,8 +6237,7 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
5948
6237
  return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
5949
6238
  }
5950
6239
  case "/api/git-workflow/add":
5951
- await getGitRoot(cwd);
5952
- return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
6240
+ return gitAddAllPayload(cwd);
5953
6241
  case "/api/git-workflow/branch": {
5954
6242
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
5955
6243
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -6719,7 +7007,7 @@ function responseWithPendingThinking(tab, response) {
6719
7007
 
6720
7008
  function eventForTabClients(tab, event) {
6721
7009
  return {
6722
- ...responseWithPendingThinking(tab, event),
7010
+ ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
6723
7011
  tabId: tab.id,
6724
7012
  tabTitle: tab.title,
6725
7013
  tabActivity: tabActivitySnapshot(tab),
@@ -7812,35 +8100,59 @@ async function getUpdateStatus({ force = false } = {}) {
7812
8100
  checkedAt: new Date(now).toISOString(),
7813
8101
  updateAvailable,
7814
8102
  restartRequired: true,
7815
- command: "pi update",
7816
- allCommand: "pi update --all",
8103
+ command: piUpdateCommandText(),
8104
+ allCommand: piUpdateCommandText({ all: true, supportsAll: true }),
8105
+ allFallbackCommand: piUpdateCommandText({ all: true }),
7817
8106
  webuiDev: webuiDevServer,
7818
8107
  pi: piStatus,
7819
8108
  webui: webuiStatus,
7820
8109
  packages: {
7821
8110
  checked: false,
7822
- note: "Default update runs pi update for Pi only. Use update all to run pi update --all for Pi and configured packages."
8111
+ note: "Update all checks whether the selected Pi executable supports pi update --all. If not, it falls back to pi update --self followed by pi update --extensions."
7823
8112
  },
7824
8113
  };
7825
8114
  updateStatusCacheAt = now;
7826
8115
  return updateStatusCache;
7827
8116
  }
7828
8117
 
7829
- async function resolvePiUpdateCommand({ all = false } = {}) {
7830
- const updateArgs = all ? ["update", "--all"] : ["update"];
7831
- const label = all ? "Pi CLI and configured packages" : "Pi CLI";
7832
- if (options.piBinExplicit) {
7833
- const command = await resolvePiCommand(updateArgs);
7834
- return { ...command, label, timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
7835
- }
8118
+ async function piUpdateCommandSupportsAll(command) {
8119
+ const result = await runCommand(command.command, command.args || [], {
8120
+ cwd: process.cwd(),
8121
+ timeoutMs: 5000,
8122
+ maxOutputLength: 20_000,
8123
+ });
8124
+ if (result.exitCode !== 0 || result.timedOut || result.error) return false;
8125
+ return piUpdateHelpSupportsAll(`${result.stdout}\n${result.stderr}`);
8126
+ }
8127
+
8128
+ async function resolvePiUpdateCommands({ all = false } = {}) {
8129
+ let resolveCommand;
8130
+ let labelPrefix = "";
7836
8131
 
7837
- const pathPi = await runCommand(options.piBin, ["--version"], { timeoutMs: 3000, maxOutputLength: 4000 });
7838
- if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
7839
- return { label, command: options.piBin, args: updateArgs, displayCommand: formatCommandForDisplay(options.piBin, updateArgs), timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
8132
+ if (options.piBinExplicit) {
8133
+ resolveCommand = (args) => resolvePiCommand(args);
8134
+ } else {
8135
+ const pathPi = await runCommand(options.piBin, ["--version"], { timeoutMs: 3000, maxOutputLength: 4000 });
8136
+ if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
8137
+ resolveCommand = async (args) => ({
8138
+ command: options.piBin,
8139
+ args,
8140
+ displayCommand: formatCommandForDisplay(options.piBin, args),
8141
+ });
8142
+ } else {
8143
+ resolveCommand = (args) => resolvePiCommand(args);
8144
+ labelPrefix = "bundled ";
8145
+ }
7840
8146
  }
7841
8147
 
7842
- const fallback = await resolvePiCommand(updateArgs);
7843
- return { ...fallback, label: `bundled ${label}`, timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
8148
+ const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
8149
+ const steps = piUpdateCommandSteps({ all, supportsAll });
8150
+ return Promise.all(steps.map(async (step) => ({
8151
+ ...(await resolveCommand(step.args)),
8152
+ label: `${labelPrefix}${step.label}`,
8153
+ timeoutMs: PI_UPDATE_TIMEOUT_MS,
8154
+ maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
8155
+ })));
7844
8156
  }
7845
8157
 
7846
8158
  function packageNodeModulesPath(nodeModulesRoot, packageName) {
@@ -7918,17 +8230,23 @@ function packageInstallSpecs(packageNames) {
7918
8230
  return packageNames.map((packageName) => `${packageName}@latest`);
7919
8231
  }
7920
8232
 
7921
- function npmCommandName() {
7922
- 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
+ };
7923
8240
  }
7924
8241
 
7925
8242
  function npmPrefixUpdateTask(label, installRoot, packageNames) {
7926
8243
  if (!packageNames.length) return null;
7927
- const npmCommand = npmCommandName();
8244
+ const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)]);
7928
8245
  return {
7929
8246
  label,
7930
- command: npmCommand,
7931
- args: ["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)],
8247
+ command: npmCommand.command,
8248
+ args: npmCommand.args,
8249
+ displayCommand: npmCommand.displayCommand,
7932
8250
  cwd: installRoot,
7933
8251
  };
7934
8252
  }
@@ -7983,8 +8301,8 @@ async function projectPackageRootUpdateTasks() {
7983
8301
  }
7984
8302
 
7985
8303
  async function npmGlobalNodeModulesRoot() {
7986
- const npmCommand = npmCommandName();
7987
- 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 });
7988
8306
  if (result.exitCode !== 0 || result.timedOut || result.error) return null;
7989
8307
  return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
7990
8308
  }
@@ -7993,11 +8311,12 @@ async function npmGlobalPackageRootUpdateTask() {
7993
8311
  const nodeModulesRoot = await npmGlobalNodeModulesRoot();
7994
8312
  const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
7995
8313
  if (!packages.length) return null;
7996
- const npmCommand = npmCommandName();
8314
+ const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)]);
7997
8315
  return {
7998
8316
  label: "global npm package root",
7999
- command: npmCommand,
8000
- args: ["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)],
8317
+ command: npmCommand.command,
8318
+ args: npmCommand.args,
8319
+ displayCommand: npmCommand.displayCommand,
8001
8320
  cwd: nodeModulesRoot ? path.dirname(nodeModulesRoot) : process.cwd(),
8002
8321
  };
8003
8322
  }
@@ -8046,8 +8365,8 @@ function uniqueUpdateTasks(tasks) {
8046
8365
  }
8047
8366
 
8048
8367
  async function resolveUpdateTasks({ all = false } = {}) {
8049
- const piTask = await resolvePiUpdateCommand({ all });
8050
- if (!all) return uniqueUpdateTasks([piTask]);
8368
+ const piTasks = await resolvePiUpdateCommands({ all });
8369
+ if (!all) return uniqueUpdateTasks(piTasks);
8051
8370
 
8052
8371
  const [
8053
8372
  currentWebuiTask,
@@ -8066,7 +8385,7 @@ async function resolveUpdateTasks({ all = false } = {}) {
8066
8385
  ]);
8067
8386
 
8068
8387
  return uniqueUpdateTasks([
8069
- piTask,
8388
+ ...piTasks,
8070
8389
  currentWebuiTask,
8071
8390
  agentTask,
8072
8391
  optionalFeatureTask,
@@ -8328,7 +8647,7 @@ function fallbackRpcResponse(tab, command, error) {
8328
8647
 
8329
8648
  async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
8330
8649
  try {
8331
- return responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs));
8650
+ return rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
8332
8651
  } catch (error) {
8333
8652
  const message = sanitizeError(error);
8334
8653
  if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
@@ -8403,8 +8722,46 @@ async function sendWebuiHelperCommand(tab, action, payload = {}, timeoutMs = WEB
8403
8722
  }
8404
8723
  }
8405
8724
 
8406
- async function getToolConfigData(tab) {
8407
- 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);
8408
8765
  }
8409
8766
 
8410
8767
  let packageManagerModulePromise;
@@ -8597,88 +8954,56 @@ async function saveSkillFileData(tab, body = {}) {
8597
8954
  };
8598
8955
  }
8599
8956
 
8600
- function getResourcePatternForSkill(tab, skill) {
8601
- const info = skill.sourceInfo || {};
8602
- const baseDir = info.baseDir || (info.scope === "project" ? path.join(tab?.cwd || options.cwd, ".pi") : agentDir);
8603
- return path.relative(baseDir, skill.filePath);
8604
- }
8605
-
8606
8957
  async function setToolConfigData(tab, body) {
8607
- return sendWebuiHelperCommand(tab, "tools-set", {
8608
- enabledTools: Array.isArray(body.enabledTools) ? body.enabledTools : undefined,
8609
- disabledTools: Array.isArray(body.disabledTools) ? body.disabledTools : undefined,
8610
- });
8611
- }
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
+ }
8612
8968
 
8613
- async function getSkillConfigDataFromRuntime(tab) {
8614
- 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);
8615
8975
  }
8616
8976
 
8617
- function desiredSkillEnabledFromBody(skillName, body) {
8618
- if (Array.isArray(body.enabledSkills)) return body.enabledSkills.map(String).includes(skillName);
8619
- if (Array.isArray(body.disabledSkills)) return !body.disabledSkills.map(String).includes(skillName);
8620
- 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);
8621
8983
  }
8622
8984
 
8623
- function updatePatternListForResource(current, pattern, enabled) {
8624
- const updated = (current || []).filter((item) => {
8625
- const text = String(item || "");
8626
- const stripped = text.startsWith("!") || text.startsWith("+") || text.startsWith("-") ? text.slice(1) : text;
8627
- return stripped !== pattern;
8628
- });
8629
- updated.push(`${enabled ? "+" : "-"}${pattern}`);
8630
- return updated;
8631
- }
8632
-
8633
- function setSkillPathsForScope(settingsManager, scope, updated) {
8634
- if (scope === "project") settingsManager.setProjectSkillPaths(updated);
8635
- else settingsManager.setSkillPaths(updated);
8636
- }
8637
-
8638
- function toggleConfiguredSkill(tab, settingsManager, skill, enabled) {
8639
- const info = skill.sourceInfo || {};
8640
- const scope = info.scope === "project" ? "project" : "user";
8641
- if (info.origin === "package") {
8642
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8643
- const packages = [...(settings.packages || [])];
8644
- const packageIndex = packages.findIndex((item) => (typeof item === "string" ? item : item?.source) === info.source);
8645
- if (packageIndex < 0) return false;
8646
- let packageEntry = packages[packageIndex];
8647
- if (typeof packageEntry === "string") {
8648
- packageEntry = { source: packageEntry };
8649
- packages[packageIndex] = packageEntry;
8650
- }
8651
- const pattern = path.relative(info.baseDir || path.dirname(skill.filePath), skill.filePath);
8652
- packageEntry.skills = updatePatternListForResource(packageEntry.skills || [], pattern, enabled);
8653
- if (scope === "project") settingsManager.setProjectPackages(packages);
8654
- else settingsManager.setPackages(packages);
8655
- return true;
8656
- }
8657
-
8658
- const settings = scope === "project" ? settingsManager.getProjectSettings() : settingsManager.getGlobalSettings();
8659
- const pattern = getResourcePatternForSkill(tab, skill);
8660
- setSkillPathsForScope(settingsManager, scope, updatePatternListForResource(settings.skills || [], pattern, enabled));
8661
- return true;
8985
+ async function getSkillConfigDataFromRuntime(tab) {
8986
+ return sendWebuiHelperCommand(tab, "skills-state");
8662
8987
  }
8663
8988
 
8664
8989
  async function setSkillConfigData(tab, body) {
8665
- const { skills, settingsManager } = await resolveSkillResources(tab);
8666
- let configChanged = false;
8667
- for (const skill of skills) {
8668
- const desiredEnabled = desiredSkillEnabledFromBody(skill.name, body);
8669
- if (skill.configEnabled !== desiredEnabled && toggleConfiguredSkill(tab, settingsManager, skill, desiredEnabled)) configChanged = true;
8670
- }
8671
-
8672
- const runtimeOnly = skills.length === 0;
8673
- if (runtimeOnly) {
8674
- await sendWebuiHelperCommand(tab, "skills-set", {
8675
- enabledSkills: Array.isArray(body.enabledSkills) ? body.enabledSkills : undefined,
8676
- disabledSkills: Array.isArray(body.disabledSkills) ? body.disabledSkills : undefined,
8677
- });
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
+ };
8678
8999
  }
8679
9000
 
8680
- const activeTab = configChanged ? await restartTabRpc(tab, "skills-config") : tab;
8681
- 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);
8682
9007
  }
8683
9008
 
8684
9009
  function settingsManagerForTab(tab) {
@@ -9972,7 +10297,12 @@ async function switchTabSession(tab, sessionPath) {
9972
10297
  let authContextCache;
9973
10298
 
9974
10299
  function authContext() {
9975
- if (!authContextCache) authContextCache = createAuthContext();
10300
+ if (!authContextCache) {
10301
+ authContextCache = createAuthContext().catch((error) => {
10302
+ authContextCache = undefined;
10303
+ throw error;
10304
+ });
10305
+ }
9976
10306
  return authContextCache;
9977
10307
  }
9978
10308
 
@@ -10005,13 +10335,13 @@ async function deleteSessionData(tab, body) {
10005
10335
  };
10006
10336
  }
10007
10337
 
10008
- function getAuthProvidersData() {
10009
- return authProvidersPayload(authContext().modelRegistry);
10338
+ async function getAuthProvidersData() {
10339
+ return authProvidersPayload((await authContext()).modelRuntime);
10010
10340
  }
10011
10341
 
10012
- function logoutAuthProviderData(body) {
10342
+ async function logoutAuthProviderData(body) {
10013
10343
  if (body.confirmed !== true) throw makeHttpError(409, "Logout requires explicit confirmation (confirmed: true).");
10014
- return logoutStoredProvider(authContext().modelRegistry, body.provider || body.providerId);
10344
+ return logoutStoredProvider((await authContext()).modelRuntime, body.provider || body.providerId);
10015
10345
  }
10016
10346
 
10017
10347
  async function navigateSessionTree(tab, body) {
@@ -10087,14 +10417,12 @@ async function handleNativeExportCommand(tab, args, req) {
10087
10417
  fileName: `${nativeExportBaseName(tab, state)}.html`,
10088
10418
  contentType: MIME_TYPES.get(".html"),
10089
10419
  });
10090
- return respondNative("export", {
10091
- status: "succeeded",
10092
- level: "info",
10093
- 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,
10094
10423
  download,
10095
- result: response.data,
10096
- refresh: ["state"],
10097
- });
10424
+ responseData: response.data,
10425
+ }));
10098
10426
  }
10099
10427
 
10100
10428
  if (!isLocalRequest(req)) {
@@ -10914,6 +11242,24 @@ const server = createServer(async (req, res) => {
10914
11242
  return;
10915
11243
  }
10916
11244
 
11245
+ const artifactRoute = url.pathname.match(/^\/api\/artifacts\/([^/]+)\/(manifest|download|page\/(\d+))$/);
11246
+ if (artifactRoute && req.method === "GET") {
11247
+ const token = decodeURIComponent(artifactRoute[1]), record = documentArtifactRecord(req, url, token), tabQuery = `tab=${encodeURIComponent(record.tabId)}`;
11248
+ if (artifactRoute[2] === "manifest") {
11249
+ sendJson(res, 200, { ok: true, data: { artifact: publicDocumentArtifact(record), ...record.manifest, pages: record.pages.map(({ path: _path, ...page }) => ({ ...page, imageUrl: `/api/artifacts/${encodeURIComponent(token)}/page/${page.pageNum}?${tabQuery}` })) } }, { "cache-control": "private, no-store" });
11250
+ return;
11251
+ }
11252
+ if (artifactRoute[2] === "download") {
11253
+ if (!record.downloadPath) throw makeHttpError(404, "Artifact download is unavailable");
11254
+ await sendDocumentArtifactFile(req, res, record.downloadPath, { contentType: record.mimeType, fileName: record.title });
11255
+ return;
11256
+ }
11257
+ const pageNum = Number(artifactRoute[3]), page = record.pages.find((item) => item.pageNum === pageNum);
11258
+ if (!page) throw makeHttpError(404, "Artifact page is unavailable");
11259
+ await sendDocumentArtifactFile(req, res, page.path, { contentType: "image/png", fileName: `page-${pageNum}.png`, inline: true });
11260
+ return;
11261
+ }
11262
+
10917
11263
  if (url.pathname.startsWith("/api/native-download/") && req.method === "GET") {
10918
11264
  await sendNativeDownload(res, decodeURIComponent(url.pathname.slice("/api/native-download/".length)), {
10919
11265
  inline: url.searchParams.get("disposition") === "inline",
@@ -11277,14 +11623,14 @@ const server = createServer(async (req, res) => {
11277
11623
  }
11278
11624
 
11279
11625
  if (url.pathname === "/api/auth-providers" && req.method === "GET") {
11280
- sendJson(res, 200, { ok: true, data: getAuthProvidersData() });
11626
+ sendJson(res, 200, { ok: true, data: await getAuthProvidersData() });
11281
11627
  return;
11282
11628
  }
11283
11629
 
11284
11630
  if (url.pathname === "/api/auth-logout" && req.method === "POST") {
11285
11631
  requireLocalhostRoute(req, url.pathname);
11286
11632
  const body = await readJsonBody(req);
11287
- sendJson(res, 200, { ok: true, data: logoutAuthProviderData(body) });
11633
+ sendJson(res, 200, { ok: true, data: await logoutAuthProviderData(body) });
11288
11634
  return;
11289
11635
  }
11290
11636
 
@@ -11370,7 +11716,7 @@ const server = createServer(async (req, res) => {
11370
11716
 
11371
11717
  if (url.pathname === "/api/tools" && req.method === "GET") {
11372
11718
  const tab = getRequestedTab(req, url);
11373
- sendJson(res, 200, { ok: true, data: await getToolConfigData(tab) });
11719
+ sendJson(res, 200, { ok: true, data: await getToolConfigData(tab, url.searchParams.get("scope")) });
11374
11720
  return;
11375
11721
  }
11376
11722
 
@@ -11384,7 +11730,7 @@ const server = createServer(async (req, res) => {
11384
11730
 
11385
11731
  if (url.pathname === "/api/skills" && req.method === "GET") {
11386
11732
  const tab = getRequestedTab(req, url);
11387
- sendJson(res, 200, { ok: true, data: await getMergedSkillConfigData(tab) });
11733
+ sendJson(res, 200, { ok: true, data: await getSkillConfigData(tab, url.searchParams.get("scope")) });
11388
11734
  return;
11389
11735
  }
11390
11736
 
@@ -11411,6 +11757,20 @@ const server = createServer(async (req, res) => {
11411
11757
  return;
11412
11758
  }
11413
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
+
11414
11774
  if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11415
11775
  const tab = getRequestedTab(req, url);
11416
11776
  sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
@@ -11651,6 +12011,7 @@ const server = createServer(async (req, res) => {
11651
12011
  "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11652
12012
  "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11653
12013
  "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
12014
+ "/api/git-operation/resolve-with-agent": (_cwd, _body, tab) => openGitConflictResolutionAgentTab(tab),
11654
12015
  "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11655
12016
  "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11656
12017
  "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
@@ -11669,7 +12030,7 @@ const server = createServer(async (req, res) => {
11669
12030
  const tab = getRequestedTab(req, url, body);
11670
12031
  ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11671
12032
  try {
11672
- const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
12033
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body, tab);
11673
12034
  sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11674
12035
  } catch (error) {
11675
12036
  gitActionError(error);