@firstpick/pi-package-webui 0.9.2 → 0.9.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.
Files changed (77) hide show
  1. package/README.md +13 -7
  2. package/bin/pi-webui.mjs +256 -39
  3. package/index.ts +266 -1
  4. package/lib/git-workflow-preferences.mjs +8 -25
  5. package/lib/intercom-conversations.mjs +491 -0
  6. package/lib/intercom-transcript-filter.mjs +99 -0
  7. package/lib/resource-selection.mjs +140 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1025 -115
  10. package/public/index.html +31 -6
  11. package/public/service-worker.js +2 -1
  12. package/public/stream-output-controller.mjs +15 -0
  13. package/public/styles.css +394 -0
  14. package/public/syntax-highlight.mjs +622 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +34 -0
  17. package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
  18. package/tests/browser/persistent-ui-layout.spec.mjs +61 -0
  19. package/tests/browser/resource-profiles.spec.mjs +200 -0
  20. package/tests/browser/subagent-observability.spec.mjs +29 -0
  21. package/tests/codex-fast-mode-static.test.mjs +7 -6
  22. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  23. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  24. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  25. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  26. package/tests/control-deck-component-updates-static.test.mjs +4 -0
  27. package/tests/controls-layout-static.test.mjs +3 -3
  28. package/tests/fast-mode-client-static.test.mjs +2 -2
  29. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  30. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  31. package/tests/file-viewer-image-static.test.mjs +69 -0
  32. package/tests/fixtures/fake-pi.mjs +105 -6
  33. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  34. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  35. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  36. package/tests/git-workflow-preferences.test.mjs +4 -4
  37. package/tests/http-endpoints-harness.test.mjs +124 -2
  38. package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
  39. package/tests/intercom-conversations-http.test.mjs +252 -0
  40. package/tests/intercom-conversations.test.mjs +374 -0
  41. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  42. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  43. package/tests/intercom-transcript-filter.test.mjs +98 -0
  44. package/tests/main-output-loading-static.test.mjs +59 -0
  45. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  46. package/tests/mobile-compact-layout.test.mjs +2 -3
  47. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  48. package/tests/mobile-foundation-static.test.mjs +3 -3
  49. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  50. package/tests/mobile-static.test.mjs +63 -39
  51. package/tests/native-parity.test.mjs +8 -7
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  54. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  55. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  58. package/tests/resource-defaults-helper.test.mjs +60 -6
  59. package/tests/resource-selection.test.mjs +114 -0
  60. package/tests/resource-tui-extension.test.mjs +23 -0
  61. package/tests/session-sampling-ui-static.test.mjs +3 -3
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/stream-output-controller.test.mjs +8 -0
  64. package/tests/stream-output-isolation-static.test.mjs +2 -2
  65. package/tests/streaming-ui-coupling.test.mjs +5 -0
  66. package/tests/subagent-gate-visibility.test.mjs +1 -1
  67. package/tests/subagent-launch-slots.test.mjs +1 -1
  68. package/tests/subagent-observability-static.test.mjs +3 -3
  69. package/tests/subagent-reliability-integration.test.mjs +23 -1
  70. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  71. package/tests/subagents-helper.test.mjs +204 -1
  72. package/tests/syntax-highlight.test.mjs +235 -0
  73. package/tests/syntax-highlighting-static.test.mjs +84 -0
  74. package/tests/theme-customizer-static.test.mjs +5 -5
  75. package/tests/thinking-format-parser.test.mjs +64 -0
  76. package/tests/webui-settings-locking.test.mjs +1 -1
  77. package/webui-rpc-helper.mjs +291 -69
@@ -9,6 +9,10 @@ import {
9
9
  normalizeProviderSnapshot,
10
10
  } from "./lib/agent-run-protocol.mjs";
11
11
  import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
12
+ import {
13
+ branchResourceDirective,
14
+ resolveResourceSelection,
15
+ } from "./lib/resource-selection.mjs";
12
16
  import { mutatePiRuntimeFollowUpQueue } from "./lib/queue-mutation.mjs";
13
17
  import {
14
18
  formatSubagentLaunchSlotGuidance,
@@ -889,9 +893,16 @@ function parseSubagentStatusText(text, previousRuns = new Map()) {
889
893
  }
890
894
 
891
895
  export default function webuiRpcHelper(pi) {
896
+ let runtimeToolBaseline;
892
897
  let enabledTools = new Set();
893
898
  let disabledSkills = new Set();
894
899
  let inheritedEnabledSkills = null;
900
+ let toolsPinned = false;
901
+ let skillsPinned = false;
902
+ let toolSelectionSource = "runtime";
903
+ let skillSelectionSource = "runtime";
904
+ let resourceGeneration = 0;
905
+ let resourceRpcActive = false;
895
906
  let sessionSamplingParams = {};
896
907
  let subagentLaunchSlotGuidance = "";
897
908
  let subagentContext = null;
@@ -910,6 +921,8 @@ export default function webuiRpcHelper(pi) {
910
921
  const agentRunProviderSnapshots = new Map();
911
922
  const agentRunProviderDiagnostics = [];
912
923
  const helperAgentRunOutputSelections = new Map();
924
+ // Canonical projection key -> dismissed lifecycle end. Keeps duplicate providers from recreating cleared rows.
925
+ const dismissedHelperAgentRunProjections = new Map();
913
926
  const subagentStatusRequestsInFlight = new Set();
914
927
  const asyncSubagentRuns = new Map();
915
928
  const foregroundSubagentRuns = new Map();
@@ -924,6 +937,34 @@ export default function webuiRpcHelper(pi) {
924
937
  ];
925
938
  }
926
939
 
940
+ function helperAgentRunProjectionKey(instance) {
941
+ return `${instance?.parentSessionId || "external"}\0${instance?.instanceId || ""}`;
942
+ }
943
+
944
+ function rememberDismissedHelperAgentRunProjections(instances) {
945
+ for (const instance of instances) {
946
+ const key = helperAgentRunProjectionKey(instance);
947
+ if (!instance?.instanceId || dismissedHelperAgentRunProjections.has(key)) continue;
948
+ dismissedHelperAgentRunProjections.set(key, Number.isFinite(instance.endedAt) ? instance.endedAt : Number.isFinite(instance.startedAt) ? instance.startedAt : 0);
949
+ }
950
+ while (dismissedHelperAgentRunProjections.size > AGENT_RUN_INSTANCE_LIMIT) {
951
+ const oldest = dismissedHelperAgentRunProjections.keys().next().value;
952
+ if (oldest === undefined) break;
953
+ dismissedHelperAgentRunProjections.delete(oldest);
954
+ }
955
+ }
956
+
957
+ function helperAgentRunProjectionIsDismissed(instance) {
958
+ const key = helperAgentRunProjectionKey(instance);
959
+ if (!dismissedHelperAgentRunProjections.has(key)) return false;
960
+ const dismissedLifecycleEnd = dismissedHelperAgentRunProjections.get(key);
961
+ if (instance?.status === "running" && Number.isFinite(instance.startedAt) && instance.startedAt > dismissedLifecycleEnd) {
962
+ dismissedHelperAgentRunProjections.delete(key);
963
+ return false;
964
+ }
965
+ return true;
966
+ }
967
+
927
968
  function trimFinishedSubagentRuns() {
928
969
  const finished = ordinarySubagentRunEntries()
929
970
  .filter(({ run }) => run?.status && run.status !== "running")
@@ -1212,7 +1253,6 @@ export default function webuiRpcHelper(pi) {
1212
1253
  const launcher = gateRunIds.has(run.id) ? "gate" : workflow ? "workflow" : "pi-subagents";
1213
1254
  return (Array.isArray(run.agents) ? run.agents : []).map((agent) => {
1214
1255
  const status = canonicalAgentRunStatus(run.status, agent.status);
1215
- const openable = !recovered;
1216
1256
  return {
1217
1257
  version: 1,
1218
1258
  instanceId: canonicalAgentRunId(agent.id, `${canonicalRunId}-agent`),
@@ -1231,16 +1271,14 @@ export default function webuiRpcHelper(pi) {
1231
1271
  activityState: agent.activityState && CANONICAL_AGENT_RUN_ID_PATTERN.test(agent.activityState) ? agent.activityState : undefined,
1232
1272
  currentTool: agent.currentTool,
1233
1273
  capabilities: {
1234
- open: openable,
1235
- refresh: openable,
1236
- // Only the owning pi-subagents lifecycle keeps cancel authority in v1.
1274
+ open: true,
1275
+ refresh: true,
1276
+ // Aggregate fleet recovery grants a read-only metadata view, never lifecycle control.
1237
1277
  cancel: status === "running" && !workflow && !recovered && run.controllable !== false,
1238
1278
  steer: false,
1239
1279
  },
1240
- outputRef: openable
1241
- ? { kind: "helper", id: helperAgentRunOutputId(run.id, agent.id) }
1242
- : { kind: "none" },
1243
- _selection: openable ? { runId: run.id, agentId: agent.id } : null,
1280
+ outputRef: { kind: "helper", id: helperAgentRunOutputId(run.id, agent.id) },
1281
+ _selection: { runId: run.id, agentId: agent.id },
1244
1282
  };
1245
1283
  });
1246
1284
  }
@@ -1262,6 +1300,7 @@ export default function webuiRpcHelper(pi) {
1262
1300
  for (const run of runs) {
1263
1301
  for (const candidate of canonicalInstancesFromPublicRun(run, gateRunIds)) {
1264
1302
  const { _selection: selection, ...instance } = candidate;
1303
+ if (instance.status === "running") dismissedHelperAgentRunProjections.delete(helperAgentRunProjectionKey(instance));
1265
1304
  try {
1266
1305
  // The helper owns lifecycle and capabilities for the rows it observes directly.
1267
1306
  index.upsert(instance, { producerId: instance.provider, lifecycleOwner: true, capabilityOwner: true });
@@ -1278,6 +1317,7 @@ export default function webuiRpcHelper(pi) {
1278
1317
 
1279
1318
  for (const [producerId, rows] of agentRunProviderSnapshots) {
1280
1319
  for (const instance of rows.values()) {
1320
+ if (helperAgentRunProjectionIsDismissed(instance)) continue;
1281
1321
  try {
1282
1322
  // Foreign producers may enrich an existing instance but never seize ownership.
1283
1323
  index.upsert(instance, { producerId, lifecycleOwner: false, capabilityOwner: false });
@@ -1390,10 +1430,18 @@ export default function webuiRpcHelper(pi) {
1390
1430
  }
1391
1431
 
1392
1432
  function findTrackedSubagent(runId, agentId) {
1393
- const { run } = findTrackedSubagentRun(runId);
1394
- const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate?.id === agentId);
1395
- if (!agent) throw new Error(`Subagent not found: ${agentId}`);
1396
- return { run, agent };
1433
+ const entry = ordinarySubagentRunEntries().find((candidate) => candidate.run?.id === runId);
1434
+ if (entry) {
1435
+ const agent = (Array.isArray(entry.run.agents) ? entry.run.agents : []).find((candidate) => candidate?.id === agentId);
1436
+ if (!agent) throw new Error(`Subagent not found: ${agentId}`);
1437
+ return { run: entry.run, agent };
1438
+ }
1439
+ const recovered = [...recoveredSubagentRuns.values()].find((candidate) => candidate?.id === runId);
1440
+ if (recovered?.agent?.id !== agentId) throw new Error(`Subagent run not found: ${runId}`);
1441
+ return {
1442
+ run: { id: recovered.id, source: "recovered", mode: "single", status: "running", startedAt: recovered.startedAt, provisional: true, controllable: false },
1443
+ agent: { ...recovered.agent, status: "running", index: 0, nested: false },
1444
+ };
1397
1445
  }
1398
1446
 
1399
1447
  function findWorkflowSubagent(runId, agentId) {
@@ -1404,6 +1452,24 @@ export default function webuiRpcHelper(pi) {
1404
1452
  return { run, agent };
1405
1453
  }
1406
1454
 
1455
+ function claimRecoveredSubagentMatches(agents) {
1456
+ const available = [...recoveredSubagentRuns.entries()]
1457
+ .sort((left, right) => Number(left[1]?.startedAt || 0) - Number(right[1]?.startedAt || 0));
1458
+ return agents.map((agent) => {
1459
+ const name = subagentAgentName(agent?.name);
1460
+ const matchesName = (run) => run?.agent?.identity === name || run?.agent?.name === name;
1461
+ const exactModelIndex = available.findIndex(([, run]) => matchesName(run)
1462
+ && agent?.model && run.agent.model && agent.model === run.agent.model);
1463
+ const matchIndex = exactModelIndex >= 0
1464
+ ? exactModelIndex
1465
+ : available.findIndex(([, run]) => matchesName(run));
1466
+ if (matchIndex < 0) return undefined;
1467
+ const [[key, run]] = available.splice(matchIndex, 1);
1468
+ recoveredSubagentRuns.delete(key);
1469
+ return run;
1470
+ });
1471
+ }
1472
+
1407
1473
  function workflowSubagentOutputSnapshot(run, agent) {
1408
1474
  return {
1409
1475
  version: 1,
@@ -1484,6 +1550,55 @@ export default function webuiRpcHelper(pi) {
1484
1550
  }
1485
1551
  }
1486
1552
 
1553
+ function trackSubagentGateAttempts(gate) {
1554
+ for (const attempt of Array.isArray(gate?.attempts) ? gate.attempts : []) {
1555
+ const runId = subagentText(attempt?.runId, 160);
1556
+ const agentName = subagentAgentName(attempt?.agent);
1557
+ if (!runId || !agentName || attempt?.status !== "running") continue;
1558
+
1559
+ const [recovered] = claimRecoveredSubagentMatches([{ name: agentName, model: subagentModel(attempt?.model) || undefined }]);
1560
+ const existing = ordinarySubagentRunEntries().find((entry) => entry.run?.id === runId)?.run;
1561
+ if (existing) {
1562
+ if (recovered && Array.isArray(existing.agents) && existing.agents.length === 1) {
1563
+ const [agent] = existing.agents;
1564
+ Object.assign(agent, {
1565
+ model: agent.model || recovered.agent?.model,
1566
+ thinking: agent.thinking || recovered.agent?.thinking,
1567
+ });
1568
+ }
1569
+ continue;
1570
+ }
1571
+
1572
+ const startedAt = Number.isFinite(attempt?.startedAt)
1573
+ ? attempt.startedAt
1574
+ : Number.isFinite(recovered?.startedAt)
1575
+ ? recovered.startedAt
1576
+ : Date.now();
1577
+ const run = {
1578
+ id: runId,
1579
+ source: "async",
1580
+ mode: "single",
1581
+ status: "running",
1582
+ startedAt,
1583
+ eventSeenAt: Date.now(),
1584
+ agents: [{
1585
+ ...recovered?.agent,
1586
+ id: `${runId}:0:${agentName}`,
1587
+ name: agentName,
1588
+ status: "running",
1589
+ index: 0,
1590
+ model: subagentModel(attempt?.model) || recovered?.agent?.model,
1591
+ thinking: subagentThinkingFromModel(attempt?.model) || recovered?.agent?.thinking,
1592
+ nested: false,
1593
+ }],
1594
+ };
1595
+ asyncSubagentRuns.set(runId, run);
1596
+ void enrichAsyncSubagentRun(run).finally(() => {
1597
+ if (asyncSubagentRuns.get(runId) === run) publishSubagentStatus();
1598
+ });
1599
+ }
1600
+ }
1601
+
1487
1602
  function subagentOutputSnapshotFromAgent(run, agent, patch = {}) {
1488
1603
  const model = subagentModel(patch.model || agent.model) || undefined;
1489
1604
  const thinking = subagentThinking(patch.thinking || agent.thinking) || undefined;
@@ -1493,7 +1608,7 @@ export default function webuiRpcHelper(pi) {
1493
1608
  return {
1494
1609
  version: 1,
1495
1610
  runId: run.id,
1496
- source: run.source === "foreground" ? "foreground" : "async",
1611
+ source: ["foreground", "recovered"].includes(run.source) ? run.source : "async",
1497
1612
  mode: subagentMode(run.mode),
1498
1613
  startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
1499
1614
  updatedAt: Number.isFinite(patch.updatedAt) ? patch.updatedAt : Date.now(),
@@ -1516,6 +1631,8 @@ export default function webuiRpcHelper(pi) {
1516
1631
  recentTools: subagentRecentTools(patch.recentTools || agent.recentTools),
1517
1632
  recentOutput: subagentOutputLines(patch.recentOutput || agent.recentOutput),
1518
1633
  transcript: Array.isArray(patch.transcript) ? patch.transcript : [],
1634
+ unavailable: patch.unavailable === true || undefined,
1635
+ unavailableReason: patch.unavailable === true ? subagentText(patch.unavailableReason, 1000) || "Live output is unavailable for this recovered agent." : undefined,
1519
1636
  error: subagentText(patch.error, 1000) || undefined,
1520
1637
  },
1521
1638
  };
@@ -1542,6 +1659,12 @@ export default function webuiRpcHelper(pi) {
1542
1659
  const agentId = subagentText(payload.agentId, 240);
1543
1660
  if (!runId || !agentId) throw new Error("Subagent output requires runId and agentId");
1544
1661
  const { run, agent } = findTrackedSubagent(runId, agentId);
1662
+ if (run.source === "recovered") {
1663
+ return subagentOutputSnapshotFromAgent(run, agent, {
1664
+ unavailable: true,
1665
+ unavailableReason: "This active pi-subagents child was recovered from aggregate fleet metadata; detailed live output is unavailable until its run locator is observed.",
1666
+ });
1667
+ }
1545
1668
  if (run.source === "foreground") return subagentOutputSnapshotFromAgent(run, agent, { updatedAt: run.endedAt });
1546
1669
  if (run.status !== "running") {
1547
1670
  if (!agent.sessionFile && agent.asyncDir) {
@@ -1654,6 +1777,7 @@ export default function webuiRpcHelper(pi) {
1654
1777
  agent: {
1655
1778
  id: `fleet:${entry.key}:agent`,
1656
1779
  name: entry.name,
1780
+ identity: entry.agent,
1657
1781
  model: entry.model,
1658
1782
  thinking: entry.thinking,
1659
1783
  },
@@ -1802,12 +1926,18 @@ export default function webuiRpcHelper(pi) {
1802
1926
  pi.events.on(SUBAGENT_GATE_UPDATE_EVENT, (value) => {
1803
1927
  const id = subagentText(value?.id, 160);
1804
1928
  if (!id) return;
1805
- subagentGates.set(id, { ...value, id });
1929
+ const gate = { ...value, id };
1930
+ subagentGates.set(id, gate);
1931
+ trackSubagentGateAttempts(gate);
1806
1932
  while (subagentGates.size > 32) subagentGates.delete(subagentGates.keys().next().value);
1807
1933
  publishSubagentStatus();
1808
1934
  }),
1809
1935
  ].filter((unsubscribe) => typeof unsubscribe === "function");
1810
1936
 
1937
+ function runtimeTools() {
1938
+ return runtimeToolBaseline ??= normalizeNameList(pi.getActiveTools());
1939
+ }
1940
+
1811
1941
  function allToolNames() {
1812
1942
  return pi.getAllTools().map((tool) => tool.name);
1813
1943
  }
@@ -1879,12 +2009,7 @@ export default function webuiRpcHelper(pi) {
1879
2009
  }
1880
2010
 
1881
2011
  async function readGlobalResourceDefaults() {
1882
- try {
1883
- return (await readWebuiSettings()).resourceDefaults;
1884
- } catch (error) {
1885
- console.warn(`Web UI resource defaults could not be read: ${error instanceof Error ? error.message : String(error)}`);
1886
- return { tools: { enabledTools: null }, skills: { enabledSkills: null } };
1887
- }
2012
+ return (await readWebuiSettings()).resourceDefaults;
1888
2013
  }
1889
2014
 
1890
2015
  async function loadSubagentLaunchSlotGuidance(ctx) {
@@ -1899,8 +2024,10 @@ export default function webuiRpcHelper(pi) {
1899
2024
  }
1900
2025
  }
1901
2026
 
1902
- function persistToolsState() {
1903
- pi.appendEntry(TOOLS_CONFIG_TYPE, { enabledTools: [...enabledTools] });
2027
+ function persistToolsState(mode = "explicit") {
2028
+ pi.appendEntry(TOOLS_CONFIG_TYPE, mode === "inherit"
2029
+ ? { version: 2, mode: "inherit" }
2030
+ : { version: 2, mode: "explicit", enabledTools: [...enabledTools] });
1904
2031
  }
1905
2032
 
1906
2033
  function applyTools() {
@@ -1908,23 +2035,24 @@ export default function webuiRpcHelper(pi) {
1908
2035
  pi.setActiveTools([...enabledTools].filter((name) => existing.has(name)));
1909
2036
  }
1910
2037
 
1911
- function restoreToolsFromBranch(ctx, globalDefaults) {
1912
- const saved = lastBranchConfig(ctx, TOOLS_CONFIG_TYPE)?.enabledTools;
1913
- const inherited = globalDefaults?.tools?.enabledTools;
1914
- const selected = Array.isArray(saved) ? saved : inherited;
1915
- if (Array.isArray(selected)) {
1916
- const existing = new Set(allToolNames());
1917
- enabledTools = new Set(normalizeNameList(selected).filter((name) => existing.has(name)));
1918
- applyTools();
1919
- return;
1920
- }
1921
- enabledTools = new Set(pi.getActiveTools());
2038
+ function restoreToolsFromBranch(ctx, resourceDefaults, model = ctx.model) {
2039
+ const directive = branchResourceDirective(lastBranchConfig(ctx, TOOLS_CONFIG_TYPE), "tools");
2040
+ toolsPinned = directive.pinned;
2041
+ const baseline = runtimeTools();
2042
+ const resolved = directive.pinned
2043
+ ? { names: directive.names || [], source: "session" }
2044
+ : resolveResourceSelection(resourceDefaults, "tools", model?.provider, model?.id, baseline);
2045
+ enabledTools = new Set(resolved.names || baseline);
2046
+ toolSelectionSource = resolved.source;
2047
+ applyTools();
1922
2048
  }
1923
2049
 
1924
2050
  function toolState() {
1925
2051
  const active = new Set(pi.getActiveTools());
1926
- enabledTools = new Set([...active]);
1927
2052
  return {
2053
+ pinned: toolsPinned,
2054
+ source: toolSelectionSource,
2055
+ enabledTools: [...enabledTools],
1928
2056
  tools: pi.getAllTools().map((tool) => ({
1929
2057
  name: tool.name,
1930
2058
  description: tool.description || "",
@@ -1934,39 +2062,75 @@ export default function webuiRpcHelper(pi) {
1934
2062
  };
1935
2063
  }
1936
2064
 
1937
- function setToolState(payload) {
2065
+ async function setToolState(ctx, payload) {
2066
+ if (payload?.mode === "inherit") {
2067
+ persistToolsState("inherit");
2068
+ await recomputeResourceState(ctx);
2069
+ return toolState();
2070
+ }
1938
2071
  const existing = new Set(allToolNames());
1939
2072
  if (Array.isArray(payload.enabledTools)) {
1940
- enabledTools = new Set(normalizeNameList(payload.enabledTools).filter((name) => existing.has(name)));
2073
+ enabledTools = new Set(normalizeNameList(payload.enabledTools));
1941
2074
  } else if (Array.isArray(payload.disabledTools)) {
1942
2075
  const disabled = new Set(normalizeNameList(payload.disabledTools));
1943
2076
  enabledTools = new Set([...existing].filter((name) => !disabled.has(name)));
1944
2077
  } else {
1945
- throw new Error("Tool update requires enabledTools or disabledTools");
2078
+ throw new Error("Tool update requires enabledTools, disabledTools, or inherit mode");
1946
2079
  }
2080
+ toolsPinned = true;
2081
+ toolSelectionSource = "session";
1947
2082
  applyTools();
1948
2083
  persistToolsState();
1949
2084
  return toolState();
1950
2085
  }
1951
2086
 
1952
- function persistSkillsState() {
1953
- pi.appendEntry(SKILLS_CONFIG_TYPE, { disabledSkills: [...disabledSkills] });
2087
+ function persistSkillsState(mode = "explicit") {
2088
+ pi.appendEntry(SKILLS_CONFIG_TYPE, mode === "inherit"
2089
+ ? { version: 2, mode: "inherit" }
2090
+ : { version: 2, mode: "explicit", enabledSkills: [...(inheritedEnabledSkills || [])] });
1954
2091
  }
1955
2092
 
1956
2093
  function isSkillEnabled(name) {
1957
2094
  return inheritedEnabledSkills instanceof Set ? inheritedEnabledSkills.has(name) : !disabledSkills.has(name);
1958
2095
  }
1959
2096
 
1960
- function restoreSkillsFromBranch(ctx, globalDefaults) {
1961
- const saved = lastBranchConfig(ctx, SKILLS_CONFIG_TYPE)?.disabledSkills;
1962
- if (Array.isArray(saved)) {
2097
+ function restoreSkillsFromBranch(ctx, resourceDefaults, model = ctx.model) {
2098
+ const directive = branchResourceDirective(lastBranchConfig(ctx, SKILLS_CONFIG_TYPE), "skills");
2099
+ skillsPinned = directive.pinned;
2100
+ disabledSkills = new Set();
2101
+ if (directive.pinned && directive.legacyDisabledNames !== null) {
1963
2102
  inheritedEnabledSkills = null;
1964
- disabledSkills = new Set(normalizeNameList(saved));
2103
+ disabledSkills = new Set(directive.legacyDisabledNames);
2104
+ skillSelectionSource = "session";
1965
2105
  return;
1966
2106
  }
1967
- const inherited = globalDefaults?.skills?.enabledSkills;
1968
- inheritedEnabledSkills = Array.isArray(inherited) ? new Set(normalizeNameList(inherited)) : null;
1969
- disabledSkills = new Set();
2107
+ const resolved = directive.pinned
2108
+ ? { names: directive.names || [], source: "session" }
2109
+ : resolveResourceSelection(resourceDefaults, "skills", model?.provider, model?.id, null);
2110
+ inheritedEnabledSkills = resolved.names === null ? null : new Set(resolved.names);
2111
+ skillSelectionSource = resolved.source;
2112
+ }
2113
+
2114
+ function activeModelKey(model) {
2115
+ return model?.provider && model?.id ? `${model.provider}\0${model.id}` : "";
2116
+ }
2117
+
2118
+ async function recomputeResourceState(ctx, requestedModel = ctx.model) {
2119
+ if (ctx?.mode !== "rpc") return false;
2120
+ const generation = ++resourceGeneration;
2121
+ const requestedKey = activeModelKey(requestedModel);
2122
+ let resourceDefaults;
2123
+ try {
2124
+ resourceDefaults = await readGlobalResourceDefaults();
2125
+ } catch (error) {
2126
+ console.warn(`Web UI resource defaults could not be read; retaining the last safe resource state: ${error instanceof Error ? error.message : String(error)}`);
2127
+ ctx.ui?.notify?.("Resource defaults could not be read; tools and skills remain unchanged.", "error");
2128
+ return false;
2129
+ }
2130
+ if (generation !== resourceGeneration || activeModelKey(ctx.model) !== requestedKey) return false;
2131
+ restoreToolsFromBranch(ctx, resourceDefaults, requestedModel);
2132
+ restoreSkillsFromBranch(ctx, resourceDefaults, requestedModel);
2133
+ return true;
1970
2134
  }
1971
2135
 
1972
2136
  function skillsFromContext(ctx) {
@@ -1987,20 +2151,34 @@ export default function webuiRpcHelper(pi) {
1987
2151
  const known = new Set(skillsFromContext(ctx).map((skill) => skill.name));
1988
2152
  disabledSkills = new Set([...disabledSkills].filter((name) => known.has(name)));
1989
2153
  }
1990
- return { skills: skillsFromContext(ctx) };
2154
+ return {
2155
+ pinned: skillsPinned,
2156
+ source: skillSelectionSource,
2157
+ enabledSkills: inheritedEnabledSkills instanceof Set
2158
+ ? [...inheritedEnabledSkills]
2159
+ : skillsFromContext(ctx).filter((skill) => !disabledSkills.has(skill.name)).map((skill) => skill.name),
2160
+ skills: skillsFromContext(ctx),
2161
+ };
1991
2162
  }
1992
2163
 
1993
- function setSkillState(ctx, payload) {
2164
+ async function setSkillState(ctx, payload) {
2165
+ if (payload?.mode === "inherit") {
2166
+ persistSkillsState("inherit");
2167
+ await recomputeResourceState(ctx);
2168
+ return skillState(ctx);
2169
+ }
1994
2170
  const allNames = new Set(skillsFromContext(ctx).map((skill) => skill.name));
1995
- inheritedEnabledSkills = null;
1996
2171
  if (Array.isArray(payload.enabledSkills)) {
1997
- const enabled = new Set(normalizeNameList(payload.enabledSkills));
1998
- disabledSkills = new Set([...allNames].filter((name) => !enabled.has(name)));
2172
+ inheritedEnabledSkills = new Set(normalizeNameList(payload.enabledSkills));
1999
2173
  } else if (Array.isArray(payload.disabledSkills)) {
2000
- disabledSkills = new Set(normalizeNameList(payload.disabledSkills).filter((name) => allNames.has(name)));
2174
+ const disabled = new Set(normalizeNameList(payload.disabledSkills));
2175
+ inheritedEnabledSkills = new Set([...allNames].filter((name) => !disabled.has(name)));
2001
2176
  } else {
2002
- throw new Error("Skill update requires enabledSkills or disabledSkills");
2177
+ throw new Error("Skill update requires enabledSkills, disabledSkills, or inherit mode");
2003
2178
  }
2179
+ disabledSkills = new Set();
2180
+ skillsPinned = true;
2181
+ skillSelectionSource = "session";
2004
2182
  persistSkillsState();
2005
2183
  return skillState(ctx);
2006
2184
  }
@@ -2028,6 +2206,7 @@ export default function webuiRpcHelper(pi) {
2028
2206
  if (!runId) throw new Error("Subagent dismiss requires runId");
2029
2207
  const entry = findTrackedSubagentRun(runId);
2030
2208
  if (entry.run.status === "running") throw new Error(`Cannot dismiss running subagent run: ${runId}`);
2209
+ rememberDismissedHelperAgentRunProjections(canonicalInstancesFromPublicRun(entry.run, new Set()));
2031
2210
  entry.runs.delete(entry.key);
2032
2211
  persistRetainedSubagentRuns();
2033
2212
  publishSubagentStatus();
@@ -2070,13 +2249,21 @@ export default function webuiRpcHelper(pi) {
2070
2249
  async function executeAction(action, payload, ctx) {
2071
2250
  switch (action) {
2072
2251
  case "tools-state":
2252
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2073
2253
  return toolState();
2074
2254
  case "tools-set":
2075
- return setToolState(payload);
2255
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2256
+ return setToolState(ctx, payload);
2076
2257
  case "skills-state":
2258
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2077
2259
  return skillState(ctx);
2078
2260
  case "skills-set":
2261
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2079
2262
  return setSkillState(ctx, payload);
2263
+ case "resources-recompute":
2264
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2265
+ if (!(await recomputeResourceState(ctx))) throw new Error("Resource defaults could not be applied; current resources remain unchanged");
2266
+ return { tools: toolState(), skills: skillState(ctx) };
2080
2267
  case "sampling-state":
2081
2268
  return samplingState(ctx);
2082
2269
  case "sampling-set":
@@ -2116,9 +2303,11 @@ export default function webuiRpcHelper(pi) {
2116
2303
  });
2117
2304
 
2118
2305
  pi.on("session_start", async (_event, ctx) => {
2119
- const globalDefaults = await readGlobalResourceDefaults();
2120
- restoreToolsFromBranch(ctx, globalDefaults);
2121
- restoreSkillsFromBranch(ctx, globalDefaults);
2306
+ resourceRpcActive = ctx.mode === "rpc";
2307
+ if (resourceRpcActive) {
2308
+ if (runtimeToolBaseline === undefined) enabledTools = new Set(runtimeTools());
2309
+ await recomputeResourceState(ctx);
2310
+ }
2122
2311
  restoreSamplingParamsFromBranch(ctx);
2123
2312
  await loadSubagentLaunchSlotGuidance(ctx);
2124
2313
  subagentContext = ctx;
@@ -2138,9 +2327,8 @@ export default function webuiRpcHelper(pi) {
2138
2327
  });
2139
2328
 
2140
2329
  pi.on("session_tree", async (_event, ctx) => {
2141
- const globalDefaults = await readGlobalResourceDefaults();
2142
- restoreToolsFromBranch(ctx, globalDefaults);
2143
- restoreSkillsFromBranch(ctx, globalDefaults);
2330
+ resourceRpcActive = ctx.mode === "rpc";
2331
+ if (resourceRpcActive) await recomputeResourceState(ctx);
2144
2332
  restoreSamplingParamsFromBranch(ctx);
2145
2333
  subagentContext = ctx;
2146
2334
  subagentPollGeneration += 1;
@@ -2158,6 +2346,12 @@ export default function webuiRpcHelper(pi) {
2158
2346
  scheduleSubagentStatusPoll(subagentPollGeneration, 0);
2159
2347
  });
2160
2348
 
2349
+ pi.on("model_select", async (event, ctx) => {
2350
+ if (ctx.mode !== "rpc") return;
2351
+ resourceRpcActive = true;
2352
+ await recomputeResourceState(ctx, event.model);
2353
+ });
2354
+
2161
2355
  pi.on("tool_execution_start", (event, ctx) => {
2162
2356
  if (event.toolName !== "subagent" || event.args?.action) return;
2163
2357
  const id = subagentText(event.toolCallId, 160);
@@ -2193,11 +2387,36 @@ export default function webuiRpcHelper(pi) {
2193
2387
  pi.on("tool_execution_update", (event, ctx) => {
2194
2388
  if (event.toolName !== "subagent") return;
2195
2389
  const id = subagentText(event.toolCallId, 160);
2196
- const run = foregroundSubagentRuns.get(id);
2390
+ if (!id) return;
2391
+ const details = event.partialResult?.details || event.result?.details;
2392
+ const controlRunId = subagentText(details?.runId, 160);
2393
+ const agents = subagentRunningAgentsFromDetails(details, controlRunId || id);
2394
+ let run = foregroundSubagentRuns.get(id);
2395
+ if (!run && controlRunId && agents.length) {
2396
+ const recoveredMatches = claimRecoveredSubagentMatches(agents);
2397
+ const startedAt = recoveredMatches
2398
+ .map((match) => match?.startedAt)
2399
+ .filter(Number.isFinite)
2400
+ .sort((left, right) => left - right)[0];
2401
+ run = {
2402
+ id: controlRunId,
2403
+ source: "foreground",
2404
+ mode: subagentMode(details?.mode),
2405
+ status: "running",
2406
+ startedAt: Number.isFinite(startedAt) ? startedAt : Date.now(),
2407
+ controlRunId,
2408
+ workflowProvisional: false,
2409
+ agents: agents.map((agent, index) => ({
2410
+ ...recoveredMatches[index]?.agent,
2411
+ ...agent,
2412
+ model: agent.model || recoveredMatches[index]?.agent?.model,
2413
+ thinking: agent.thinking || recoveredMatches[index]?.agent?.thinking,
2414
+ })),
2415
+ };
2416
+ foregroundSubagentRuns.set(id, run);
2417
+ }
2197
2418
  if (!run || run.status !== "running") return;
2198
2419
  subagentContext = ctx;
2199
- const details = event.partialResult?.details || event.result?.details;
2200
- const agents = subagentRunningAgentsFromDetails(details, details?.runId || id);
2201
2420
  if (agents.length) {
2202
2421
  run.workflowProvisional = false;
2203
2422
  const runningAgents = agents.map((agent) => {
@@ -2215,9 +2434,9 @@ export default function webuiRpcHelper(pi) {
2215
2434
  .map((agent) => ({ ...agent, status: agent.status === "running" ? "done" : agent.status }));
2216
2435
  run.agents = [...completedAgents, ...runningAgents];
2217
2436
  }
2218
- if (details?.runId) {
2219
- run.controlRunId = subagentText(details.runId, 160);
2220
- run.id = run.controlRunId;
2437
+ if (controlRunId) {
2438
+ run.controlRunId = controlRunId;
2439
+ run.id = controlRunId;
2221
2440
  }
2222
2441
  run.mode = subagentMode(details?.mode, run.mode);
2223
2442
  publishSubagentStatus();
@@ -2234,6 +2453,8 @@ export default function webuiRpcHelper(pi) {
2234
2453
  });
2235
2454
 
2236
2455
  pi.on("session_shutdown", () => {
2456
+ resourceRpcActive = false;
2457
+ resourceGeneration += 1;
2237
2458
  subagentContext = null;
2238
2459
  subagentLaunchSlotGuidance = "";
2239
2460
  subagentPollGeneration += 1;
@@ -2257,6 +2478,7 @@ export default function webuiRpcHelper(pi) {
2257
2478
  });
2258
2479
 
2259
2480
  pi.on("input", async (event, ctx) => {
2481
+ if (!resourceRpcActive || ctx.mode !== "rpc") return { action: "continue" };
2260
2482
  const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
2261
2483
  if (!match) return { action: "continue" };
2262
2484
  const skillName = match[1];
@@ -2268,11 +2490,11 @@ export default function webuiRpcHelper(pi) {
2268
2490
  pi.on("before_agent_start", async (event) => {
2269
2491
  let nextPrompt = event.systemPrompt;
2270
2492
  let changed = false;
2271
- if (disabledSkills.size !== 0 || inheritedEnabledSkills !== null) {
2493
+ if (resourceRpcActive && (disabledSkills.size !== 0 || inheritedEnabledSkills !== null)) {
2272
2494
  const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
2273
2495
  const disabledNames = allSkills.filter((skill) => !isSkillEnabled(skill.name)).map((skill) => skill.name);
2274
- if (disabledNames.length) {
2275
- const filteredSkills = allSkills.filter((skill) => isSkillEnabled(skill.name));
2496
+ const filteredSkills = allSkills.filter((skill) => isSkillEnabled(skill.name) && skill.disableModelInvocation !== true);
2497
+ if (disabledNames.length || filteredSkills.length !== allSkills.length) {
2276
2498
  nextPrompt = replaceAvailableSkillsSection(nextPrompt, filteredSkills);
2277
2499
  for (const name of disabledNames) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
2278
2500
  changed = true;