@firstpick/pi-package-webui 0.10.1 → 0.10.3
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/DEVELOPMENT.md +41 -19
- package/README.md +13 -3
- package/TECHNICAL.md +16 -2
- package/bin/pi-webui.mjs +257 -76
- package/index.ts +1 -256
- package/lib/append-system-selection.mjs +311 -0
- package/lib/git-workflow-preferences.mjs +6 -0
- package/lib/trust-boundaries.mjs +37 -0
- package/package.json +1 -1
- package/public/app.js +162 -7
- package/public/index.html +5 -2
- package/public/service-worker.js +1 -1
- package/tests/append-system-http.test.mjs +622 -0
- package/tests/append-system-selection.test.mjs +259 -0
- package/tests/append-system-selector-static.test.mjs +95 -0
- package/tests/boot-failure-diagnostics.test.mjs +2 -2
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +4 -0
- package/tests/common-options-submenus-markup-static.test.mjs +2 -1
- package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
- package/tests/control-visibility-static.test.mjs +2 -2
- package/tests/controls-layout-static.test.mjs +2 -2
- package/tests/events-tree-context-menu-static.test.mjs +2 -2
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +1 -1
- package/tests/file-viewer-image-static.test.mjs +2 -2
- package/tests/guided-git-activation-static.test.mjs +10 -3
- package/tests/guided-git-fallback-runtime.test.mjs +46 -21
- package/tests/guided-git-fallback-ui-static.test.mjs +3 -3
- package/tests/intercom-conversation-viewer-static.test.mjs +2 -2
- package/tests/main-output-loading-static.test.mjs +2 -2
- package/tests/middle-button-drag-scroll-static.test.mjs +2 -2
- package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
- package/tests/mobile-foundation-static.test.mjs +2 -2
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +3 -2
- package/tests/native-parity-harness.test.mjs +7 -0
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/optional-feature-prompt-impact-static.test.mjs +2 -2
- package/tests/persistent-ui-layout-static.test.mjs +2 -2
- package/tests/prompt-input-vertical-scroll-static.test.mjs +2 -2
- package/tests/questionnaire-dialog.test.mjs +2 -2
- package/tests/resource-tui-extension.test.mjs +4 -18
- package/tests/session-sampling-ui-static.test.mjs +2 -2
- package/tests/side-panel-section-height-removal-static.test.mjs +2 -2
- package/tests/subagent-observability-static.test.mjs +2 -2
- package/tests/syntax-highlighting-static.test.mjs +2 -2
- package/tests/terminal-tab-prompt-tooltip-static.test.mjs +147 -0
- package/tests/terminal-tab-workspace-static.test.mjs +1 -1
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/windows-drive-cwd-picker-static.test.mjs +2 -2
- package/lib/tui-model-profile-selector.mjs +0 -183
- package/lib/tui-resource-selector.mjs +0 -173
- package/tests/tui-model-profile-selector.test.mjs +0 -102
- package/tests/tui-resource-selector.test.mjs +0 -74
package/index.ts
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import type { Readable } from "node:stream";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import {
|
|
6
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { delay, takeValue, tokenizeArgs } from "@firstpick/pi-utils";
|
|
8
8
|
import { detachChildProcess as releaseStartedChild, isProcessRunning, terminateChildProcess as terminateFailedChild } from "@firstpick/pi-utils/process";
|
|
9
9
|
import { fetchJsonWithTimeout as fetchJsonWithTimeoutBase } from "@firstpick/pi-utils/http";
|
|
@@ -12,21 +12,9 @@ import { createRestoreFile } from "./lib/update/supervisor.mjs";
|
|
|
12
12
|
import {
|
|
13
13
|
gitWorkflowPreferencesSummary,
|
|
14
14
|
readGitWorkflowPreferences,
|
|
15
|
-
readWebuiSettings,
|
|
16
15
|
supportedGitWorkflowThinkingLevels,
|
|
17
|
-
updateWebuiSettings,
|
|
18
16
|
writeGitWorkflowPreferences,
|
|
19
17
|
} from "./lib/git-workflow-preferences.mjs";
|
|
20
|
-
import {
|
|
21
|
-
branchResourceDirective,
|
|
22
|
-
exactModelProfile,
|
|
23
|
-
normalizeResourceNameList,
|
|
24
|
-
preserveUnavailableResourceNames,
|
|
25
|
-
resolveResourceSelection,
|
|
26
|
-
setExactModelProfile,
|
|
27
|
-
} from "./lib/resource-selection.mjs";
|
|
28
|
-
import { selectTuiModelProfile } from "./lib/tui-model-profile-selector.mjs";
|
|
29
|
-
import { selectTuiResources } from "./lib/tui-resource-selector.mjs";
|
|
30
18
|
|
|
31
19
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
32
20
|
const packageRoot = __dirname;
|
|
@@ -881,250 +869,7 @@ async function runGitWorkflowSetup(ctx: ExtensionCommandContext): Promise<void>
|
|
|
881
869
|
}
|
|
882
870
|
}
|
|
883
871
|
|
|
884
|
-
function lastResourceBranchConfig(ctx: ExtensionCommandContext, customType: string): any {
|
|
885
|
-
let found: any;
|
|
886
|
-
for (const entry of ctx.sessionManager.getBranch()) {
|
|
887
|
-
if ((entry as any)?.type === "custom" && (entry as any).customType === customType) found = (entry as any).data;
|
|
888
|
-
}
|
|
889
|
-
return found;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
function registerTuiResourceController(pi: ExtensionAPI): void {
|
|
893
|
-
let runtimeToolBaseline: string[] | undefined;
|
|
894
|
-
let enabledTools = new Set<string>();
|
|
895
|
-
let enabledSkills: Set<string> | null = null;
|
|
896
|
-
let legacyDisabledSkills = new Set<string>();
|
|
897
|
-
let toolsPinned = false;
|
|
898
|
-
let skillsPinned = false;
|
|
899
|
-
let tuiActive = false;
|
|
900
|
-
let generation = 0;
|
|
901
|
-
|
|
902
|
-
const modelKey = (model: any): string => model?.provider && model?.id ? `${model.provider}\0${model.id}` : "";
|
|
903
|
-
const runtimeTools = (): string[] => runtimeToolBaseline ??= normalizeResourceNameList(pi.getActiveTools()) || [];
|
|
904
|
-
const toolNames = (): string[] => pi.getAllTools().map((tool: any) => tool.name);
|
|
905
|
-
const skills = (ctx: ExtensionCommandContext): any[] => {
|
|
906
|
-
const options = (ctx as any).getSystemPromptOptions?.();
|
|
907
|
-
return Array.isArray(options?.skills) ? options.skills : [];
|
|
908
|
-
};
|
|
909
|
-
const isSkillEnabled = (name: string): boolean => enabledSkills instanceof Set ? enabledSkills.has(name) : !legacyDisabledSkills.has(name);
|
|
910
|
-
|
|
911
|
-
function applyResolvedState(ctx: ExtensionCommandContext, defaults: any, model: any): void {
|
|
912
|
-
const toolDirective = branchResourceDirective(lastResourceBranchConfig(ctx, "webui-tools-config"), "tools");
|
|
913
|
-
toolsPinned = toolDirective.pinned;
|
|
914
|
-
const baseline = runtimeTools();
|
|
915
|
-
const resolvedTools = toolDirective.pinned
|
|
916
|
-
? { names: toolDirective.names || [], source: "session" }
|
|
917
|
-
: resolveResourceSelection(defaults, "tools", model?.provider, model?.id, baseline);
|
|
918
|
-
enabledTools = new Set(resolvedTools.names || baseline);
|
|
919
|
-
const existingTools = new Set(toolNames());
|
|
920
|
-
pi.setActiveTools([...enabledTools].filter((name) => existingTools.has(name)));
|
|
921
|
-
|
|
922
|
-
const skillDirective = branchResourceDirective(lastResourceBranchConfig(ctx, "webui-skills-config"), "skills");
|
|
923
|
-
skillsPinned = skillDirective.pinned;
|
|
924
|
-
legacyDisabledSkills = new Set();
|
|
925
|
-
if (skillDirective.pinned && skillDirective.legacyDisabledNames !== null) {
|
|
926
|
-
enabledSkills = null;
|
|
927
|
-
legacyDisabledSkills = new Set(skillDirective.legacyDisabledNames);
|
|
928
|
-
} else {
|
|
929
|
-
const resolvedSkills = skillDirective.pinned
|
|
930
|
-
? { names: skillDirective.names || [], source: "session" }
|
|
931
|
-
: resolveResourceSelection(defaults, "skills", model?.provider, model?.id, null);
|
|
932
|
-
enabledSkills = resolvedSkills.names === null ? null : new Set(resolvedSkills.names);
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
async function recompute(ctx: ExtensionCommandContext, requestedModel: any = ctx.model): Promise<boolean> {
|
|
937
|
-
if (ctx.mode !== "tui") return false;
|
|
938
|
-
const requestedKey = modelKey(requestedModel);
|
|
939
|
-
const currentGeneration = ++generation;
|
|
940
|
-
let defaults;
|
|
941
|
-
try {
|
|
942
|
-
defaults = (await readWebuiSettings()).resourceDefaults;
|
|
943
|
-
} catch (error) {
|
|
944
|
-
ctx.ui.notify(`Resource defaults could not be read: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
945
|
-
return false;
|
|
946
|
-
}
|
|
947
|
-
if (currentGeneration !== generation || modelKey(ctx.model) !== requestedKey) return false;
|
|
948
|
-
applyResolvedState(ctx, defaults, requestedModel);
|
|
949
|
-
return true;
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
function availableModels(ctx: ExtensionCommandContext): any[] {
|
|
953
|
-
return ctx.modelRegistry.getAvailable()
|
|
954
|
-
.filter((model: any) => model?.provider && model?.id)
|
|
955
|
-
.sort((left: any, right: any) => `${left.provider}/${left.id}`.localeCompare(`${right.provider}/${right.id}`));
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
async function runSelector(resourceType: "tools" | "skills", ctx: ExtensionCommandContext): Promise<void> {
|
|
959
|
-
if (ctx.mode !== "tui") {
|
|
960
|
-
ctx.ui.notify(`/${resourceType} is available in interactive TUI mode only.`, "warning");
|
|
961
|
-
return;
|
|
962
|
-
}
|
|
963
|
-
const resourceLabel = resourceType === "tools" ? "Tools" : "Skills";
|
|
964
|
-
const scope = await ctx.ui.select(`${resourceLabel} setup`, ["Session only", "Global default", "Model default"]);
|
|
965
|
-
if (!scope) return;
|
|
966
|
-
const settings = await readWebuiSettings();
|
|
967
|
-
const visibleNames = resourceType === "tools" ? toolNames() : skills(ctx).map((skill: any) => skill.name);
|
|
968
|
-
const selectionKey = resourceType === "tools" ? "enabledTools" : "enabledSkills";
|
|
969
|
-
let previousNames: string[] | null = null;
|
|
970
|
-
let provider = "";
|
|
971
|
-
let modelId = "";
|
|
972
|
-
|
|
973
|
-
if (scope === "Session only") {
|
|
974
|
-
const action = await ctx.ui.select(`${resourceLabel} for this session`, ["Edit selection", "Use inherited defaults"]);
|
|
975
|
-
if (!action) return;
|
|
976
|
-
if (action === "Use inherited defaults") {
|
|
977
|
-
pi.appendEntry(resourceType === "tools" ? "webui-tools-config" : "webui-skills-config", { version: 2, mode: "inherit" });
|
|
978
|
-
await recompute(ctx);
|
|
979
|
-
ctx.ui.notify(`${resourceLabel} now use inherited defaults.`, "info");
|
|
980
|
-
return;
|
|
981
|
-
}
|
|
982
|
-
previousNames = resourceType === "tools"
|
|
983
|
-
? [...enabledTools]
|
|
984
|
-
: enabledSkills instanceof Set ? [...enabledSkills] : visibleNames.filter((name) => !legacyDisabledSkills.has(name));
|
|
985
|
-
} else if (scope === "Global default") {
|
|
986
|
-
const action = await ctx.ui.select(`Global ${resourceLabel.toLowerCase()} default`, ["Edit selection", "Use Pi runtime default"]);
|
|
987
|
-
if (!action) return;
|
|
988
|
-
if (action === "Use Pi runtime default") {
|
|
989
|
-
await updateWebuiSettings(() => ({ resourceDefaults: { [resourceType]: { [selectionKey]: null } } }));
|
|
990
|
-
await recompute(ctx);
|
|
991
|
-
ctx.ui.notify(`Global ${resourceLabel.toLowerCase()} default now inherits Pi runtime behavior.`, "info");
|
|
992
|
-
return;
|
|
993
|
-
}
|
|
994
|
-
previousNames = settings.resourceDefaults?.[resourceType]?.[selectionKey];
|
|
995
|
-
if (previousNames === null) previousNames = resolveResourceSelection(settings.resourceDefaults, resourceType, "", "", resourceType === "tools" ? runtimeTools() : null).names;
|
|
996
|
-
} else {
|
|
997
|
-
const models = availableModels(ctx);
|
|
998
|
-
if (!models.length) {
|
|
999
|
-
ctx.ui.notify("No authenticated Pi models are available.", "warning");
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
const configuredModelKeys = (Array.isArray(settings.resourceDefaults?.modelProfiles)
|
|
1003
|
-
? settings.resourceDefaults.modelProfiles
|
|
1004
|
-
: [])
|
|
1005
|
-
.filter((profile: any) => Array.isArray(profile?.[resourceType]?.[selectionKey]))
|
|
1006
|
-
.map((profile: any) => `${profile.provider}\0${profile.modelId}`);
|
|
1007
|
-
const model = await selectTuiModelProfile(ctx, {
|
|
1008
|
-
title: `${resourceLabel} Model Profile`,
|
|
1009
|
-
subtitle: "Choose a profile to edit. This does not switch the active model.",
|
|
1010
|
-
models,
|
|
1011
|
-
activeModelKey: modelKey(ctx.model),
|
|
1012
|
-
configuredModelKeys,
|
|
1013
|
-
});
|
|
1014
|
-
if (!model) return;
|
|
1015
|
-
provider = model.provider;
|
|
1016
|
-
modelId = model.id;
|
|
1017
|
-
const action = await ctx.ui.select(`${resourceLabel} for ${provider}/${modelId}`, ["Edit selection", "Use inherited defaults"]);
|
|
1018
|
-
if (!action) return;
|
|
1019
|
-
const profile = exactModelProfile(settings.resourceDefaults, provider, modelId);
|
|
1020
|
-
previousNames = profile?.[resourceType]?.[selectionKey] ?? null;
|
|
1021
|
-
if (action === "Use inherited defaults") {
|
|
1022
|
-
await updateWebuiSettings((current: any) => ({
|
|
1023
|
-
resourceDefaults: {
|
|
1024
|
-
modelProfiles: setExactModelProfile(current.resourceDefaults, provider, modelId, resourceType, null),
|
|
1025
|
-
},
|
|
1026
|
-
}));
|
|
1027
|
-
await recompute(ctx);
|
|
1028
|
-
ctx.ui.notify(`${resourceLabel} for ${provider}/${modelId} now use inherited defaults.`, "info");
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
if (previousNames === null) {
|
|
1032
|
-
previousNames = resolveResourceSelection(settings.resourceDefaults, resourceType, provider, modelId, resourceType === "tools" ? runtimeTools() : null).names;
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
const selectionTarget = scope === "Model default" ? `${provider}/${modelId} model profile` : scope;
|
|
1037
|
-
const selected = await selectTuiResources(ctx, {
|
|
1038
|
-
title: `${resourceLabel} Configuration`,
|
|
1039
|
-
subtitle: `${selectionTarget}. Changes apply only after Ctrl+S.`,
|
|
1040
|
-
resources: visibleNames,
|
|
1041
|
-
enabledResourceNames: previousNames || [],
|
|
1042
|
-
});
|
|
1043
|
-
if (!selected) return;
|
|
1044
|
-
if (scope === "Session only") {
|
|
1045
|
-
const preserved = preserveUnavailableResourceNames(previousNames, visibleNames, selected);
|
|
1046
|
-
pi.appendEntry(resourceType === "tools" ? "webui-tools-config" : "webui-skills-config", {
|
|
1047
|
-
version: 2,
|
|
1048
|
-
mode: "explicit",
|
|
1049
|
-
[selectionKey]: preserved,
|
|
1050
|
-
});
|
|
1051
|
-
} else if (scope === "Global default") {
|
|
1052
|
-
await updateWebuiSettings((current: any) => ({
|
|
1053
|
-
resourceDefaults: {
|
|
1054
|
-
[resourceType]: {
|
|
1055
|
-
[selectionKey]: preserveUnavailableResourceNames(current.resourceDefaults?.[resourceType]?.[selectionKey], visibleNames, selected),
|
|
1056
|
-
},
|
|
1057
|
-
},
|
|
1058
|
-
}));
|
|
1059
|
-
} else {
|
|
1060
|
-
await updateWebuiSettings((current: any) => {
|
|
1061
|
-
const currentNames = exactModelProfile(current.resourceDefaults, provider, modelId)?.[resourceType]?.[selectionKey];
|
|
1062
|
-
const preserved = preserveUnavailableResourceNames(currentNames, visibleNames, selected);
|
|
1063
|
-
return {
|
|
1064
|
-
resourceDefaults: {
|
|
1065
|
-
modelProfiles: setExactModelProfile(current.resourceDefaults, provider, modelId, resourceType, preserved),
|
|
1066
|
-
},
|
|
1067
|
-
};
|
|
1068
|
-
});
|
|
1069
|
-
}
|
|
1070
|
-
await recompute(ctx);
|
|
1071
|
-
ctx.ui.notify(`${resourceLabel} ${selectionTarget.toLowerCase()} saved.`, "info");
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
pi.registerCommand("tools", {
|
|
1075
|
-
description: "Choose session, global, or exact-model tools",
|
|
1076
|
-
handler: async (_args, ctx) => runSelector("tools", ctx),
|
|
1077
|
-
});
|
|
1078
|
-
pi.registerCommand("skills", {
|
|
1079
|
-
description: "Choose session, global, or exact-model skills",
|
|
1080
|
-
handler: async (_args, ctx) => runSelector("skills", ctx),
|
|
1081
|
-
});
|
|
1082
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
1083
|
-
tuiActive = ctx.mode === "tui";
|
|
1084
|
-
if (tuiActive) {
|
|
1085
|
-
if (runtimeToolBaseline === undefined) enabledTools = new Set(runtimeTools());
|
|
1086
|
-
await recompute(ctx);
|
|
1087
|
-
}
|
|
1088
|
-
});
|
|
1089
|
-
pi.on("session_tree", async (_event, ctx) => {
|
|
1090
|
-
tuiActive = ctx.mode === "tui";
|
|
1091
|
-
if (tuiActive) await recompute(ctx);
|
|
1092
|
-
});
|
|
1093
|
-
pi.on("model_select", async (event, ctx) => {
|
|
1094
|
-
if (ctx.mode === "tui") await recompute(ctx, event.model);
|
|
1095
|
-
});
|
|
1096
|
-
pi.on("session_shutdown", () => {
|
|
1097
|
-
tuiActive = false;
|
|
1098
|
-
generation += 1;
|
|
1099
|
-
});
|
|
1100
|
-
pi.on("input", async (event, ctx) => {
|
|
1101
|
-
if (!tuiActive || ctx.mode !== "tui") return { action: "continue" };
|
|
1102
|
-
const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
|
|
1103
|
-
if (!match || isSkillEnabled(match[1])) return { action: "continue" };
|
|
1104
|
-
ctx.ui.notify(`Skill /skill:${match[1]} is disabled by /skills.`, "warning");
|
|
1105
|
-
return { action: "handled" };
|
|
1106
|
-
});
|
|
1107
|
-
pi.on("before_agent_start", async (event) => {
|
|
1108
|
-
if (!tuiActive || (enabledSkills === null && legacyDisabledSkills.size === 0)) return undefined;
|
|
1109
|
-
const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
|
|
1110
|
-
const disabledNames = allSkills.filter((skill: any) => !isSkillEnabled(skill.name)).map((skill: any) => skill.name);
|
|
1111
|
-
const filtered = allSkills.filter((skill: any) => isSkillEnabled(skill.name) && skill.disableModelInvocation !== true);
|
|
1112
|
-
if (filtered.length === allSkills.length) return undefined;
|
|
1113
|
-
let nextPrompt = event.systemPrompt;
|
|
1114
|
-
const nextSection = formatSkillsForPrompt(filtered);
|
|
1115
|
-
if (nextPrompt.includes("<available_skills>")) {
|
|
1116
|
-
nextPrompt = nextPrompt.replace(/\n?The following skills provide[\s\S]*?<\/available_skills>\n?/m, nextSection ? `\n${nextSection}\n` : "\n");
|
|
1117
|
-
}
|
|
1118
|
-
for (const name of disabledNames) {
|
|
1119
|
-
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1120
|
-
nextPrompt = nextPrompt.replace(new RegExp(`\\n? <skill>\\n <name>${escaped}<\\/name>[\\s\\S]*? <\\/skill>`, "g"), "");
|
|
1121
|
-
}
|
|
1122
|
-
return { systemPrompt: nextPrompt };
|
|
1123
|
-
});
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
872
|
export default function (pi: ExtensionAPI) {
|
|
1127
|
-
registerTuiResourceController(pi);
|
|
1128
873
|
const subagentGate = registerSubagentGate(pi);
|
|
1129
874
|
pi.on("session_shutdown", () => subagentGate.dispose());
|
|
1130
875
|
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { readdir, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export const APPEND_SYSTEM_FILE_NAME = "APPEND_SYSTEM.md";
|
|
6
|
+
export const APPEND_SYSTEM_DISCOVERY_LIMITS = Object.freeze({
|
|
7
|
+
maxDepth: 10,
|
|
8
|
+
maxVisitedDirectories: 2_048,
|
|
9
|
+
maxCandidates: 256,
|
|
10
|
+
maxDiagnostics: 64,
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export const APPEND_SYSTEM_DIAGNOSTIC_MESSAGES = Object.freeze({
|
|
14
|
+
"candidate-limit": "Additional APPEND_SYSTEM.md candidates were omitted because the candidate limit was reached.",
|
|
15
|
+
"diagnostic-limit": "Additional scan diagnostics were omitted because the diagnostic limit was reached.",
|
|
16
|
+
"directory-inaccessible": "This directory could not be read and was skipped.",
|
|
17
|
+
"directory-limit": "Additional directories were not scanned because the directory limit was reached.",
|
|
18
|
+
"root-inaccessible": "This discovery root could not be read and was skipped.",
|
|
19
|
+
"root-missing": "This discovery root does not exist and was skipped.",
|
|
20
|
+
"root-not-directory": "This discovery root is not a directory and was skipped.",
|
|
21
|
+
"saved-selection-invalid": "The saved APPEND_SYSTEM.md selection is no longer available from the approved discovery roots.",
|
|
22
|
+
"symlink-entry": "This symbolic-link entry was skipped and was not followed.",
|
|
23
|
+
"symlink-inaccessible": "This symbolic-link target could not be resolved and was skipped.",
|
|
24
|
+
"symlink-unsupported-target": "This symbolic-link target is not a regular file or directory and was skipped.",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const APPEND_SYSTEM_DIAGNOSTIC_KINDS = Object.freeze(Object.keys(APPEND_SYSTEM_DIAGNOSTIC_MESSAGES));
|
|
28
|
+
|
|
29
|
+
function hasControlCharacters(value) {
|
|
30
|
+
return /[\u0000-\u001f\u007f]/.test(value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function cleanPath(value) {
|
|
34
|
+
if (typeof value !== "string" || hasControlCharacters(value)) return null;
|
|
35
|
+
const clean = value.trim();
|
|
36
|
+
if (!clean || clean.length > 4_096 || !path.isAbsolute(clean)) return null;
|
|
37
|
+
return path.normalize(clean);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function normalizeAppendSystemPromptPath(value) {
|
|
41
|
+
if (value === null || value === undefined) return null;
|
|
42
|
+
return cleanPath(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function normalizeAppendSystemPromptRootPath(value) {
|
|
46
|
+
if (value === null || value === undefined) return null;
|
|
47
|
+
return cleanPath(value);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function diagnosticCollector() {
|
|
51
|
+
const diagnostics = [];
|
|
52
|
+
let truncated = false;
|
|
53
|
+
return {
|
|
54
|
+
diagnostics,
|
|
55
|
+
add(kind, diagnosticPath = "") {
|
|
56
|
+
if (!Object.hasOwn(APPEND_SYSTEM_DIAGNOSTIC_MESSAGES, kind)) return;
|
|
57
|
+
const normalizedPath = typeof diagnosticPath === "string" && !hasControlCharacters(diagnosticPath)
|
|
58
|
+
? diagnosticPath.slice(0, 4_096)
|
|
59
|
+
: "";
|
|
60
|
+
if (diagnostics.length < APPEND_SYSTEM_DISCOVERY_LIMITS.maxDiagnostics - 1) {
|
|
61
|
+
diagnostics.push({ kind, path: normalizedPath, message: APPEND_SYSTEM_DIAGNOSTIC_MESSAGES[kind] });
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
truncated = true;
|
|
65
|
+
if (!diagnostics.some((item) => item.kind === "diagnostic-limit")) {
|
|
66
|
+
diagnostics.push({ kind: "diagnostic-limit", path: "", message: APPEND_SYSTEM_DIAGNOSTIC_MESSAGES["diagnostic-limit"] });
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
get truncated() {
|
|
70
|
+
return truncated;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function resolveDiscoveryRoot(root, diagnostics) {
|
|
76
|
+
const requestedPath = path.resolve(root.path);
|
|
77
|
+
let canonicalPath;
|
|
78
|
+
try {
|
|
79
|
+
canonicalPath = await realpath(requestedPath);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
diagnostics.add(error?.code === "ENOENT" ? "root-missing" : "root-inaccessible", requestedPath);
|
|
82
|
+
return { ...root, path: requestedPath, scan: false };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
const info = await stat(canonicalPath);
|
|
87
|
+
if (!info.isDirectory()) {
|
|
88
|
+
diagnostics.add("root-not-directory", requestedPath);
|
|
89
|
+
return { ...root, path: requestedPath, scan: false };
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
diagnostics.add("root-inaccessible", requestedPath);
|
|
93
|
+
return { ...root, path: requestedPath, scan: false };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { ...root, path: requestedPath, canonicalPath, scan: true };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function discoveryRootInputs({ piRoot, cwd }) {
|
|
100
|
+
return [
|
|
101
|
+
{ path: piRoot || path.join(homedir(), ".pi"), label: "Pi home" },
|
|
102
|
+
{ path: cwd, label: "Current folder" },
|
|
103
|
+
].filter((root) => typeof root.path === "string" && root.path.trim() && !hasControlCharacters(root.path));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function resolveSymbolicLink(entryPath, diagnostics) {
|
|
107
|
+
try {
|
|
108
|
+
const canonicalPath = await realpath(entryPath);
|
|
109
|
+
return { canonicalPath, info: await stat(canonicalPath) };
|
|
110
|
+
} catch {
|
|
111
|
+
diagnostics.add("symlink-inaccessible", entryPath);
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Discovers exact visible-name APPEND_SYSTEM.md regular files under the lexical
|
|
118
|
+
* roots. Directory links are followed, and all output classes are capped by
|
|
119
|
+
* APPEND_SYSTEM_DISCOVERY_LIMITS.
|
|
120
|
+
*/
|
|
121
|
+
export async function discoverAppendSystemFiles({ piRoot, cwd, savedPath = null, excludedPaths = [] } = {}) {
|
|
122
|
+
const diagnostics = diagnosticCollector();
|
|
123
|
+
const excludedCandidatePaths = new Set(
|
|
124
|
+
(Array.isArray(excludedPaths) ? excludedPaths : []).map(cleanPath).filter(Boolean),
|
|
125
|
+
);
|
|
126
|
+
const resolvedRoots = [];
|
|
127
|
+
for (const root of discoveryRootInputs({ piRoot, cwd })) {
|
|
128
|
+
resolvedRoots.push(await resolveDiscoveryRoot(root, diagnostics));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const roots = [];
|
|
132
|
+
const seenRootPaths = new Set();
|
|
133
|
+
for (const root of resolvedRoots) {
|
|
134
|
+
if (seenRootPaths.has(root.path)) continue;
|
|
135
|
+
seenRootPaths.add(root.path);
|
|
136
|
+
roots.push({ path: root.path, label: root.label });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const candidatesByPath = new Map();
|
|
140
|
+
const addCandidate = (candidatePath, rootLabel) => {
|
|
141
|
+
const normalizedPath = cleanPath(candidatePath);
|
|
142
|
+
if (!normalizedPath || candidatesByPath.has(normalizedPath)) return;
|
|
143
|
+
if (candidatesByPath.size < APPEND_SYSTEM_DISCOVERY_LIMITS.maxCandidates) {
|
|
144
|
+
candidatesByPath.set(normalizedPath, { path: normalizedPath, rootLabel });
|
|
145
|
+
} else if (!candidateLimitReached) {
|
|
146
|
+
candidateLimitReached = true;
|
|
147
|
+
diagnostics.add("candidate-limit");
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const scannedRemainingDepth = new Map();
|
|
151
|
+
const scanStates = resolvedRoots
|
|
152
|
+
.filter((root) => root.scan)
|
|
153
|
+
.map((root) => ({
|
|
154
|
+
root,
|
|
155
|
+
queue: [{ directory: root.path, canonicalDirectory: root.canonicalPath, depth: 0 }],
|
|
156
|
+
queueIndex: 0,
|
|
157
|
+
}));
|
|
158
|
+
let visitedDirectories = 0;
|
|
159
|
+
let directoryLimitReached = false;
|
|
160
|
+
let candidateLimitReached = false;
|
|
161
|
+
|
|
162
|
+
// Round-robin traversal prevents either approved root from consuming the shared
|
|
163
|
+
// directory budget before the other root receives a deterministic scan turn.
|
|
164
|
+
while (visitedDirectories < APPEND_SYSTEM_DISCOVERY_LIMITS.maxVisitedDirectories) {
|
|
165
|
+
let scannedInRound = false;
|
|
166
|
+
for (const state of scanStates) {
|
|
167
|
+
let current;
|
|
168
|
+
while (state.queueIndex < state.queue.length) {
|
|
169
|
+
const queued = state.queue[state.queueIndex];
|
|
170
|
+
state.queueIndex += 1;
|
|
171
|
+
const remainingDepth = APPEND_SYSTEM_DISCOVERY_LIMITS.maxDepth - queued.depth;
|
|
172
|
+
if ((scannedRemainingDepth.get(queued.canonicalDirectory) ?? -1) >= remainingDepth) continue;
|
|
173
|
+
current = queued;
|
|
174
|
+
scannedRemainingDepth.set(current.canonicalDirectory, remainingDepth);
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
if (!current) continue;
|
|
178
|
+
if (visitedDirectories >= APPEND_SYSTEM_DISCOVERY_LIMITS.maxVisitedDirectories) {
|
|
179
|
+
directoryLimitReached = true;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
scannedInRound = true;
|
|
183
|
+
visitedDirectories += 1;
|
|
184
|
+
|
|
185
|
+
let entries;
|
|
186
|
+
try {
|
|
187
|
+
entries = await readdir(current.directory, { withFileTypes: true });
|
|
188
|
+
} catch {
|
|
189
|
+
diagnostics.add("directory-inaccessible", current.directory);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
|
|
193
|
+
|
|
194
|
+
for (const entry of entries) {
|
|
195
|
+
const entryPath = path.join(current.directory, entry.name);
|
|
196
|
+
if (entry.isSymbolicLink()) {
|
|
197
|
+
const resolvedLink = await resolveSymbolicLink(entryPath, diagnostics);
|
|
198
|
+
if (!resolvedLink) continue;
|
|
199
|
+
if (resolvedLink.info.isFile()) {
|
|
200
|
+
if (entry.name === APPEND_SYSTEM_FILE_NAME && !excludedCandidatePaths.has(entryPath)) {
|
|
201
|
+
addCandidate(entryPath, state.root.label);
|
|
202
|
+
}
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (resolvedLink.info.isDirectory()) {
|
|
206
|
+
if (current.depth < APPEND_SYSTEM_DISCOVERY_LIMITS.maxDepth) {
|
|
207
|
+
state.queue.push({
|
|
208
|
+
directory: entryPath,
|
|
209
|
+
canonicalDirectory: resolvedLink.canonicalPath,
|
|
210
|
+
depth: current.depth + 1,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
diagnostics.add("symlink-unsupported-target", entryPath);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (entry.isFile() && entry.name === APPEND_SYSTEM_FILE_NAME && !excludedCandidatePaths.has(entryPath)) {
|
|
219
|
+
addCandidate(entryPath, state.root.label);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (entry.isDirectory() && current.depth < APPEND_SYSTEM_DISCOVERY_LIMITS.maxDepth) {
|
|
223
|
+
let canonicalDirectory;
|
|
224
|
+
try {
|
|
225
|
+
canonicalDirectory = await realpath(entryPath);
|
|
226
|
+
} catch {
|
|
227
|
+
diagnostics.add("directory-inaccessible", entryPath);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
state.queue.push({ directory: entryPath, canonicalDirectory, depth: current.depth + 1 });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!scannedInRound || directoryLimitReached) break;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!directoryLimitReached && visitedDirectories >= APPEND_SYSTEM_DISCOVERY_LIMITS.maxVisitedDirectories) {
|
|
238
|
+
directoryLimitReached = scanStates.some((state) => state.queueIndex < state.queue.length);
|
|
239
|
+
}
|
|
240
|
+
if (directoryLimitReached) diagnostics.add("directory-limit");
|
|
241
|
+
|
|
242
|
+
const candidates = [...candidatesByPath.values()].sort((left, right) => left.path.localeCompare(right.path, "en"));
|
|
243
|
+
const appendSystemPromptPath = normalizeAppendSystemPromptPath(savedPath);
|
|
244
|
+
if (appendSystemPromptPath && !candidatesByPath.has(appendSystemPromptPath)) {
|
|
245
|
+
diagnostics.add("saved-selection-invalid", appendSystemPromptPath);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
appendSystemPromptPath,
|
|
250
|
+
roots,
|
|
251
|
+
candidates,
|
|
252
|
+
diagnostics: diagnostics.diagnostics,
|
|
253
|
+
limits: {
|
|
254
|
+
...APPEND_SYSTEM_DISCOVERY_LIMITS,
|
|
255
|
+
visitedDirectories,
|
|
256
|
+
truncated: {
|
|
257
|
+
directories: directoryLimitReached,
|
|
258
|
+
candidates: candidateLimitReached,
|
|
259
|
+
diagnostics: diagnostics.truncated,
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Revalidates a saved lexical root/path pair without discovery caps. Symlinks
|
|
267
|
+
* may resolve outside the root, but the final visible path must resolve to a
|
|
268
|
+
* regular file.
|
|
269
|
+
*/
|
|
270
|
+
export async function validateSavedAppendSystemSelection(value, rootValue) {
|
|
271
|
+
const savedPath = cleanPath(value);
|
|
272
|
+
const rootPath = cleanPath(rootValue);
|
|
273
|
+
if (!savedPath || !rootPath || path.basename(savedPath) !== APPEND_SYSTEM_FILE_NAME) return null;
|
|
274
|
+
|
|
275
|
+
const relativePath = path.relative(rootPath, savedPath);
|
|
276
|
+
if (!relativePath || path.isAbsolute(relativePath) || relativePath === ".." || relativePath.startsWith(`..${path.sep}`)) return null;
|
|
277
|
+
const segments = relativePath.split(path.sep);
|
|
278
|
+
if (segments.length - 1 > APPEND_SYSTEM_DISCOVERY_LIMITS.maxDepth) return null;
|
|
279
|
+
|
|
280
|
+
try {
|
|
281
|
+
await realpath(rootPath);
|
|
282
|
+
const rootInfo = await stat(rootPath);
|
|
283
|
+
if (!rootInfo.isDirectory()) return null;
|
|
284
|
+
|
|
285
|
+
await realpath(savedPath);
|
|
286
|
+
const savedInfo = await stat(savedPath);
|
|
287
|
+
if (!savedInfo.isFile()) return null;
|
|
288
|
+
return { path: savedPath, rootPath };
|
|
289
|
+
} catch {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Confirms a submitted visible alias appears in a fresh bounded scan. */
|
|
295
|
+
export async function validateAppendSystemSelection(value, options = {}) {
|
|
296
|
+
const submittedPath = cleanPath(value);
|
|
297
|
+
if (!submittedPath || path.basename(submittedPath) !== APPEND_SYSTEM_FILE_NAME) return null;
|
|
298
|
+
|
|
299
|
+
const discovery = await discoverAppendSystemFiles({ ...options, savedPath: submittedPath });
|
|
300
|
+
const candidate = discovery.candidates.find((item) => item.path === submittedPath);
|
|
301
|
+
if (!candidate) return null;
|
|
302
|
+
const rootPath = discovery.roots.find((root) => root.label === candidate.rootLabel)?.path;
|
|
303
|
+
if (!rootPath) return null;
|
|
304
|
+
try {
|
|
305
|
+
const finalInfo = await stat(submittedPath);
|
|
306
|
+
if (!finalInfo.isFile()) return null;
|
|
307
|
+
} catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
return { path: submittedPath, rootPath, discovery };
|
|
311
|
+
}
|
|
@@ -5,6 +5,10 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
5
5
|
import { normalizeSubagentLaunchSlots } from "./subagent-launch-slots.mjs";
|
|
6
6
|
import { normalizeUiLayout } from "./ui-layout-settings.mjs";
|
|
7
7
|
import { normalizeResourceDefaults } from "./resource-selection.mjs";
|
|
8
|
+
import {
|
|
9
|
+
normalizeAppendSystemPromptPath,
|
|
10
|
+
normalizeAppendSystemPromptRootPath,
|
|
11
|
+
} from "./append-system-selection.mjs";
|
|
8
12
|
import { normalizeOutputMode, OUTPUT_MODE_NORMAL } from "./webui-output-mode.mjs";
|
|
9
13
|
|
|
10
14
|
export const GIT_WORKFLOW_SETUP_VERSION = 1;
|
|
@@ -186,6 +190,8 @@ export function normalizeWebuiSettings(value) {
|
|
|
186
190
|
...source,
|
|
187
191
|
version: normalizedSettingsVersion(source),
|
|
188
192
|
remoteAuthEnabled: source.remoteAuthEnabled === true,
|
|
193
|
+
appendSystemPromptPath: normalizeAppendSystemPromptPath(source.appendSystemPromptPath),
|
|
194
|
+
appendSystemPromptRootPath: normalizeAppendSystemPromptRootPath(source.appendSystemPromptRootPath),
|
|
189
195
|
outputModeDefault: normalizeOutputMode(source.outputModeDefault, OUTPUT_MODE_NORMAL),
|
|
190
196
|
gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
|
|
191
197
|
resourceDefaults: normalizeResourceDefaults(resourceDefaultsSource),
|
package/lib/trust-boundaries.mjs
CHANGED
|
@@ -57,6 +57,43 @@ export function isLocalRequest(req) {
|
|
|
57
57
|
return isLocalAddress(req?.socket?.remoteAddress);
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
function validAuthorityPort(value) {
|
|
61
|
+
return /^\d{1,5}$/.test(value) && Number(value) <= 65_535;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Accepts only localhost, 127/8, or IPv6 loopback HTTP Host authorities. */
|
|
65
|
+
export function isLoopbackHostAuthority(authority = "") {
|
|
66
|
+
const value = String(authority || "").trim();
|
|
67
|
+
if (!value || /[\s,@/\\]/.test(value)) return false;
|
|
68
|
+
|
|
69
|
+
let host = value;
|
|
70
|
+
if (value.startsWith("[")) {
|
|
71
|
+
const closingBracket = value.indexOf("]");
|
|
72
|
+
if (closingBracket < 0) return false;
|
|
73
|
+
host = value.slice(1, closingBracket);
|
|
74
|
+
const suffix = value.slice(closingBracket + 1);
|
|
75
|
+
if (suffix && (!suffix.startsWith(":") || !validAuthorityPort(suffix.slice(1)))) return false;
|
|
76
|
+
if (!suffix && closingBracket !== value.length - 1) return false;
|
|
77
|
+
try {
|
|
78
|
+
return new URL(`http://[${host}]`).hostname.toLowerCase() === "[::1]";
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const separator = value.lastIndexOf(":");
|
|
85
|
+
if (separator >= 0) {
|
|
86
|
+
if (value.indexOf(":") !== separator || !validAuthorityPort(value.slice(separator + 1))) return false;
|
|
87
|
+
host = value.slice(0, separator);
|
|
88
|
+
}
|
|
89
|
+
const normalizedHost = host.toLowerCase().replace(/\.$/, "");
|
|
90
|
+
if (normalizedHost === "localhost") return true;
|
|
91
|
+
const octets = normalizedHost.split(".");
|
|
92
|
+
return octets.length === 4
|
|
93
|
+
&& octets.every((octet) => /^(?:0|[1-9]\d{0,2})$/.test(octet) && Number(octet) <= 255)
|
|
94
|
+
&& Number(octets[0]) === 127;
|
|
95
|
+
}
|
|
96
|
+
|
|
60
97
|
export function makeTrustError(statusCode, message, details = {}) {
|
|
61
98
|
const error = new Error(message);
|
|
62
99
|
error.statusCode = statusCode;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@firstpick/pi-package-webui",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.3",
|
|
4
4
|
"description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
|