@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.
package/README.md CHANGED
@@ -139,7 +139,7 @@ Normal output is the default. In the sidebar, open **Controls → Output process
139
139
 
140
140
  The browser negotiates compact-v1 per EventSource connection (`outputMode=auto&outputModeProtocol=1`), so normal and compact clients can share one Pi tab. A browser only enables compact handling after the protocol-1 acknowledgement; an older server gets one normal-mode reconnect instead. The server default applies only to `auto` clients, and active auto streams change representation at a semantic boundary.
141
141
 
142
- Compact mode keeps live text and thinking as plain text, coalesces sustained live DOM/scroll flushes to at most once every 100 ms, and uses lightweight tool shells. It then reconciles with the existing final `/api/messages` transcript to restore Markdown, thinking formatting, and full tool cards. It does not change Pi generation, prompts, tools, models, providers, inference, final transcript semantics, or the normal renderer.
142
+ Fast mode keeps live output lightweight, coalesces sustained live DOM/scroll flushes to at most once every 100 ms, preserves Markdown formatting for live and reconciled thinking, and displays only the current transient tool status as a compact labeled row with a state pill; each new tool or assistant delta replaces that status instead of retaining a tool-call history. Final reconciliation keeps visible thinking formatted and renders the final assistant response as Markdown while omitting intermediate tool calls, results, diffs, images, and raw details. The existing final `/api/messages` transcript remains authoritative. Fast mode does not change Pi generation, prompts, tools, models, providers, inference, stored transcript semantics, or the normal renderer.
143
143
 
144
144
  The included fast-mode metric measures deterministic post-parse serialized JSON byte-work only (`R + 2×S`) and semantic parity; it does not claim wall-clock improvement, lower DOM CPU, reduced network latency, or higher model token/s.
145
145
 
@@ -156,6 +156,7 @@ Optional Natural Conversation server-side voice fallback variables:
156
156
 
157
157
  - Pathless `pi-webui` startup: the server opens first, then the browser prompts for the first terminal CWD.
158
158
  - Multi-tab Pi sessions with isolated processes, working directories, prompt drafts, activity state, per-tab settings, and a workspace dashboard for common actions.
159
+ - The Subagents side panel includes a separate **Agent models** editor above the live monitor. It stores WebUI-owned launch slots for the eight builtin roles (`context-builder`, `delegate`, `oracle`, `planner`, `researcher`, `reviewer`, `scout`, and `worker`): every role keeps a non-removable base slot, while added same-role slots copy a model/thinking draft but retain independent stable IDs. Choose **User default** or **This project**; projects inherit user defaults until saved, and **Use user defaults** removes a project override. Select `Default / inherit` to inherit both values, or an active-tab provider-qualified model and its supported thinking levels. Saves are revision-checked and localhost-only; saved assignments guide only future delegation after **Reload active tab**, never running children. The configuration form has independent load/draft/error state, so its controls are not reset by live subagent monitoring.
159
160
  - Tracked subagent output can open in the existing non-blocking overlay/widget or in a dedicated **Subagent** terminal tab, selected from the Subagents side-panel section and saved in the browser. Side-panel rows and both output views show the effective model and reasoning effort (or an explicit `unknown` for legacy metadata). Subagent tabs are view-only, reuse the bounded live transcript at the normal full terminal width, show the pulsing **Agent is running:** card with current child activity, and close without stopping or interrupting the child run; use the parent terminal for interaction. The package also registers a generic `subagent_gate` tool that launches task slots through pi-subagents RPC v1, enforces a required success quorum, and performs bounded reason-aware retries only when declared safe; the side panel retains gate quorum, attempt, provider, and failure-class history after children finish.
160
161
  - Unified command palette (`Ctrl/Cmd+K`) for commands, tabs, models, sessions, settings, app controls, and frequent Web UI actions.
161
162
  - Automatic tab naming from the first prompt, with `--name <name>` still available for an explicit initial tab name.
package/bin/pi-webui.mjs CHANGED
@@ -44,10 +44,24 @@ import {
44
44
  readGitWorkflowPreferences,
45
45
  readWebuiSettings,
46
46
  supportedGitWorkflowThinkingLevels,
47
+ updateWebuiSettings,
47
48
  webuiSettingsFile,
48
49
  writeGitWorkflowPreferences,
49
50
  writeWebuiSettings,
50
51
  } from "../lib/git-workflow-preferences.mjs";
52
+ import {
53
+ SUBAGENT_LAUNCH_SLOT_LIMITS,
54
+ SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
55
+ SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS,
56
+ normalizeSubagentLaunchSlots,
57
+ resolveSubagentLaunchSlotProjectKey,
58
+ subagentLaunchSlotModelKey,
59
+ subagentLaunchSlotProjectLabel,
60
+ subagentLaunchSlotRevision,
61
+ subagentLaunchSlotScopeEntry,
62
+ supportedSubagentLaunchSlotThinkingLevels,
63
+ validateSubagentLaunchSlotRoles,
64
+ } from "../lib/subagent-launch-slots.mjs";
51
65
  import {
52
66
  encodeBrowserSseEvent,
53
67
  isOutputModeSemanticBarrier,
@@ -2059,6 +2073,107 @@ async function saveSafetyGuardConfigData(body = {}) {
2059
2073
  }
2060
2074
  }
2061
2075
 
2076
+ function requireSubagentLaunchSlotScope(value) {
2077
+ const scope = String(value || "").trim();
2078
+ if (!["user", "project"].includes(scope)) throw makeHttpError(400, "scope must be user or project");
2079
+ return scope;
2080
+ }
2081
+
2082
+ async function availableSubagentLaunchSlotModels(tab) {
2083
+ const response = await safeRpcData(tab, { type: "get_available_models" });
2084
+ if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
2085
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
2086
+ .filter((model) => subagentLaunchSlotModelKey(model))
2087
+ .sort((left, right) => subagentLaunchSlotModelKey(left).localeCompare(subagentLaunchSlotModelKey(right)));
2088
+ }
2089
+
2090
+ async function subagentLaunchSlotProjectContext(tab) {
2091
+ const projectKey = await resolveSubagentLaunchSlotProjectKey(tab.cwd);
2092
+ return { projectKey, projectLabel: subagentLaunchSlotProjectLabel(projectKey) };
2093
+ }
2094
+
2095
+ function subagentLaunchSlotConfigPayload(settings, scope, project, models, extra = {}) {
2096
+ const config = normalizeSubagentLaunchSlots(settings?.subagentLaunchSlots);
2097
+ const effective = subagentLaunchSlotScopeEntry(config, scope, project.projectKey);
2098
+ return {
2099
+ scope,
2100
+ projectKey: project.projectKey,
2101
+ projectLabel: project.projectLabel,
2102
+ inherited: effective.inherited,
2103
+ revision: subagentLaunchSlotRevision(config, scope, project.projectKey),
2104
+ roles: effective.entry.roles,
2105
+ roleMetadata: SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
2106
+ models,
2107
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [
2108
+ subagentLaunchSlotModelKey(model),
2109
+ supportedSubagentLaunchSlotThinkingLevels(model),
2110
+ ])),
2111
+ limits: SUBAGENT_LAUNCH_SLOT_LIMITS,
2112
+ thinkingLevels: SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS,
2113
+ reloadRequired: false,
2114
+ ...extra,
2115
+ };
2116
+ }
2117
+
2118
+ async function subagentLaunchSlotConfigData(tab, requestedScope) {
2119
+ const scope = requireSubagentLaunchSlotScope(requestedScope);
2120
+ const [settings, models, project] = await Promise.all([
2121
+ readWebuiSettings(),
2122
+ availableSubagentLaunchSlotModels(tab),
2123
+ subagentLaunchSlotProjectContext(tab),
2124
+ ]);
2125
+ return subagentLaunchSlotConfigPayload(settings, scope, project, models);
2126
+ }
2127
+
2128
+ async function saveSubagentLaunchSlotConfigData(tab, body = {}) {
2129
+ const scope = requireSubagentLaunchSlotScope(body.scope);
2130
+ const revision = typeof body.revision === "string" ? body.revision.trim() : "";
2131
+ if (!revision || revision.length > 128) throw makeHttpError(400, "revision is required");
2132
+ const inherit = body.inherit === true;
2133
+ if (inherit && scope !== "project") throw makeHttpError(400, "inherit is only supported for project scope");
2134
+
2135
+ const [models, project] = await Promise.all([
2136
+ availableSubagentLaunchSlotModels(tab),
2137
+ subagentLaunchSlotProjectContext(tab),
2138
+ ]);
2139
+ let roles;
2140
+ if (!inherit) {
2141
+ try {
2142
+ roles = validateSubagentLaunchSlotRoles(body.roles, models);
2143
+ } catch (error) {
2144
+ throw makeHttpError(400, error instanceof Error ? error.message : String(error));
2145
+ }
2146
+ }
2147
+
2148
+ let changed = false;
2149
+ const settings = await updateWebuiSettings((currentSettings) => {
2150
+ const config = normalizeSubagentLaunchSlots(currentSettings.subagentLaunchSlots);
2151
+ const currentRevision = subagentLaunchSlotRevision(config, scope, project.projectKey);
2152
+ if (currentRevision !== revision) {
2153
+ throw makeHttpError(409, "Subagent launch-slot configuration changed; reload it before saving.");
2154
+ }
2155
+
2156
+ const nextConfig = normalizeSubagentLaunchSlots(config);
2157
+ if (scope === "user") {
2158
+ nextConfig.user = { roles };
2159
+ } else if (inherit) {
2160
+ delete nextConfig.projects[project.projectKey];
2161
+ } else {
2162
+ nextConfig.projects[project.projectKey] = { roles };
2163
+ }
2164
+ const before = scope === "user" ? config.user : config.projects[project.projectKey] || null;
2165
+ const after = scope === "user" ? nextConfig.user : nextConfig.projects[project.projectKey] || null;
2166
+ changed = JSON.stringify(before) !== JSON.stringify(after);
2167
+ return changed ? { subagentLaunchSlots: nextConfig } : undefined;
2168
+ });
2169
+
2170
+ return subagentLaunchSlotConfigPayload(settings, scope, project, models, {
2171
+ saved: true,
2172
+ changed,
2173
+ reloadRequired: changed,
2174
+ });
2175
+ }
2176
+
2062
2177
  function gitWorkflowModelKey(model) {
2063
2178
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2064
2179
  }
@@ -7044,7 +7159,7 @@ async function readBundledThemes() {
7044
7159
  function normalizeStaticPath(urlPath) {
7045
7160
  if (urlPath === "/") return "index.html";
7046
7161
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7047
- if (!["index.html", "app.js", "fast-output-live.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7162
+ if (!["index.html", "app.js", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7048
7163
  return name;
7049
7164
  }
7050
7165
 
@@ -12207,6 +12322,20 @@ const server = createServer(async (req, res) => {
12207
12322
  return;
12208
12323
  }
12209
12324
 
12325
+ if (url.pathname === "/api/subagents/config" && req.method === "GET") {
12326
+ const tab = getRequestedTab(req, url);
12327
+ sendJson(res, 200, { ok: true, data: await subagentLaunchSlotConfigData(tab, url.searchParams.get("scope")) });
12328
+ return;
12329
+ }
12330
+
12331
+ if (url.pathname === "/api/subagents/config" && req.method === "POST") {
12332
+ requireLocalhostRoute(req, url.pathname);
12333
+ const body = await readJsonBody(req);
12334
+ const tab = getRequestedTab(req, url, body);
12335
+ sendJson(res, 200, { ok: true, data: await saveSubagentLaunchSlotConfigData(tab, body) });
12336
+ return;
12337
+ }
12338
+
12210
12339
  if (url.pathname === "/api/tabs" && req.method === "POST") {
12211
12340
  const body = await readJsonBody(req);
12212
12341
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -1,6 +1,7 @@
1
1
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
+ import { normalizeSubagentLaunchSlots } from "./subagent-launch-slots.mjs";
4
5
  import { normalizeOutputMode, OUTPUT_MODE_NORMAL } from "./webui-output-mode.mjs";
5
6
 
6
7
  export const GIT_WORKFLOW_SETUP_VERSION = 1;
@@ -25,6 +26,7 @@ export function supportedGitWorkflowThinkingLevels(model) {
25
26
 
26
27
  const WEBUI_SETTINGS_VERSION = 4;
27
28
  const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
29
+ const webuiSettingsUpdateQueues = new Map();
28
30
 
29
31
  function cleanBoundedString(value, maxLength = 512) {
30
32
  return typeof value === "string" ? value.trim().slice(0, maxLength) : "";
@@ -136,52 +138,112 @@ export function normalizeResourceDefaults(value) {
136
138
  };
137
139
  }
138
140
 
141
+ function settingsObject(value) {
142
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
143
+ }
144
+
145
+ function normalizedSettingsVersion(value) {
146
+ const stored = Number.isInteger(value?.version) ? value.version : 0;
147
+ return Math.max(WEBUI_SETTINGS_VERSION, stored, value?.subagentLaunchSlots !== undefined ? 5 : 0);
148
+ }
149
+
139
150
  export function normalizeWebuiSettings(value) {
151
+ const source = settingsObject(value);
140
152
  return {
141
- version: WEBUI_SETTINGS_VERSION,
142
- remoteAuthEnabled: value?.remoteAuthEnabled === true,
143
- outputModeDefault: normalizeOutputMode(value?.outputModeDefault, OUTPUT_MODE_NORMAL),
144
- gitWorkflow: normalizeGitWorkflowPreferences(value?.gitWorkflow),
145
- resourceDefaults: normalizeResourceDefaults(value?.resourceDefaults),
153
+ ...source,
154
+ version: normalizedSettingsVersion(source),
155
+ remoteAuthEnabled: source.remoteAuthEnabled === true,
156
+ outputModeDefault: normalizeOutputMode(source.outputModeDefault, OUTPUT_MODE_NORMAL),
157
+ gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
158
+ resourceDefaults: normalizeResourceDefaults(source.resourceDefaults),
159
+ subagentLaunchSlots: normalizeSubagentLaunchSlots(source.subagentLaunchSlots),
146
160
  };
147
161
  }
148
162
 
149
- export async function readWebuiSettings(storageFile = webuiSettingsFile(), { reportInvalidOutputMode = false } = {}) {
163
+ async function readRawWebuiSettings(storageFile) {
150
164
  try {
151
- const raw = JSON.parse(await readFile(storageFile, "utf8"));
152
- const normalized = normalizeWebuiSettings(raw);
153
- if (reportInvalidOutputMode && raw?.outputModeDefault !== undefined && normalized.outputModeDefault !== raw.outputModeDefault) {
154
- console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)} in ${storageFile}; using ${OUTPUT_MODE_NORMAL}.`);
155
- }
156
- return normalized;
165
+ return settingsObject(JSON.parse(await readFile(storageFile, "utf8")));
157
166
  } catch (error) {
158
- if (error?.code === "ENOENT") return normalizeWebuiSettings({});
167
+ if (error?.code === "ENOENT") return {};
159
168
  throw new Error(`Cannot read Pi Web UI settings at ${storageFile}: ${error instanceof Error ? error.message : String(error)}`);
160
169
  }
161
170
  }
162
171
 
163
- export async function writeWebuiSettings(patch, storageFile = webuiSettingsFile()) {
164
- const current = await readWebuiSettings(storageFile);
165
- const next = normalizeWebuiSettings({
166
- ...current,
167
- ...(patch || {}),
168
- gitWorkflow: patch?.gitWorkflow
169
- ? mergeGitWorkflowPreferences(current.gitWorkflow, patch.gitWorkflow)
172
+ export async function readWebuiSettings(storageFile = webuiSettingsFile(), { reportInvalidOutputMode = false } = {}) {
173
+ const raw = await readRawWebuiSettings(storageFile);
174
+ const normalized = normalizeWebuiSettings(raw);
175
+ if (reportInvalidOutputMode && raw.outputModeDefault !== undefined && normalized.outputModeDefault !== raw.outputModeDefault) {
176
+ console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)} in ${storageFile}; using ${OUTPUT_MODE_NORMAL}.`);
177
+ }
178
+ return normalized;
179
+ }
180
+
181
+ function mergeWebuiSettings(rawCurrent, patch) {
182
+ const raw = settingsObject(rawCurrent);
183
+ const current = normalizeWebuiSettings(raw);
184
+ const patchValue = settingsObject(patch);
185
+ const hasLaunchSlotPatch = Object.hasOwn(patchValue, "subagentLaunchSlots");
186
+ const persistLaunchSlots = raw.subagentLaunchSlots !== undefined || hasLaunchSlotPatch;
187
+ const source = {
188
+ ...raw,
189
+ ...patchValue,
190
+ gitWorkflow: patchValue.gitWorkflow
191
+ ? mergeGitWorkflowPreferences(current.gitWorkflow, patchValue.gitWorkflow)
170
192
  : current.gitWorkflow,
171
- resourceDefaults: patch?.resourceDefaults
193
+ resourceDefaults: patchValue.resourceDefaults
172
194
  ? {
173
195
  ...current.resourceDefaults,
174
- ...patch.resourceDefaults,
175
- tools: { ...current.resourceDefaults.tools, ...(patch.resourceDefaults.tools || {}) },
176
- skills: { ...current.resourceDefaults.skills, ...(patch.resourceDefaults.skills || {}) },
196
+ ...patchValue.resourceDefaults,
197
+ tools: { ...current.resourceDefaults.tools, ...(patchValue.resourceDefaults.tools || {}) },
198
+ skills: { ...current.resourceDefaults.skills, ...(patchValue.resourceDefaults.skills || {}) },
177
199
  }
178
200
  : current.resourceDefaults,
179
- });
201
+ };
202
+ if (persistLaunchSlots) {
203
+ source.subagentLaunchSlots = hasLaunchSlotPatch
204
+ ? normalizeSubagentLaunchSlots(patchValue.subagentLaunchSlots)
205
+ : normalizeSubagentLaunchSlots(raw.subagentLaunchSlots);
206
+ source.version = Math.max(5, Number.isInteger(raw.version) ? raw.version : 0);
207
+ } else {
208
+ delete source.subagentLaunchSlots;
209
+ source.version = Math.max(WEBUI_SETTINGS_VERSION, Number.isInteger(raw.version) ? raw.version : 0);
210
+ }
211
+ return { settings: normalizeWebuiSettings(source), persistLaunchSlots };
212
+ }
213
+
214
+ async function writeMergedWebuiSettings(rawCurrent, patch, storageFile) {
215
+ const { settings, persistLaunchSlots } = mergeWebuiSettings(rawCurrent, patch);
216
+ const persisted = { ...settings };
217
+ if (!persistLaunchSlots) delete persisted.subagentLaunchSlots;
180
218
  await mkdir(path.dirname(storageFile), { recursive: true });
181
219
  const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
182
- await writeFile(temporaryFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
220
+ await writeFile(temporaryFile, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });
183
221
  await rename(temporaryFile, storageFile);
184
- return next;
222
+ return settings;
223
+ }
224
+
225
+ /**
226
+ * Applies a settings patch against the latest on-disk snapshot and writes it
227
+ * atomically. Returning undefined from the updater avoids an unnecessary write.
228
+ */
229
+ export function updateWebuiSettings(updater, storageFile = webuiSettingsFile()) {
230
+ const queueKey = path.resolve(storageFile);
231
+ const previous = webuiSettingsUpdateQueues.get(queueKey) || Promise.resolve();
232
+ const currentUpdate = previous.catch(() => {}).then(async () => {
233
+ const rawCurrent = await readRawWebuiSettings(storageFile);
234
+ const current = normalizeWebuiSettings(rawCurrent);
235
+ const patch = await updater(current);
236
+ if (patch === undefined) return current;
237
+ return writeMergedWebuiSettings(rawCurrent, patch, storageFile);
238
+ });
239
+ webuiSettingsUpdateQueues.set(queueKey, currentUpdate);
240
+ return currentUpdate.finally(() => {
241
+ if (webuiSettingsUpdateQueues.get(queueKey) === currentUpdate) webuiSettingsUpdateQueues.delete(queueKey);
242
+ });
243
+ }
244
+
245
+ export async function writeWebuiSettings(patch, storageFile = webuiSettingsFile()) {
246
+ return updateWebuiSettings(() => patch, storageFile);
185
247
  }
186
248
 
187
249
  export async function readGitWorkflowPreferences(storageFile = webuiSettingsFile()) {
@@ -0,0 +1,304 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export const SUBAGENT_LAUNCH_SLOTS_VERSION = 1;
6
+ export const SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
7
+ export const SUBAGENT_LAUNCH_SLOT_LIMITS = Object.freeze({
8
+ slotsPerRole: 8,
9
+ totalSlots: 32,
10
+ slotIdLength: 160,
11
+ modelIdLength: 240,
12
+ });
13
+
14
+ export const SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG = Object.freeze([
15
+ { id: "context-builder", title: "Context builder", purpose: "Build focused context before delegation." },
16
+ { id: "delegate", title: "Delegate", purpose: "Coordinate scoped delegation work." },
17
+ { id: "oracle", title: "Oracle", purpose: "Resolve difficult design or implementation questions." },
18
+ { id: "planner", title: "Planner", purpose: "Plan implementation work and acceptance checks." },
19
+ { id: "researcher", title: "Researcher", purpose: "Research evidence and implementation options." },
20
+ { id: "reviewer", title: "Reviewer", purpose: "Review implementation quality and correctness." },
21
+ { id: "scout", title: "Scout", purpose: "Inspect repository context and constraints." },
22
+ { id: "worker", title: "Worker", purpose: "Implement an assigned workstream." },
23
+ ]);
24
+
25
+ const ROLE_IDS = new Set(SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG.map((role) => role.id));
26
+ const BASE_SLOT_IDS = new Set(SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG.map((role) => `${role.id}:base`));
27
+ const SLOT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:_-]*$/;
28
+ const THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/i;
29
+
30
+ function isPlainObject(value) {
31
+ return !!value && typeof value === "object" && !Array.isArray(value);
32
+ }
33
+
34
+ function exactString(value, maxLength) {
35
+ return typeof value === "string" && value.length <= maxLength && value.trim() === value ? value : "";
36
+ }
37
+
38
+ export function subagentLaunchSlotBaseId(roleId) {
39
+ return `${roleId}:base`;
40
+ }
41
+
42
+ export function subagentLaunchSlotModelKey(model) {
43
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
44
+ }
45
+
46
+ export function supportedSubagentLaunchSlotThinkingLevels(model) {
47
+ if (!model?.reasoning) return ["off"];
48
+ const mapping = isPlainObject(model.thinkingLevelMap) ? model.thinkingLevelMap : {};
49
+ return SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS.filter((level) => {
50
+ if (mapping[level] === null) return false;
51
+ if (["xhigh", "max"].includes(level)) return typeof mapping[level] === "string";
52
+ return true;
53
+ });
54
+ }
55
+
56
+ export function isCanonicalSubagentLaunchSlotModel(value) {
57
+ const model = exactString(value, SUBAGENT_LAUNCH_SLOT_LIMITS.modelIdLength);
58
+ if (!model || !model.includes("/") || /\s/.test(model) || THINKING_SUFFIX_PATTERN.test(model)) return false;
59
+ const [provider, ...idParts] = model.split("/");
60
+ return !!provider && idParts.join("/").length > 0;
61
+ }
62
+
63
+ function isSafeSlotId(value) {
64
+ const id = exactString(value, SUBAGENT_LAUNCH_SLOT_LIMITS.slotIdLength);
65
+ return !!id && SLOT_ID_PATTERN.test(id);
66
+ }
67
+
68
+ function normalizedSlot(value, fallbackId) {
69
+ const raw = isPlainObject(value) ? value : {};
70
+ const id = isSafeSlotId(raw.id) ? raw.id : fallbackId;
71
+ const model = isCanonicalSubagentLaunchSlotModel(raw.model) ? raw.model : null;
72
+ const thinking = SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS.includes(raw.thinking) ? raw.thinking : null;
73
+ return {
74
+ id,
75
+ model,
76
+ thinking: model ? thinking : null,
77
+ };
78
+ }
79
+
80
+ function normalizedRoleSlots(value, roleId) {
81
+ const baseId = subagentLaunchSlotBaseId(roleId);
82
+ const values = Array.isArray(value) ? value : [];
83
+ const slots = [];
84
+ const seen = new Set();
85
+ let base = null;
86
+
87
+ for (const value of values) {
88
+ const rawId = isPlainObject(value) && isSafeSlotId(value.id) ? value.id : "";
89
+ if (rawId === baseId && !base) base = normalizedSlot(value, baseId);
90
+ }
91
+ slots.push(base || normalizedSlot({}, baseId));
92
+ seen.add(baseId);
93
+
94
+ for (const value of values) {
95
+ const slot = normalizedSlot(value, "");
96
+ if (!slot.id || slot.id === baseId || BASE_SLOT_IDS.has(slot.id) || seen.has(slot.id)) continue;
97
+ if (slots.length >= SUBAGENT_LAUNCH_SLOT_LIMITS.slotsPerRole) break;
98
+ seen.add(slot.id);
99
+ slots.push(slot);
100
+ }
101
+ return slots;
102
+ }
103
+
104
+ export function defaultSubagentLaunchSlotRoles() {
105
+ return Object.fromEntries(SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG.map((role) => [
106
+ role.id,
107
+ [{ id: subagentLaunchSlotBaseId(role.id), model: null, thinking: null }],
108
+ ]));
109
+ }
110
+
111
+ export function normalizeSubagentLaunchSlotRoles(value) {
112
+ const rawRoles = isPlainObject(value) ? value : {};
113
+ const normalizedByRole = new Map(SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG.map((role) => [
114
+ role.id,
115
+ normalizedRoleSlots(rawRoles[role.id], role.id),
116
+ ]));
117
+ const roles = {};
118
+ const seen = new Set();
119
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
120
+ const base = normalizedByRole.get(role.id)[0];
121
+ roles[role.id] = [base];
122
+ seen.add(base.id);
123
+ }
124
+
125
+ let remaining = SUBAGENT_LAUNCH_SLOT_LIMITS.totalSlots - seen.size;
126
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
127
+ const slots = roles[role.id];
128
+ for (const slot of normalizedByRole.get(role.id).slice(1)) {
129
+ if (remaining <= 0 || seen.has(slot.id)) continue;
130
+ seen.add(slot.id);
131
+ remaining -= 1;
132
+ slots.push(slot);
133
+ }
134
+ }
135
+ return roles;
136
+ }
137
+
138
+ function normalizeScopeEntry(value) {
139
+ return { roles: normalizeSubagentLaunchSlotRoles(value?.roles) };
140
+ }
141
+
142
+ function isSafeProjectKey(value) {
143
+ return typeof value === "string"
144
+ && value.length > 0
145
+ && value.length <= 4096
146
+ && path.isAbsolute(value)
147
+ && !value.includes("\0");
148
+ }
149
+
150
+ export function normalizeSubagentLaunchSlots(value) {
151
+ const source = isPlainObject(value) ? value : {};
152
+ const projects = {};
153
+ if (isPlainObject(source.projects)) {
154
+ for (const projectKey of Object.keys(source.projects).sort()) {
155
+ if (!isSafeProjectKey(projectKey) || !isPlainObject(source.projects[projectKey])) continue;
156
+ projects[projectKey] = normalizeScopeEntry(source.projects[projectKey]);
157
+ }
158
+ }
159
+ return {
160
+ version: SUBAGENT_LAUNCH_SLOTS_VERSION,
161
+ user: normalizeScopeEntry(source.user),
162
+ projects,
163
+ };
164
+ }
165
+
166
+ export function subagentLaunchSlotScopeEntry(config, scope, projectKey) {
167
+ const normalized = normalizeSubagentLaunchSlots(config);
168
+ if (scope === "user") return { entry: normalized.user, inherited: false };
169
+ if (scope !== "project") throw new Error("scope must be user or project");
170
+ if (!isSafeProjectKey(projectKey)) throw new Error("projectKey must be an absolute canonical path");
171
+ const entry = normalized.projects[projectKey];
172
+ return { entry: entry || normalized.user, inherited: !entry };
173
+ }
174
+
175
+ function stableJson(value) {
176
+ if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
177
+ if (isPlainObject(value)) {
178
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
179
+ }
180
+ return JSON.stringify(value);
181
+ }
182
+
183
+ export function subagentLaunchSlotRevision(config, scope, projectKey) {
184
+ const normalized = normalizeSubagentLaunchSlots(config);
185
+ let revisionValue;
186
+ if (scope === "user") {
187
+ revisionValue = { scope: "user", entry: normalized.user };
188
+ } else if (scope === "project") {
189
+ if (!isSafeProjectKey(projectKey)) throw new Error("projectKey must be an absolute canonical path");
190
+ const projectEntry = normalized.projects[projectKey];
191
+ revisionValue = projectEntry
192
+ ? { scope: "project", projectKey, entry: projectEntry }
193
+ : { scope: "project", projectKey, inherited: true, user: normalized.user };
194
+ } else {
195
+ throw new Error("scope must be user or project");
196
+ }
197
+ return createHash("sha256").update(stableJson(revisionValue)).digest("hex");
198
+ }
199
+
200
+ export function validateSubagentLaunchSlotRoles(value, models = []) {
201
+ if (!isPlainObject(value)) throw new Error("roles must be an object");
202
+ const keys = Object.keys(value);
203
+ const unknown = keys.filter((key) => !ROLE_IDS.has(key));
204
+ if (unknown.length) throw new Error(`Unknown subagent role: ${unknown[0]}`);
205
+
206
+ const availableModels = new Map();
207
+ for (const model of Array.isArray(models) ? models : []) {
208
+ const key = subagentLaunchSlotModelKey(model);
209
+ if (key) availableModels.set(key, model);
210
+ }
211
+
212
+ const seenIds = new Set();
213
+ let totalSlots = 0;
214
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
215
+ const slots = value[role.id];
216
+ if (!Array.isArray(slots)) throw new Error(`${role.id} slots are required`);
217
+ if (slots.length < 1) throw new Error(`${role.id} requires its base slot`);
218
+ if (slots.length > SUBAGENT_LAUNCH_SLOT_LIMITS.slotsPerRole) {
219
+ throw new Error(`${role.id} is limited to ${SUBAGENT_LAUNCH_SLOT_LIMITS.slotsPerRole} slots`);
220
+ }
221
+ const baseId = subagentLaunchSlotBaseId(role.id);
222
+ if (slots.filter((slot) => slot?.id === baseId).length !== 1) {
223
+ throw new Error(`${role.id} requires exactly one base slot`);
224
+ }
225
+ for (const slot of slots) {
226
+ if (!isPlainObject(slot) || !isSafeSlotId(slot.id)) throw new Error(`${role.id} has an invalid slot id`);
227
+ if (seenIds.has(slot.id)) throw new Error(`Duplicate slot id: ${slot.id}`);
228
+ seenIds.add(slot.id);
229
+ totalSlots += 1;
230
+ if (totalSlots > SUBAGENT_LAUNCH_SLOT_LIMITS.totalSlots) {
231
+ throw new Error(`Launch slots are limited to ${SUBAGENT_LAUNCH_SLOT_LIMITS.totalSlots} total`);
232
+ }
233
+
234
+ if (slot.model !== null && !isCanonicalSubagentLaunchSlotModel(slot.model)) {
235
+ throw new Error(`${slot.id} has an invalid model`);
236
+ }
237
+ if (slot.thinking !== null && !SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS.includes(slot.thinking)) {
238
+ throw new Error(`${slot.id} has an unsupported thinking level`);
239
+ }
240
+ if (slot.model === null && slot.thinking !== null) {
241
+ throw new Error(`${slot.id} cannot set thinking while inheriting its model`);
242
+ }
243
+ if (slot.model) {
244
+ const model = availableModels.get(slot.model);
245
+ if (!model) throw new Error(`Selected model is not currently available: ${slot.model}`);
246
+ if (slot.thinking && !supportedSubagentLaunchSlotThinkingLevels(model).includes(slot.thinking)) {
247
+ throw new Error(`${slot.model} does not support thinking level ${slot.thinking}`);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ return normalizeSubagentLaunchSlotRoles(value);
253
+ }
254
+
255
+ export async function resolveSubagentLaunchSlotProjectKey(cwd) {
256
+ const fallback = path.resolve(String(cwd || process.cwd()));
257
+ let current;
258
+ try {
259
+ current = await realpath(fallback);
260
+ } catch {
261
+ return fallback;
262
+ }
263
+ const canonicalCwd = current;
264
+
265
+ while (true) {
266
+ for (const marker of [".pi", ".git"]) {
267
+ try {
268
+ await lstat(path.join(current, marker));
269
+ return current;
270
+ } catch (error) {
271
+ if (error?.code !== "ENOENT") throw error;
272
+ }
273
+ }
274
+ const parent = path.dirname(current);
275
+ if (parent === current) return canonicalCwd;
276
+ current = parent;
277
+ }
278
+ }
279
+
280
+ export function subagentLaunchSlotProjectLabel(projectKey) {
281
+ return path.basename(projectKey) || projectKey;
282
+ }
283
+
284
+ export function formatSubagentLaunchSlotGuidance(roles) {
285
+ const normalized = normalizeSubagentLaunchSlotRoles(roles);
286
+ const assignments = [];
287
+ for (const role of SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG) {
288
+ const slots = normalized[role.id];
289
+ if (!slots.some((slot) => slot.model)) continue;
290
+ for (const [index, slot] of slots.entries()) {
291
+ const model = slot.model
292
+ ? slot.thinking ? `${slot.model}:${slot.thinking}` : slot.model
293
+ : "<inherit; omit the model field>";
294
+ assignments.push(`- ${role.id} slot ${index + 1}: agent=${role.id} model=${model}`);
295
+ }
296
+ }
297
+ if (!assignments.length) return "";
298
+ return [
299
+ "## WebUI subagent launch slots",
300
+ "These are default model assignments for future delegation in this Pi tab. Explicit user instructions in the current request win.",
301
+ ...assignments.slice(0, SUBAGENT_LAUNCH_SLOT_LIMITS.totalSlots),
302
+ "When launching multiple slots of one role, create separate task entries so each model remains explicit; do not replace them with count when model specs differ.",
303
+ ].join("\n");
304
+ }
@@ -13,6 +13,7 @@ export const LOCALHOST_ONLY_POST_ROUTES = new Map([
13
13
  ["/api/network/open", "Opening to the network is only allowed from localhost"],
14
14
  ["/api/network/close", "Closing network access is only allowed from localhost"],
15
15
  ["/api/remote-auth/settings", "Remote PIN authentication settings are only allowed from localhost"],
16
+ ["/api/subagents/config", "Saving subagent launch-slot configuration is only allowed from localhost"],
16
17
  ["/api/recovery/plan", "Opening recovery plans is only allowed from localhost"],
17
18
  ["/api/restart", "Restart is only allowed from localhost"],
18
19
  ["/api/update", "Updating Pi from the Web UI is only allowed from localhost"],