@firstpick/pi-package-webui 0.7.4 → 0.7.5

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.
@@ -0,0 +1,143 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
7
+ defaultSubagentLaunchSlotRoles,
8
+ formatSubagentLaunchSlotGuidance,
9
+ normalizeSubagentLaunchSlots,
10
+ resolveSubagentLaunchSlotProjectKey,
11
+ subagentLaunchSlotBaseId,
12
+ subagentLaunchSlotRevision,
13
+ subagentLaunchSlotScopeEntry,
14
+ validateSubagentLaunchSlotRoles,
15
+ } from "../lib/subagent-launch-slots.mjs";
16
+ import { readWebuiSettings, updateWebuiSettings, writeWebuiSettings } from "../lib/git-workflow-preferences.mjs";
17
+
18
+ function clone(value) {
19
+ return JSON.parse(JSON.stringify(value));
20
+ }
21
+
22
+ const defaultRoles = defaultSubagentLaunchSlotRoles();
23
+ assert.deepEqual(Object.keys(defaultRoles), SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG.map((role) => role.id));
24
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
25
+ assert.deepEqual(defaultRoles[role.id], [{ id: subagentLaunchSlotBaseId(role.id), model: null, thinking: null }]);
26
+ }
27
+
28
+ const normalized = normalizeSubagentLaunchSlots({
29
+ user: {
30
+ roles: {
31
+ reviewer: [
32
+ { id: "reviewer-extra", model: "fake/reasoning", thinking: "high" },
33
+ { id: "reviewer:base", model: "fake/legacy:high", thinking: "high" },
34
+ { id: "reviewer-extra", model: "fake/reasoning", thinking: "high" },
35
+ { id: "unsafe id", model: "fake/reasoning", thinking: "high" },
36
+ ],
37
+ },
38
+ },
39
+ projects: {
40
+ relative: { roles: { reviewer: [{ id: "reviewer:base", model: "fake/reasoning", thinking: "high" }] } },
41
+ },
42
+ });
43
+ assert.equal(normalized.user.roles.reviewer[0].id, "reviewer:base", "normalization must materialize and order the stable base slot first");
44
+ assert.equal(normalized.user.roles.reviewer[0].model, null, "thinking-suffixed persisted model IDs must reset to inheritance");
45
+ assert.deepEqual(normalized.user.roles.reviewer.slice(1), [{ id: "reviewer-extra", model: "fake/reasoning", thinking: "high" }]);
46
+ assert.deepEqual(normalized.projects, {}, "unsafe project keys must be dropped without changing user defaults");
47
+ const overloadedRoles = defaultSubagentLaunchSlotRoles();
48
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
49
+ overloadedRoles[role.id].push(...Array.from({ length: 7 }, (_unused, index) => ({
50
+ id: `${role.id}-extra-${index}`,
51
+ model: null,
52
+ thinking: null,
53
+ })));
54
+ }
55
+ const boundedRoles = normalizeSubagentLaunchSlots({ user: { roles: overloadedRoles } }).user.roles;
56
+ assert.equal(Object.values(boundedRoles).flat().length, 32, "normalization must cap slots globally while retaining all role bases");
57
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
58
+ assert.equal(boundedRoles[role.id][0].id, subagentLaunchSlotBaseId(role.id), "global bounds must never displace a role base slot");
59
+ }
60
+
61
+ const availableModels = [
62
+ { provider: "fake", id: "reasoning", reasoning: true, thinkingLevelMap: { xhigh: "xhigh" } },
63
+ { provider: "fake", id: "basic", reasoning: false },
64
+ ];
65
+ const validRoles = clone(defaultRoles);
66
+ validRoles.reviewer[0] = { id: "reviewer:base", model: "fake/reasoning", thinking: "high" };
67
+ validRoles.reviewer.push({ id: "reviewer-extra", model: "fake/basic", thinking: "off" });
68
+ assert.deepEqual(validateSubagentLaunchSlotRoles(validRoles, availableModels).reviewer, validRoles.reviewer);
69
+ assert.throws(() => validateSubagentLaunchSlotRoles({ ...validRoles, unknown: [] }, availableModels), /Unknown subagent role/);
70
+ assert.throws(() => validateSubagentLaunchSlotRoles({ ...validRoles, reviewer: [{ id: "reviewer-extra", model: null, thinking: null }] }, availableModels), /base slot/);
71
+ assert.throws(() => validateSubagentLaunchSlotRoles({ ...validRoles, reviewer: [{ id: "reviewer:base", model: null, thinking: "high" }] }, availableModels), /cannot set thinking/);
72
+ assert.throws(() => validateSubagentLaunchSlotRoles({ ...validRoles, reviewer: [{ id: "reviewer:base", model: "fake/reasoning:high", thinking: "high" }] }, availableModels), /invalid model/);
73
+ assert.throws(() => validateSubagentLaunchSlotRoles({ ...validRoles, reviewer: [{ id: "reviewer:base", model: "fake/basic", thinking: "high" }] }, availableModels), /does not support/);
74
+
75
+ const projectRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-launch-slots-project-"));
76
+ const nested = path.join(projectRoot, "nested", "child");
77
+ const settingsRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-launch-slots-settings-"));
78
+ const settingsFile = path.join(settingsRoot, "settings.json");
79
+ try {
80
+ await mkdir(path.join(projectRoot, ".git"));
81
+ await mkdir(nested, { recursive: true });
82
+ const projectKey = await resolveSubagentLaunchSlotProjectKey(nested);
83
+ assert.equal(projectKey, projectRoot, "nested tab cwd must resolve to the nearest canonical repository root");
84
+ const markerlessProjectKey = await resolveSubagentLaunchSlotProjectKey(settingsRoot);
85
+ assert.equal(markerlessProjectKey, settingsRoot, "a markerless tab cwd must not collapse to the filesystem root");
86
+
87
+ const config = normalizeSubagentLaunchSlots({ user: { roles: validRoles } });
88
+ const inherited = subagentLaunchSlotScopeEntry(config, "project", projectKey);
89
+ assert.equal(inherited.inherited, true);
90
+ assert.deepEqual(inherited.entry.roles.reviewer, validRoles.reviewer);
91
+ const inheritedRevision = subagentLaunchSlotRevision(config, "project", projectKey);
92
+ config.projects[projectKey] = { roles: clone(defaultRoles) };
93
+ const explicit = subagentLaunchSlotScopeEntry(config, "project", projectKey);
94
+ assert.equal(explicit.inherited, false);
95
+ assert.notEqual(subagentLaunchSlotRevision(config, "project", projectKey), inheritedRevision, "project revisions must distinguish inheritance from an explicit project entry");
96
+
97
+ const guidance = formatSubagentLaunchSlotGuidance(inherited.entry.roles);
98
+ assert.match(guidance, /^## WebUI subagent launch slots/m);
99
+ assert.match(guidance, /reviewer slot 1: agent=reviewer model=fake\/reasoning:high/);
100
+ assert.match(guidance, /reviewer slot 2: agent=reviewer model=fake\/basic:off/);
101
+ const mixedGuidanceRoles = clone(defaultRoles);
102
+ mixedGuidanceRoles.reviewer.push({ id: "reviewer-explicit", model: "fake/reasoning", thinking: "high" });
103
+ const mixedGuidance = formatSubagentLaunchSlotGuidance(mixedGuidanceRoles);
104
+ assert.match(mixedGuidance, /reviewer slot 1: agent=reviewer model=<inherit; omit the model field>/, "mixed same-role guidance must retain inherited slots");
105
+ assert.match(mixedGuidance, /reviewer slot 2: agent=reviewer model=fake\/reasoning:high/);
106
+ assert.equal(formatSubagentLaunchSlotGuidance(defaultRoles), "", "guidance should be omitted when every slot inherits");
107
+
108
+ await writeFile(settingsFile, `${JSON.stringify({ version: 4, unrelated: { preserve: true }, remoteAuthEnabled: true }, null, 2)}\n`, "utf8");
109
+ await writeWebuiSettings({ subagentLaunchSlots: config }, settingsFile);
110
+ const persisted = JSON.parse(await readFile(settingsFile, "utf8"));
111
+ assert.equal(persisted.version, 5, "persisted launch-slot settings must use the version-5 envelope");
112
+ assert.deepEqual(persisted.unrelated, { preserve: true }, "launch-slot saves must preserve unrelated WebUI settings");
113
+ assert.deepEqual((await readWebuiSettings(settingsFile)).subagentLaunchSlots.projects[projectKey].roles, defaultRoles);
114
+
115
+ let releaseFirstUpdate;
116
+ let markFirstUpdateStarted;
117
+ const firstUpdateStarted = new Promise((resolve) => { markFirstUpdateStarted = resolve; });
118
+ const holdFirstUpdate = new Promise((resolve) => { releaseFirstUpdate = resolve; });
119
+ const firstUpdate = updateWebuiSettings(async () => {
120
+ markFirstUpdateStarted();
121
+ await holdFirstUpdate;
122
+ return { remoteAuthEnabled: false };
123
+ }, settingsFile);
124
+ await firstUpdateStarted;
125
+ let secondUpdateEntered = false;
126
+ const secondUpdate = updateWebuiSettings((current) => {
127
+ secondUpdateEntered = true;
128
+ assert.equal(current.remoteAuthEnabled, false, "serialized settings updates must observe the preceding completed write");
129
+ return { outputModeDefault: "compact-v1" };
130
+ }, settingsFile);
131
+ await new Promise((resolve) => setImmediate(resolve));
132
+ assert.equal(secondUpdateEntered, false, "same-file settings updates must not interleave between revision read and atomic write");
133
+ releaseFirstUpdate();
134
+ await Promise.all([firstUpdate, secondUpdate]);
135
+ const serialized = await readWebuiSettings(settingsFile);
136
+ assert.equal(serialized.remoteAuthEnabled, false);
137
+ assert.equal(serialized.outputModeDefault, "compact-v1");
138
+
139
+ console.log("subagent-launch-slots.test.mjs passed");
140
+ } finally {
141
+ await rm(projectRoot, { recursive: true, force: true });
142
+ await rm(settingsRoot, { recursive: true, force: true });
143
+ }
@@ -3,6 +3,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
5
  import webuiRpcHelper from "../webui-rpc-helper.mjs";
6
+ import { defaultSubagentLaunchSlotRoles } from "../lib/subagent-launch-slots.mjs";
6
7
 
7
8
  class EventBus {
8
9
  constructor() {
@@ -50,6 +51,14 @@ const ctx = {
50
51
  sessionManager: {
51
52
  getBranch() { return []; },
52
53
  },
54
+ getSystemPromptOptions() {
55
+ return {
56
+ skills: [
57
+ { name: "repo-explorer", description: "Inspect repository context", filePath: "/tmp/repo-explorer/SKILL.md" },
58
+ { name: "code-security", description: "Review code security", filePath: "/tmp/code-security/SKILL.md" },
59
+ ],
60
+ };
61
+ },
53
62
  ui: {
54
63
  setStatus(key, text) {
55
64
  statuses.push({ key, text });
@@ -61,6 +70,15 @@ const ctx = {
61
70
  };
62
71
 
63
72
  const asyncRunDir = await mkdtemp(path.join(tmpdir(), "pi-webui-subagent-output-test-"));
73
+ const settingsFile = path.join(asyncRunDir, "webui-settings.json");
74
+ const initialLaunchRoles = defaultSubagentLaunchSlotRoles();
75
+ initialLaunchRoles.reviewer[0] = { id: "reviewer:base", model: "fake/reviewer", thinking: "high" };
76
+ await writeFile(settingsFile, `${JSON.stringify({
77
+ version: 5,
78
+ resourceDefaults: { tools: { enabledTools: null }, skills: { enabledSkills: ["repo-explorer"] } },
79
+ subagentLaunchSlots: { version: 1, user: { roles: initialLaunchRoles }, projects: {} },
80
+ }, null, 2)}\n`);
81
+ process.env.PI_WEBUI_SETTINGS_FILE = settingsFile;
64
82
  const asyncSessionFile = path.join(asyncRunDir, "reviewer-session.jsonl");
65
83
  await writeFile(asyncSessionFile, [
66
84
  JSON.stringify({ type: "message", timestamp: "2026-07-19T12:00:00.000Z", message: { role: "assistant", content: [{ type: "thinking", thinking: "Checking structured transcript extraction" }, { type: "text", text: "REVIEWER STREAM 1 OF 18" }, { type: "toolCall", id: "review-call", name: "bash", arguments: { command: "sleep 5" } }, { type: "text", text: "Review complete." }] } }),
@@ -106,6 +124,33 @@ const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
106
124
  });
107
125
 
108
126
  for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "startup" }, ctx);
127
+ const beforeAgentStart = (extensionHandlers.get("before_agent_start") || [])[0];
128
+ assert.ok(beforeAgentStart, "helper should register before_agent_start guidance");
129
+ const promptWithSkills = [
130
+ "Base system prompt.",
131
+ "The following skills provide specialized capabilities:",
132
+ "<available_skills>",
133
+ " <skill>",
134
+ " <name>repo-explorer</name>",
135
+ " </skill>",
136
+ " <skill>",
137
+ " <name>code-security</name>",
138
+ " </skill>",
139
+ "</available_skills>",
140
+ ].join("\n");
141
+ const initialGuidance = await beforeAgentStart({ systemPrompt: promptWithSkills, systemPromptOptions: ctx.getSystemPromptOptions() });
142
+ assert.match(initialGuidance?.systemPrompt || "", /reviewer slot 1: agent=reviewer model=fake\/reviewer:high/, "session_start should cache effective launch-slot guidance");
143
+ assert.doesNotMatch(initialGuidance?.systemPrompt || "", /code-security/, "launch-slot guidance must compose with disabled-skill filtering");
144
+ const changedLaunchRoles = defaultSubagentLaunchSlotRoles();
145
+ changedLaunchRoles.reviewer[0] = { id: "reviewer:base", model: "fake/changed", thinking: "high" };
146
+ await writeFile(settingsFile, `${JSON.stringify({
147
+ version: 5,
148
+ resourceDefaults: { tools: { enabledTools: null }, skills: { enabledSkills: ["repo-explorer"] } },
149
+ subagentLaunchSlots: { version: 1, user: { roles: changedLaunchRoles }, projects: {} },
150
+ }, null, 2)}\n`);
151
+ const cachedGuidance = await beforeAgentStart({ systemPrompt: "Base system prompt.", systemPromptOptions: ctx.getSystemPromptOptions() });
152
+ assert.match(cachedGuidance?.systemPrompt || "", /fake\/reviewer:high/, "a settings save must not mutate the active helper snapshot");
153
+ assert.doesNotMatch(cachedGuidance?.systemPrompt || "", /fake\/changed:high/);
109
154
  for (let attempt = 0; attempt < 20 && !statuses.some((entry) => entry.text?.startsWith("PI_WEBUI_SUBAGENTS_V1 ") && entry.text.includes("run-a")); attempt++) {
110
155
  await new Promise((resolve) => setTimeout(resolve, 10));
111
156
  }
@@ -315,6 +360,7 @@ assert.equal(payload.runs.some((run) => run.source === "foreground"), false, "fo
315
360
 
316
361
  for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
317
362
  unsubscribeRpc();
363
+ delete process.env.PI_WEBUI_SETTINGS_FILE;
318
364
  await rm(asyncRunDir, { recursive: true, force: true });
319
365
 
320
366
  console.log("subagents-helper.test.mjs passed");
@@ -2,6 +2,11 @@ import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs"
2
2
  import path from "node:path";
3
3
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
4
4
  import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
5
+ import {
6
+ formatSubagentLaunchSlotGuidance,
7
+ resolveSubagentLaunchSlotProjectKey,
8
+ subagentLaunchSlotScopeEntry,
9
+ } from "./lib/subagent-launch-slots.mjs";
5
10
  import { SUBAGENT_GATE_UPDATE_EVENT } from "./lib/subagent-gate.mjs";
6
11
 
7
12
  const HELPER_COMMAND = "webui-helper";
@@ -540,6 +545,7 @@ export default function webuiRpcHelper(pi) {
540
545
  let enabledTools = new Set();
541
546
  let disabledSkills = new Set();
542
547
  let inheritedEnabledSkills = null;
548
+ let subagentLaunchSlotGuidance = "";
543
549
  let subagentContext = null;
544
550
  let subagentBridgeAvailable = false;
545
551
  let subagentPollTimer = null;
@@ -889,6 +895,18 @@ export default function webuiRpcHelper(pi) {
889
895
  }
890
896
  }
891
897
 
898
+ async function loadSubagentLaunchSlotGuidance(ctx) {
899
+ try {
900
+ const settings = await readWebuiSettings();
901
+ const projectKey = await resolveSubagentLaunchSlotProjectKey(ctx?.cwd);
902
+ const effective = subagentLaunchSlotScopeEntry(settings.subagentLaunchSlots, "project", projectKey);
903
+ subagentLaunchSlotGuidance = formatSubagentLaunchSlotGuidance(effective.entry.roles);
904
+ } catch (error) {
905
+ subagentLaunchSlotGuidance = "";
906
+ console.warn(`Web UI subagent launch slots could not be read: ${error instanceof Error ? error.message : String(error)}`);
907
+ }
908
+ }
909
+
892
910
  function persistToolsState() {
893
911
  pi.appendEntry(TOOLS_CONFIG_TYPE, { enabledTools: [...enabledTools] });
894
912
  }
@@ -1053,6 +1071,7 @@ export default function webuiRpcHelper(pi) {
1053
1071
  const globalDefaults = await readGlobalResourceDefaults();
1054
1072
  restoreToolsFromBranch(ctx, globalDefaults);
1055
1073
  restoreSkillsFromBranch(ctx, globalDefaults);
1074
+ await loadSubagentLaunchSlotGuidance(ctx);
1056
1075
  subagentContext = ctx;
1057
1076
  subagentPollGeneration += 1;
1058
1077
  foregroundSubagentRuns.clear();
@@ -1128,6 +1147,7 @@ export default function webuiRpcHelper(pi) {
1128
1147
 
1129
1148
  pi.on("session_shutdown", () => {
1130
1149
  subagentContext = null;
1150
+ subagentLaunchSlotGuidance = "";
1131
1151
  subagentPollGeneration += 1;
1132
1152
  clearTimeout(subagentPollTimer);
1133
1153
  subagentPollTimer = null;
@@ -1147,14 +1167,22 @@ export default function webuiRpcHelper(pi) {
1147
1167
  });
1148
1168
 
1149
1169
  pi.on("before_agent_start", async (event) => {
1150
- if (disabledSkills.size === 0 && inheritedEnabledSkills === null) return;
1151
- const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
1152
- if (allSkills.length === 0) return;
1153
- const disabledNames = allSkills.filter((skill) => !isSkillEnabled(skill.name)).map((skill) => skill.name);
1154
- if (disabledNames.length === 0) return;
1155
- const filteredSkills = allSkills.filter((skill) => isSkillEnabled(skill.name));
1156
- let nextPrompt = replaceAvailableSkillsSection(event.systemPrompt, filteredSkills);
1157
- for (const name of disabledNames) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
1158
- return { systemPrompt: nextPrompt };
1170
+ let nextPrompt = event.systemPrompt;
1171
+ let changed = false;
1172
+ if (disabledSkills.size !== 0 || inheritedEnabledSkills !== null) {
1173
+ const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
1174
+ const disabledNames = allSkills.filter((skill) => !isSkillEnabled(skill.name)).map((skill) => skill.name);
1175
+ if (disabledNames.length) {
1176
+ const filteredSkills = allSkills.filter((skill) => isSkillEnabled(skill.name));
1177
+ nextPrompt = replaceAvailableSkillsSection(nextPrompt, filteredSkills);
1178
+ for (const name of disabledNames) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
1179
+ changed = true;
1180
+ }
1181
+ }
1182
+ if (subagentLaunchSlotGuidance) {
1183
+ nextPrompt = `${String(nextPrompt || "").trimEnd()}\n\n${subagentLaunchSlotGuidance}\n`;
1184
+ changed = true;
1185
+ }
1186
+ return changed ? { systemPrompt: nextPrompt } : undefined;
1159
1187
  });
1160
1188
  }