@firstpick/pi-package-webui 0.9.1 → 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 (107) hide show
  1. package/README.md +31 -9
  2. package/bin/pi-webui-launcher.mjs +23 -12
  3. package/bin/pi-webui.mjs +729 -93
  4. package/index.ts +266 -1
  5. package/lib/agent-run-adapters.mjs +500 -0
  6. package/lib/agent-run-protocol.mjs +262 -0
  7. package/lib/agent-run-registry.mjs +339 -0
  8. package/lib/git-workflow-preferences.mjs +18 -28
  9. package/lib/intercom-conversations.mjs +491 -0
  10. package/lib/intercom-transcript-filter.mjs +99 -0
  11. package/lib/resource-selection.mjs +140 -0
  12. package/lib/trust-boundaries.mjs +2 -0
  13. package/lib/ui-layout-settings.mjs +172 -28
  14. package/lib/update/package-layout.mjs +50 -0
  15. package/lib/update/plan.mjs +11 -0
  16. package/package.json +2 -2
  17. package/public/app.js +2276 -419
  18. package/public/index.html +142 -72
  19. package/public/service-worker.js +2 -1
  20. package/public/stream-output-controller.mjs +15 -0
  21. package/public/styles.css +764 -92
  22. package/public/syntax-highlight.mjs +622 -0
  23. package/tests/agent-run-adapters.test.mjs +217 -0
  24. package/tests/agent-run-launcher.test.mjs +41 -0
  25. package/tests/agent-run-protocol.test.mjs +82 -0
  26. package/tests/agent-run-registry.test.mjs +102 -0
  27. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  28. package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
  29. package/tests/browser/controls-layout.spec.mjs +122 -0
  30. package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
  31. package/tests/browser/interaction-continuity.spec.mjs +161 -0
  32. package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
  33. package/tests/browser/mobile-foundation.spec.mjs +26 -0
  34. package/tests/browser/model-search-focus.spec.mjs +96 -0
  35. package/tests/browser/optimistic-prompt.spec.mjs +22 -0
  36. package/tests/browser/persistent-ui-layout.spec.mjs +285 -66
  37. package/tests/browser/resource-profiles.spec.mjs +200 -0
  38. package/tests/browser/subagent-observability.spec.mjs +116 -0
  39. package/tests/codex-fast-mode-static.test.mjs +7 -6
  40. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  41. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  42. package/tests/component-update-api-static.test.mjs +2 -1
  43. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  44. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  45. package/tests/control-deck-component-updates-static.test.mjs +6 -0
  46. package/tests/control-deck-side-panels-static.test.mjs +68 -0
  47. package/tests/controls-layout-static.test.mjs +22 -0
  48. package/tests/fast-mode-client-static.test.mjs +2 -2
  49. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  50. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  51. package/tests/file-tree-git-ignored-static.test.mjs +152 -0
  52. package/tests/file-tree-search-layout-static.test.mjs +2 -1
  53. package/tests/file-viewer-image-static.test.mjs +69 -0
  54. package/tests/fixtures/fake-pi.mjs +147 -12
  55. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  56. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  57. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  58. package/tests/git-workflow-preferences.test.mjs +55 -6
  59. package/tests/http-endpoints-harness.test.mjs +295 -14
  60. package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
  61. package/tests/intercom-conversations-http.test.mjs +252 -0
  62. package/tests/intercom-conversations.test.mjs +374 -0
  63. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  64. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  65. package/tests/intercom-transcript-filter.test.mjs +98 -0
  66. package/tests/main-output-loading-static.test.mjs +59 -0
  67. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  68. package/tests/mobile-compact-layout.test.mjs +2 -3
  69. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  70. package/tests/mobile-foundation-static.test.mjs +3 -3
  71. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  72. package/tests/mobile-static.test.mjs +76 -42
  73. package/tests/native-parity.test.mjs +8 -7
  74. package/tests/open-issue-wizard-static.test.mjs +2 -2
  75. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  76. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  77. package/tests/persistent-ui-layout-static.test.mjs +13 -13
  78. package/tests/questionnaire-dialog.test.mjs +3 -3
  79. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  80. package/tests/resource-defaults-helper.test.mjs +60 -6
  81. package/tests/resource-selection.test.mjs +114 -0
  82. package/tests/resource-tui-extension.test.mjs +23 -0
  83. package/tests/session-sampling-ui-static.test.mjs +3 -3
  84. package/tests/side-panel-context-menu-static.test.mjs +1 -1
  85. package/tests/side-panel-resize-static.test.mjs +26 -16
  86. package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
  87. package/tests/side-panel-section-reorder-static.test.mjs +16 -70
  88. package/tests/stream-output-controller.test.mjs +8 -0
  89. package/tests/stream-output-isolation-static.test.mjs +2 -2
  90. package/tests/streaming-ui-coupling.test.mjs +5 -0
  91. package/tests/subagent-gate-visibility.test.mjs +2 -1
  92. package/tests/subagent-launch-slots.test.mjs +1 -1
  93. package/tests/subagent-observability-static.test.mjs +32 -0
  94. package/tests/subagent-reliability-integration.test.mjs +183 -0
  95. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  96. package/tests/subagents-helper.test.mjs +548 -5
  97. package/tests/syntax-highlight.test.mjs +235 -0
  98. package/tests/syntax-highlighting-static.test.mjs +84 -0
  99. package/tests/terminal-tabs-resize-static.test.mjs +35 -0
  100. package/tests/theme-customizer-static.test.mjs +5 -5
  101. package/tests/thinking-format-parser.test.mjs +64 -0
  102. package/tests/ui-layout-settings.test.mjs +104 -32
  103. package/tests/update-api-harness.test.mjs +24 -10
  104. package/tests/update-package-layout.test.mjs +38 -0
  105. package/tests/update-plan.test.mjs +11 -1
  106. package/tests/webui-settings-locking.test.mjs +33 -3
  107. package/webui-rpc-helper.mjs +700 -89
@@ -1,7 +1,18 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ AGENT_RUN_PROVIDER_EVENT,
7
+ AgentRunIndex,
8
+ canonicalAgentRunId,
9
+ normalizeProviderSnapshot,
10
+ } from "./lib/agent-run-protocol.mjs";
4
11
  import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
12
+ import {
13
+ branchResourceDirective,
14
+ resolveResourceSelection,
15
+ } from "./lib/resource-selection.mjs";
5
16
  import { mutatePiRuntimeFollowUpQueue } from "./lib/queue-mutation.mjs";
6
17
  import {
7
18
  formatSubagentLaunchSlotGuidance,
@@ -31,6 +42,15 @@ const APP_RUNNER_CONTEXT_TYPE = "webui-app-runner-output";
31
42
  const RETAINED_SUBAGENT_RUNS_TYPE = "webui-subagent-retained-runs-v1";
32
43
  const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
33
44
  const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
45
+ // The helper and the HTTP server can be version-skewed across restarts, so the
46
+ // canonical payload travels on its own status key and never replaces the v1 key.
47
+ const WEBUI_SUBAGENTS_V2_STATUS_KEY = "webui-subagents-v2";
48
+ const WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V2 ";
49
+ const WEBUI_SUBAGENTS_V2_VERSION = 2;
50
+ const AGENT_RUN_PRODUCER_LIMIT = 16;
51
+ const AGENT_RUN_INSTANCE_LIMIT = 512;
52
+ const AGENT_RUN_DIAGNOSTIC_LIMIT = 16;
53
+ const AGENT_RUN_GATE_REFERENCE_LIMIT = 128;
34
54
  const SUBAGENT_RPC_VERSION = 1;
35
55
  const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
36
56
  const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
@@ -52,6 +72,8 @@ const WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS = {
52
72
  };
53
73
  const SUBAGENT_STATUS_POLL_MS = 1500;
54
74
  const SUBAGENT_STATUS_RPC_TIMEOUT_MS = 900;
75
+ const SUBAGENT_STATUS_HEARTBEAT_MS = 15_000;
76
+ const SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT = 2;
55
77
  const FINISHED_SUBAGENT_RUN_LIMIT = 16;
56
78
  const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
57
79
  const SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
@@ -266,6 +288,20 @@ function replaceAvailableSkillsSection(systemPrompt, skills) {
266
288
  return systemPrompt;
267
289
  }
268
290
 
291
+ const CANONICAL_AGENT_RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
292
+
293
+ /** Opaque helper-owned output handle. The browser never sees run/agent internals or paths. */
294
+ function helperAgentRunOutputId(runId, agentId) {
295
+ return `h-${createHash("sha256").update(`${runId}\u0000${agentId}`).digest("hex").slice(0, 32)}`;
296
+ }
297
+
298
+ function canonicalAgentRunStatus(runStatus, agentStatus) {
299
+ for (const candidate of [agentStatus, runStatus]) {
300
+ if (candidate === "cancelled" || candidate === "failed" || candidate === "done") return candidate;
301
+ }
302
+ return "running";
303
+ }
304
+
269
305
  function subagentText(value, maxLength = 240) {
270
306
  const text = String(value || "").trim();
271
307
  return text ? text.slice(0, maxLength) : "";
@@ -771,6 +807,32 @@ function subagentRunningGraphAgents(workflowGraph, runId) {
771
807
  return agents;
772
808
  }
773
809
 
810
+ function normalizeSubagentFleet(value) {
811
+ if (!value || typeof value !== "object" || value.version !== 1 || !Array.isArray(value.entries)) return undefined;
812
+ const totalActive = Number.isSafeInteger(value.totalActive) && value.totalActive >= 0 ? value.totalActive : -1;
813
+ const omitted = Number.isSafeInteger(value.omitted) && value.omitted >= 0 ? value.omitted : -1;
814
+ if (totalActive < value.entries.length || omitted !== totalActive - value.entries.length) return undefined;
815
+ const entries = [];
816
+ const keys = new Set();
817
+ for (const candidate of value.entries.slice(0, 32)) {
818
+ const key = subagentText(candidate?.key, 160);
819
+ const agent = subagentAgentName(candidate?.agent);
820
+ const startedAt = candidate?.startedAt;
821
+ if (!key || !agent || keys.has(key) || !Number.isSafeInteger(startedAt) || startedAt < 0) return undefined;
822
+ keys.add(key);
823
+ entries.push({
824
+ key,
825
+ agent,
826
+ name: subagentAgentName(candidate?.role) || agent,
827
+ model: subagentModel(candidate?.model) || undefined,
828
+ thinking: subagentThinking(candidate?.effort) || subagentThinkingFromModel(candidate?.model) || undefined,
829
+ startedAt,
830
+ });
831
+ }
832
+ if (entries.length !== value.entries.length) return undefined;
833
+ return { version: 1, entries, totalActive, omitted };
834
+ }
835
+
774
836
  function parseSubagentStatusText(text, previousRuns = new Map()) {
775
837
  const runs = [];
776
838
  let current = null;
@@ -831,21 +893,41 @@ function parseSubagentStatusText(text, previousRuns = new Map()) {
831
893
  }
832
894
 
833
895
  export default function webuiRpcHelper(pi) {
896
+ let runtimeToolBaseline;
834
897
  let enabledTools = new Set();
835
898
  let disabledSkills = new Set();
836
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;
837
906
  let sessionSamplingParams = {};
838
907
  let subagentLaunchSlotGuidance = "";
839
908
  let subagentContext = null;
840
909
  let subagentBridgeAvailable = false;
841
910
  let subagentPollTimer = null;
842
911
  let subagentPollGeneration = 0;
843
- let subagentStatusRequestInFlight = false;
912
+ let subagentPollSequence = 0;
913
+ let subagentAppliedPollSequence = 0;
914
+ let subagentFleetSummary = null;
844
915
  let lastPublishedSubagentSignature = "";
916
+ let lastPublishedSubagentAt = 0;
917
+ let lastPublishedAgentRunSignature = "";
918
+ let lastPublishedAgentRunAt = 0;
845
919
  let lastPersistedRetainedSubagentSignature = "";
920
+ // producerId -> Map<instanceId, canonical instance>. One producer never owns another's rows.
921
+ const agentRunProviderSnapshots = new Map();
922
+ const agentRunProviderDiagnostics = [];
923
+ const helperAgentRunOutputSelections = new Map();
924
+ // Canonical projection key -> dismissed lifecycle end. Keeps duplicate providers from recreating cleared rows.
925
+ const dismissedHelperAgentRunProjections = new Map();
926
+ const subagentStatusRequestsInFlight = new Set();
846
927
  const asyncSubagentRuns = new Map();
847
928
  const foregroundSubagentRuns = new Map();
848
929
  const workflowSubagentRuns = new Map();
930
+ const recoveredSubagentRuns = new Map();
849
931
  const subagentGates = new Map();
850
932
 
851
933
  function ordinarySubagentRunEntries() {
@@ -855,6 +937,34 @@ export default function webuiRpcHelper(pi) {
855
937
  ];
856
938
  }
857
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
+
858
968
  function trimFinishedSubagentRuns() {
859
969
  const finished = ordinarySubagentRunEntries()
860
970
  .filter(({ run }) => run?.status && run.status !== "running")
@@ -1025,7 +1135,25 @@ export default function webuiRpcHelper(pi) {
1025
1135
  nested: false,
1026
1136
  })),
1027
1137
  }));
1028
- return [...ordinaryRuns, ...workflowRuns]
1138
+ const recoveredRuns = [...recoveredSubagentRuns.values()].map((run) => ({
1139
+ id: run.id,
1140
+ source: "recovered",
1141
+ mode: "single",
1142
+ status: "running",
1143
+ startedAt: run.startedAt,
1144
+ provisional: true,
1145
+ controllable: false,
1146
+ agents: [{
1147
+ id: run.agent.id,
1148
+ name: run.agent.name,
1149
+ status: "running",
1150
+ index: 0,
1151
+ model: run.agent.model,
1152
+ thinking: run.agent.thinking,
1153
+ nested: false,
1154
+ }],
1155
+ }));
1156
+ return [...ordinaryRuns, ...workflowRuns, ...recoveredRuns]
1029
1157
  .filter((run) => run.id && (run.status !== "running" || run.agents.length > 0))
1030
1158
  .sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
1031
1159
  }
@@ -1067,21 +1195,206 @@ export default function webuiRpcHelper(pi) {
1067
1195
  .sort((left, right) => left.startedAt - right.startedAt || left.id.localeCompare(right.id));
1068
1196
  }
1069
1197
 
1070
- function publishSubagentStatus() {
1071
- if (!subagentContext?.hasUI) return;
1072
- const runs = publicSubagentRuns();
1073
- const gates = publicSubagentGates();
1074
- const snapshot = { version: 1, available: subagentBridgeAvailable, runs, gates };
1198
+ function resetCanonicalAgentRunState() {
1199
+ agentRunProviderSnapshots.clear();
1200
+ agentRunProviderDiagnostics.length = 0;
1201
+ helperAgentRunOutputSelections.clear();
1202
+ lastPublishedAgentRunSignature = "";
1203
+ lastPublishedAgentRunAt = 0;
1204
+ }
1205
+
1206
+ function recordAgentRunDiagnostic(code, producerId) {
1207
+ const entry = { code, ...(producerId ? { producerId: canonicalAgentRunId(producerId, "producer") } : {}) };
1208
+ const signature = JSON.stringify(entry);
1209
+ if (agentRunProviderDiagnostics.some((item) => JSON.stringify(item) === signature)) return;
1210
+ agentRunProviderDiagnostics.push(entry);
1211
+ while (agentRunProviderDiagnostics.length > AGENT_RUN_DIAGNOSTIC_LIMIT) agentRunProviderDiagnostics.shift();
1212
+ }
1213
+
1214
+ /**
1215
+ * Ingest one bounded process-local provider snapshot. A malformed or oversized
1216
+ * snapshot is dropped with a diagnostic and can never clear another producer's rows.
1217
+ */
1218
+ function ingestAgentRunProviderSnapshot(value) {
1219
+ let snapshot;
1220
+ try {
1221
+ snapshot = normalizeProviderSnapshot(value);
1222
+ } catch {
1223
+ recordAgentRunDiagnostic("invalid-provider-snapshot", value?.producerId);
1224
+ return false;
1225
+ }
1226
+ const existing = agentRunProviderSnapshots.get(snapshot.producerId);
1227
+ if (!existing && agentRunProviderSnapshots.size >= AGENT_RUN_PRODUCER_LIMIT) {
1228
+ recordAgentRunDiagnostic("producer-limit-reached", snapshot.producerId);
1229
+ return false;
1230
+ }
1231
+ const rows = snapshot.complete ? new Map() : new Map(existing || []);
1232
+ for (const instance of snapshot.instances) rows.set(instance.instanceId, instance);
1233
+ for (const removed of snapshot.removals) rows.delete(removed);
1234
+ if (rows.size) agentRunProviderSnapshots.set(snapshot.producerId, rows);
1235
+ else agentRunProviderSnapshots.delete(snapshot.producerId);
1236
+ return true;
1237
+ }
1238
+
1239
+ function canonicalInstancesFromPublicRun(run, gateRunIds) {
1240
+ const workflow = run.source === "workflow";
1241
+ const rawParentSessionId = subagentContext?.sessionManager?.getSessionId?.();
1242
+ const parentSessionId = rawParentSessionId ? canonicalAgentRunId(rawParentSessionId, "session") : null;
1243
+ const recovered = run.source === "recovered";
1244
+ const terminal = run.status !== "running";
1245
+ const startedAt = Number.isFinite(run.startedAt) ? run.startedAt : Date.now();
1246
+ // Unknown terminal time stays anchored to the stable start time instead of inventing
1247
+ // a fresh timestamp on every projection and defeating status deduplication.
1248
+ const endedAt = terminal ? Math.max(startedAt, Number.isFinite(run.endedAt) ? run.endedAt : startedAt) : null;
1249
+ // Projection signatures must stay stable between source changes; publication adds its own heartbeat timestamp.
1250
+ const updatedAt = terminal ? endedAt : startedAt;
1251
+ const canonicalRunId = canonicalAgentRunId(run.id, "run");
1252
+ // Gate launches stay one canonical child: the launch family changes, the count does not.
1253
+ const launcher = gateRunIds.has(run.id) ? "gate" : workflow ? "workflow" : "pi-subagents";
1254
+ return (Array.isArray(run.agents) ? run.agents : []).map((agent) => {
1255
+ const status = canonicalAgentRunStatus(run.status, agent.status);
1256
+ return {
1257
+ version: 1,
1258
+ instanceId: canonicalAgentRunId(agent.id, `${canonicalRunId}-agent`),
1259
+ runId: canonicalRunId,
1260
+ parentSessionId,
1261
+ launcher,
1262
+ provider: workflow ? "workflow-run" : "pi-subagents",
1263
+ origin: run.source,
1264
+ name: agent.name,
1265
+ status,
1266
+ startedAt,
1267
+ updatedAt,
1268
+ endedAt: ["done", "failed", "cancelled"].includes(status) ? endedAt : null,
1269
+ model: agent.model,
1270
+ thinking: agent.thinking,
1271
+ activityState: agent.activityState && CANONICAL_AGENT_RUN_ID_PATTERN.test(agent.activityState) ? agent.activityState : undefined,
1272
+ currentTool: agent.currentTool,
1273
+ capabilities: {
1274
+ open: true,
1275
+ refresh: true,
1276
+ // Aggregate fleet recovery grants a read-only metadata view, never lifecycle control.
1277
+ cancel: status === "running" && !workflow && !recovered && run.controllable !== false,
1278
+ steer: false,
1279
+ },
1280
+ outputRef: { kind: "helper", id: helperAgentRunOutputId(run.id, agent.id) },
1281
+ _selection: { runId: run.id, agentId: agent.id },
1282
+ };
1283
+ });
1284
+ }
1285
+
1286
+ /**
1287
+ * Canonical, deduplicated projection of every provider this helper observes.
1288
+ * Counts derive from canonical instance IDs only; gates and workflow containers
1289
+ * are references, never additional agents.
1290
+ */
1291
+ function canonicalAgentRunSnapshot(runs, gates) {
1292
+ const index = new AgentRunIndex();
1293
+ const selections = new Map();
1294
+ const gateRunIds = new Set();
1295
+ for (const gate of gates) {
1296
+ for (const attempt of gate.attempts) if (attempt.runId) gateRunIds.add(attempt.runId);
1297
+ }
1298
+
1299
+ const instanceIdByPublicRun = new Map();
1300
+ for (const run of runs) {
1301
+ for (const candidate of canonicalInstancesFromPublicRun(run, gateRunIds)) {
1302
+ const { _selection: selection, ...instance } = candidate;
1303
+ if (instance.status === "running") dismissedHelperAgentRunProjections.delete(helperAgentRunProjectionKey(instance));
1304
+ try {
1305
+ // The helper owns lifecycle and capabilities for the rows it observes directly.
1306
+ index.upsert(instance, { producerId: instance.provider, lifecycleOwner: true, capabilityOwner: true });
1307
+ } catch {
1308
+ recordAgentRunDiagnostic("invalid-helper-instance", instance.provider);
1309
+ continue;
1310
+ }
1311
+ if (selection) selections.set(instance.outputRef.id, selection);
1312
+ const known = instanceIdByPublicRun.get(run.id) || [];
1313
+ known.push(instance.instanceId);
1314
+ instanceIdByPublicRun.set(run.id, known);
1315
+ }
1316
+ }
1317
+
1318
+ for (const [producerId, rows] of agentRunProviderSnapshots) {
1319
+ for (const instance of rows.values()) {
1320
+ if (helperAgentRunProjectionIsDismissed(instance)) continue;
1321
+ try {
1322
+ // Foreign producers may enrich an existing instance but never seize ownership.
1323
+ index.upsert(instance, { producerId, lifecycleOwner: false, capabilityOwner: false });
1324
+ } catch {
1325
+ recordAgentRunDiagnostic("invalid-provider-instance", producerId);
1326
+ }
1327
+ }
1328
+ }
1329
+
1330
+ const gateReferences = [];
1331
+ for (const gate of gates) {
1332
+ for (const attempt of gate.attempts) {
1333
+ if (!attempt.runId || gateReferences.length >= AGENT_RUN_GATE_REFERENCE_LIMIT) continue;
1334
+ const instanceIds = instanceIdByPublicRun.get(attempt.runId) || [];
1335
+ gateReferences.push({
1336
+ gateId: gate.id,
1337
+ attemptId: attempt.id,
1338
+ runId: canonicalAgentRunId(attempt.runId, "run"),
1339
+ instanceIds,
1340
+ resolved: instanceIds.length > 0,
1341
+ });
1342
+ }
1343
+ }
1344
+
1345
+ helperAgentRunOutputSelections.clear();
1346
+ for (const [outputId, selection] of selections) helperAgentRunOutputSelections.set(outputId, selection);
1347
+
1348
+ return {
1349
+ instances: index.values().slice(0, AGENT_RUN_INSTANCE_LIMIT),
1350
+ gateReferences,
1351
+ producers: [...agentRunProviderSnapshots.keys()].slice(0, AGENT_RUN_PRODUCER_LIMIT),
1352
+ diagnostics: agentRunProviderDiagnostics.slice(-AGENT_RUN_DIAGNOSTIC_LIMIT),
1353
+ };
1354
+ }
1355
+
1356
+ function publishCanonicalAgentRunStatus(runs, gates, now) {
1357
+ const snapshot = { version: WEBUI_SUBAGENTS_V2_VERSION, available: subagentBridgeAvailable, ...canonicalAgentRunSnapshot(runs, gates) };
1358
+ const signature = JSON.stringify(snapshot);
1359
+ if (signature === lastPublishedAgentRunSignature && now - lastPublishedAgentRunAt < SUBAGENT_STATUS_HEARTBEAT_MS) return;
1360
+ try {
1361
+ subagentContext.ui.setStatus(WEBUI_SUBAGENTS_V2_STATUS_KEY, `${WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: now })}`);
1362
+ lastPublishedAgentRunSignature = signature;
1363
+ lastPublishedAgentRunAt = now;
1364
+ } catch {
1365
+ // Leave the signature uncommitted so a later poll or lifecycle event retries delivery.
1366
+ }
1367
+ }
1368
+
1369
+ function publishLegacySubagentStatus(snapshot, now) {
1075
1370
  const signature = JSON.stringify(snapshot);
1076
- if (signature === lastPublishedSubagentSignature) return;
1077
- lastPublishedSubagentSignature = signature;
1371
+ if (signature === lastPublishedSubagentSignature && now - lastPublishedSubagentAt < SUBAGENT_STATUS_HEARTBEAT_MS) return;
1078
1372
  try {
1079
- subagentContext.ui.setStatus(WEBUI_SUBAGENTS_STATUS_KEY, `${WEBUI_SUBAGENTS_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: Date.now() })}`);
1373
+ subagentContext.ui.setStatus(WEBUI_SUBAGENTS_STATUS_KEY, `${WEBUI_SUBAGENTS_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: now })}`);
1374
+ lastPublishedSubagentSignature = signature;
1375
+ lastPublishedSubagentAt = now;
1080
1376
  } catch {
1081
- // The old context may become stale while Pi replaces a session.
1377
+ // Leave the signature uncommitted so a later poll or lifecycle event retries delivery.
1082
1378
  }
1083
1379
  }
1084
1380
 
1381
+ function publishSubagentStatus() {
1382
+ if (!subagentContext?.hasUI) return;
1383
+ const runs = publicSubagentRuns();
1384
+ const gates = publicSubagentGates();
1385
+ const now = Date.now();
1386
+ // Both keys are published independently: an old server keeps consuming v1,
1387
+ // a new server prefers v2, and a failure on one key never suppresses the other.
1388
+ publishLegacySubagentStatus({
1389
+ version: 1,
1390
+ available: subagentBridgeAvailable,
1391
+ runs,
1392
+ gates,
1393
+ ...(subagentFleetSummary ? { fleet: subagentFleetSummary } : {}),
1394
+ }, now);
1395
+ publishCanonicalAgentRunStatus(runs, gates, now);
1396
+ }
1397
+
1085
1398
  function requestSubagentRpc(method, params = {}) {
1086
1399
  const requestId = `webui-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1087
1400
  return new Promise((resolve, reject) => {
@@ -1117,10 +1430,18 @@ export default function webuiRpcHelper(pi) {
1117
1430
  }
1118
1431
 
1119
1432
  function findTrackedSubagent(runId, agentId) {
1120
- const { run } = findTrackedSubagentRun(runId);
1121
- const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate?.id === agentId);
1122
- if (!agent) throw new Error(`Subagent not found: ${agentId}`);
1123
- 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
+ };
1124
1445
  }
1125
1446
 
1126
1447
  function findWorkflowSubagent(runId, agentId) {
@@ -1131,6 +1452,24 @@ export default function webuiRpcHelper(pi) {
1131
1452
  return { run, agent };
1132
1453
  }
1133
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
+
1134
1473
  function workflowSubagentOutputSnapshot(run, agent) {
1135
1474
  return {
1136
1475
  version: 1,
@@ -1211,6 +1550,55 @@ export default function webuiRpcHelper(pi) {
1211
1550
  }
1212
1551
  }
1213
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
+
1214
1602
  function subagentOutputSnapshotFromAgent(run, agent, patch = {}) {
1215
1603
  const model = subagentModel(patch.model || agent.model) || undefined;
1216
1604
  const thinking = subagentThinking(patch.thinking || agent.thinking) || undefined;
@@ -1220,7 +1608,7 @@ export default function webuiRpcHelper(pi) {
1220
1608
  return {
1221
1609
  version: 1,
1222
1610
  runId: run.id,
1223
- source: run.source === "foreground" ? "foreground" : "async",
1611
+ source: ["foreground", "recovered"].includes(run.source) ? run.source : "async",
1224
1612
  mode: subagentMode(run.mode),
1225
1613
  startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
1226
1614
  updatedAt: Number.isFinite(patch.updatedAt) ? patch.updatedAt : Date.now(),
@@ -1243,12 +1631,23 @@ export default function webuiRpcHelper(pi) {
1243
1631
  recentTools: subagentRecentTools(patch.recentTools || agent.recentTools),
1244
1632
  recentOutput: subagentOutputLines(patch.recentOutput || agent.recentOutput),
1245
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,
1246
1636
  error: subagentText(patch.error, 1000) || undefined,
1247
1637
  },
1248
1638
  };
1249
1639
  }
1250
1640
 
1251
1641
  async function subagentOutputSnapshot(payload = {}) {
1642
+ // Opaque helper-owned handles resolve to an internal selection here; the browser
1643
+ // never supplies a run/agent path or an arbitrary locator.
1644
+ const outputId = subagentText(payload.outputId, 160);
1645
+ if (outputId) {
1646
+ const selection = helperAgentRunOutputSelections.get(outputId);
1647
+ if (!selection) throw new Error("Subagent output handle is no longer tracked");
1648
+ return subagentOutputSnapshot({ runId: selection.runId, agentId: selection.agentId });
1649
+ }
1650
+
1252
1651
  const workflowRunId = workflowSubagentIdentifier(payload.runId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.runIdentifierLength);
1253
1652
  const workflowAgentId = workflowSubagentIdentifier(payload.agentId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.agentIdentifierLength);
1254
1653
  if (workflowRunId && workflowAgentId) {
@@ -1260,6 +1659,12 @@ export default function webuiRpcHelper(pi) {
1260
1659
  const agentId = subagentText(payload.agentId, 240);
1261
1660
  if (!runId || !agentId) throw new Error("Subagent output requires runId and agentId");
1262
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
+ }
1263
1668
  if (run.source === "foreground") return subagentOutputSnapshotFromAgent(run, agent, { updatedAt: run.endedAt });
1264
1669
  if (run.status !== "running") {
1265
1670
  if (!agent.sessionFile && agent.asyncDir) {
@@ -1330,19 +1735,74 @@ export default function webuiRpcHelper(pi) {
1330
1735
  }
1331
1736
  }
1332
1737
 
1333
- async function refreshSubagentStatus() {
1334
- if (subagentStatusRequestInFlight) return;
1335
- subagentStatusRequestInFlight = true;
1738
+ function reconcileSubagentFleet(fleet, parsedIds) {
1739
+ subagentFleetSummary = fleet ? { version: 1, totalActive: fleet.totalActive, omitted: fleet.omitted } : null;
1740
+ if (!fleet) return new Set();
1741
+ const slots = [];
1742
+ const addSlots = (runs, priority) => {
1743
+ for (const run of runs) {
1744
+ if (run?.status !== "running") continue;
1745
+ for (const agent of Array.isArray(run.agents) ? run.agents : []) {
1746
+ if (agent?.status !== "running" || !subagentAgentName(agent.name)) continue;
1747
+ slots.push({ run, agent, priority: parsedIds.has(run.id) ? 0 : priority, claimed: false });
1748
+ }
1749
+ }
1750
+ };
1751
+ addSlots(asyncSubagentRuns.values(), 1);
1752
+ addSlots(foregroundSubagentRuns.values(), 2);
1753
+ slots.sort((left, right) => left.priority - right.priority);
1754
+
1755
+ const matchedRunIds = new Set();
1756
+ const unmatched = [];
1757
+ for (const entry of fleet.entries) {
1758
+ const slot = slots.find((candidate) => !candidate.claimed && candidate.agent.name === entry.agent);
1759
+ if (!slot) {
1760
+ unmatched.push(entry);
1761
+ continue;
1762
+ }
1763
+ slot.claimed = true;
1764
+ matchedRunIds.add(slot.run.id);
1765
+ recoveredSubagentRuns.delete(entry.key);
1766
+ }
1767
+
1768
+ const unmatchedKeys = new Set(unmatched.map((entry) => entry.key));
1769
+ for (const entry of unmatched) {
1770
+ const previous = recoveredSubagentRuns.get(entry.key);
1771
+ recoveredSubagentRuns.set(entry.key, {
1772
+ ...previous,
1773
+ id: `fleet:${entry.key}`,
1774
+ startedAt: entry.startedAt,
1775
+ absenceGeneration: subagentPollGeneration,
1776
+ absenceCount: 0,
1777
+ agent: {
1778
+ id: `fleet:${entry.key}:agent`,
1779
+ name: entry.name,
1780
+ identity: entry.agent,
1781
+ model: entry.model,
1782
+ thinking: entry.thinking,
1783
+ },
1784
+ });
1785
+ }
1786
+ if (fleet.omitted === 0) {
1787
+ for (const [key, run] of recoveredSubagentRuns) {
1788
+ if (unmatchedKeys.has(key)) continue;
1789
+ const count = run.absenceGeneration === subagentPollGeneration ? Number(run.absenceCount || 0) + 1 : 1;
1790
+ if (count >= SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT) recoveredSubagentRuns.delete(key);
1791
+ else Object.assign(run, { absenceGeneration: subagentPollGeneration, absenceCount: count });
1792
+ }
1793
+ }
1794
+ return matchedRunIds;
1795
+ }
1796
+
1797
+ async function refreshSubagentStatus(generation = subagentPollGeneration) {
1798
+ if (generation !== subagentPollGeneration || subagentStatusRequestsInFlight.has(generation)) return;
1799
+ const sequence = ++subagentPollSequence;
1800
+ subagentStatusRequestsInFlight.add(generation);
1336
1801
  try {
1337
1802
  const data = await requestSubagentStatus();
1338
- subagentBridgeAvailable = true;
1803
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1339
1804
  const parsedRuns = parseSubagentStatusText(data?.text, asyncSubagentRuns);
1340
- const nextIds = new Set(parsedRuns.map((run) => run.id));
1341
- for (const run of asyncSubagentRuns.values()) {
1342
- if (run?.status === "running" && !nextIds.has(run.id) && Date.now() - Number(run.eventSeenAt || 0) > SUBAGENT_STATUS_POLL_MS * 2) {
1343
- finishSubagentRun(run, "done");
1344
- }
1345
- }
1805
+ const nextRuns = [];
1346
1806
  for (const run of parsedRuns) {
1347
1807
  const previous = asyncSubagentRuns.get(run.id);
1348
1808
  if (previous?.status && previous.status !== "running") continue;
@@ -1359,16 +1819,39 @@ export default function webuiRpcHelper(pi) {
1359
1819
  ...previous,
1360
1820
  ...run,
1361
1821
  eventSeenAt: previous?.eventSeenAt || Date.now(),
1822
+ authoritativeAbsenceGeneration: generation,
1823
+ authoritativeAbsenceCount: 0,
1362
1824
  agents: [...completedAgents, ...runningAgents],
1363
1825
  };
1364
1826
  await enrichAsyncSubagentRun(merged);
1365
- asyncSubagentRuns.set(run.id, merged);
1827
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1828
+ nextRuns.push(merged);
1829
+ }
1830
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1831
+ subagentAppliedPollSequence = sequence;
1832
+ subagentBridgeAvailable = true;
1833
+ for (const run of nextRuns) asyncSubagentRuns.set(run.id, run);
1834
+ const nextIds = new Set(nextRuns.map((run) => run.id));
1835
+ const fleet = normalizeSubagentFleet(data?.fleet);
1836
+ const fleetRunIds = reconcileSubagentFleet(fleet, nextIds);
1837
+ for (const run of asyncSubagentRuns.values()) {
1838
+ if (run?.status !== "running") continue;
1839
+ if (nextIds.has(run.id) || fleetRunIds.has(run.id)) {
1840
+ run.authoritativeAbsenceGeneration = generation;
1841
+ run.authoritativeAbsenceCount = 0;
1842
+ continue;
1843
+ }
1844
+ if (!fleet || fleet.omitted !== 0) continue;
1845
+ const count = run.authoritativeAbsenceGeneration === generation ? Number(run.authoritativeAbsenceCount || 0) + 1 : 1;
1846
+ run.authoritativeAbsenceGeneration = generation;
1847
+ run.authoritativeAbsenceCount = count;
1848
+ if (count >= SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT) finishSubagentRun(run, "done");
1366
1849
  }
1367
- publishSubagentStatus();
1368
1850
  } catch {
1369
1851
  // The optional pi-subagents extension may not be loaded in this tab.
1370
1852
  } finally {
1371
- subagentStatusRequestInFlight = false;
1853
+ subagentStatusRequestsInFlight.delete(generation);
1854
+ if (generation === subagentPollGeneration) publishSubagentStatus();
1372
1855
  }
1373
1856
  }
1374
1857
 
@@ -1376,7 +1859,7 @@ export default function webuiRpcHelper(pi) {
1376
1859
  clearTimeout(subagentPollTimer);
1377
1860
  subagentPollTimer = setTimeout(async () => {
1378
1861
  if (generation !== subagentPollGeneration || !subagentContext) return;
1379
- await refreshSubagentStatus();
1862
+ await refreshSubagentStatus(generation);
1380
1863
  scheduleSubagentStatusPoll(generation);
1381
1864
  }, delay);
1382
1865
  subagentPollTimer.unref?.();
@@ -1394,10 +1877,17 @@ export default function webuiRpcHelper(pi) {
1394
1877
  // Ignore malformed cross-extension events without disrupting current live rows.
1395
1878
  }
1396
1879
  }),
1880
+ pi.events.on(AGENT_RUN_PROVIDER_EVENT, (value) => {
1881
+ // Generic process-local producers: bounded, validated, and producer-scoped.
1882
+ // Rejected snapshots still publish so their bounded diagnostic becomes visible;
1883
+ // repeated identical failures collapse into one deduplicated entry.
1884
+ ingestAgentRunProviderSnapshot(value);
1885
+ publishSubagentStatus();
1886
+ }),
1397
1887
  pi.events.on(SUBAGENT_RPC_READY_EVENT, () => {
1398
1888
  subagentBridgeAvailable = true;
1399
1889
  publishSubagentStatus();
1400
- void refreshSubagentStatus();
1890
+ void refreshSubagentStatus(subagentPollGeneration);
1401
1891
  }),
1402
1892
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (value) => {
1403
1893
  const info = value && typeof value === "object" ? value : {};
@@ -1436,12 +1926,18 @@ export default function webuiRpcHelper(pi) {
1436
1926
  pi.events.on(SUBAGENT_GATE_UPDATE_EVENT, (value) => {
1437
1927
  const id = subagentText(value?.id, 160);
1438
1928
  if (!id) return;
1439
- subagentGates.set(id, { ...value, id });
1929
+ const gate = { ...value, id };
1930
+ subagentGates.set(id, gate);
1931
+ trackSubagentGateAttempts(gate);
1440
1932
  while (subagentGates.size > 32) subagentGates.delete(subagentGates.keys().next().value);
1441
1933
  publishSubagentStatus();
1442
1934
  }),
1443
1935
  ].filter((unsubscribe) => typeof unsubscribe === "function");
1444
1936
 
1937
+ function runtimeTools() {
1938
+ return runtimeToolBaseline ??= normalizeNameList(pi.getActiveTools());
1939
+ }
1940
+
1445
1941
  function allToolNames() {
1446
1942
  return pi.getAllTools().map((tool) => tool.name);
1447
1943
  }
@@ -1513,12 +2009,7 @@ export default function webuiRpcHelper(pi) {
1513
2009
  }
1514
2010
 
1515
2011
  async function readGlobalResourceDefaults() {
1516
- try {
1517
- return (await readWebuiSettings()).resourceDefaults;
1518
- } catch (error) {
1519
- console.warn(`Web UI resource defaults could not be read: ${error instanceof Error ? error.message : String(error)}`);
1520
- return { tools: { enabledTools: null }, skills: { enabledSkills: null } };
1521
- }
2012
+ return (await readWebuiSettings()).resourceDefaults;
1522
2013
  }
1523
2014
 
1524
2015
  async function loadSubagentLaunchSlotGuidance(ctx) {
@@ -1533,8 +2024,10 @@ export default function webuiRpcHelper(pi) {
1533
2024
  }
1534
2025
  }
1535
2026
 
1536
- function persistToolsState() {
1537
- 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] });
1538
2031
  }
1539
2032
 
1540
2033
  function applyTools() {
@@ -1542,23 +2035,24 @@ export default function webuiRpcHelper(pi) {
1542
2035
  pi.setActiveTools([...enabledTools].filter((name) => existing.has(name)));
1543
2036
  }
1544
2037
 
1545
- function restoreToolsFromBranch(ctx, globalDefaults) {
1546
- const saved = lastBranchConfig(ctx, TOOLS_CONFIG_TYPE)?.enabledTools;
1547
- const inherited = globalDefaults?.tools?.enabledTools;
1548
- const selected = Array.isArray(saved) ? saved : inherited;
1549
- if (Array.isArray(selected)) {
1550
- const existing = new Set(allToolNames());
1551
- enabledTools = new Set(normalizeNameList(selected).filter((name) => existing.has(name)));
1552
- applyTools();
1553
- return;
1554
- }
1555
- 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();
1556
2048
  }
1557
2049
 
1558
2050
  function toolState() {
1559
2051
  const active = new Set(pi.getActiveTools());
1560
- enabledTools = new Set([...active]);
1561
2052
  return {
2053
+ pinned: toolsPinned,
2054
+ source: toolSelectionSource,
2055
+ enabledTools: [...enabledTools],
1562
2056
  tools: pi.getAllTools().map((tool) => ({
1563
2057
  name: tool.name,
1564
2058
  description: tool.description || "",
@@ -1568,39 +2062,75 @@ export default function webuiRpcHelper(pi) {
1568
2062
  };
1569
2063
  }
1570
2064
 
1571
- 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
+ }
1572
2071
  const existing = new Set(allToolNames());
1573
2072
  if (Array.isArray(payload.enabledTools)) {
1574
- enabledTools = new Set(normalizeNameList(payload.enabledTools).filter((name) => existing.has(name)));
2073
+ enabledTools = new Set(normalizeNameList(payload.enabledTools));
1575
2074
  } else if (Array.isArray(payload.disabledTools)) {
1576
2075
  const disabled = new Set(normalizeNameList(payload.disabledTools));
1577
2076
  enabledTools = new Set([...existing].filter((name) => !disabled.has(name)));
1578
2077
  } else {
1579
- throw new Error("Tool update requires enabledTools or disabledTools");
2078
+ throw new Error("Tool update requires enabledTools, disabledTools, or inherit mode");
1580
2079
  }
2080
+ toolsPinned = true;
2081
+ toolSelectionSource = "session";
1581
2082
  applyTools();
1582
2083
  persistToolsState();
1583
2084
  return toolState();
1584
2085
  }
1585
2086
 
1586
- function persistSkillsState() {
1587
- 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 || [])] });
1588
2091
  }
1589
2092
 
1590
2093
  function isSkillEnabled(name) {
1591
2094
  return inheritedEnabledSkills instanceof Set ? inheritedEnabledSkills.has(name) : !disabledSkills.has(name);
1592
2095
  }
1593
2096
 
1594
- function restoreSkillsFromBranch(ctx, globalDefaults) {
1595
- const saved = lastBranchConfig(ctx, SKILLS_CONFIG_TYPE)?.disabledSkills;
1596
- 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) {
1597
2102
  inheritedEnabledSkills = null;
1598
- disabledSkills = new Set(normalizeNameList(saved));
2103
+ disabledSkills = new Set(directive.legacyDisabledNames);
2104
+ skillSelectionSource = "session";
1599
2105
  return;
1600
2106
  }
1601
- const inherited = globalDefaults?.skills?.enabledSkills;
1602
- inheritedEnabledSkills = Array.isArray(inherited) ? new Set(normalizeNameList(inherited)) : null;
1603
- 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;
1604
2134
  }
1605
2135
 
1606
2136
  function skillsFromContext(ctx) {
@@ -1621,20 +2151,34 @@ export default function webuiRpcHelper(pi) {
1621
2151
  const known = new Set(skillsFromContext(ctx).map((skill) => skill.name));
1622
2152
  disabledSkills = new Set([...disabledSkills].filter((name) => known.has(name)));
1623
2153
  }
1624
- 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
+ };
1625
2162
  }
1626
2163
 
1627
- 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
+ }
1628
2170
  const allNames = new Set(skillsFromContext(ctx).map((skill) => skill.name));
1629
- inheritedEnabledSkills = null;
1630
2171
  if (Array.isArray(payload.enabledSkills)) {
1631
- const enabled = new Set(normalizeNameList(payload.enabledSkills));
1632
- disabledSkills = new Set([...allNames].filter((name) => !enabled.has(name)));
2172
+ inheritedEnabledSkills = new Set(normalizeNameList(payload.enabledSkills));
1633
2173
  } else if (Array.isArray(payload.disabledSkills)) {
1634
- 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)));
1635
2176
  } else {
1636
- throw new Error("Skill update requires enabledSkills or disabledSkills");
2177
+ throw new Error("Skill update requires enabledSkills, disabledSkills, or inherit mode");
1637
2178
  }
2179
+ disabledSkills = new Set();
2180
+ skillsPinned = true;
2181
+ skillSelectionSource = "session";
1638
2182
  persistSkillsState();
1639
2183
  return skillState(ctx);
1640
2184
  }
@@ -1662,6 +2206,7 @@ export default function webuiRpcHelper(pi) {
1662
2206
  if (!runId) throw new Error("Subagent dismiss requires runId");
1663
2207
  const entry = findTrackedSubagentRun(runId);
1664
2208
  if (entry.run.status === "running") throw new Error(`Cannot dismiss running subagent run: ${runId}`);
2209
+ rememberDismissedHelperAgentRunProjections(canonicalInstancesFromPublicRun(entry.run, new Set()));
1665
2210
  entry.runs.delete(entry.key);
1666
2211
  persistRetainedSubagentRuns();
1667
2212
  publishSubagentStatus();
@@ -1704,13 +2249,21 @@ export default function webuiRpcHelper(pi) {
1704
2249
  async function executeAction(action, payload, ctx) {
1705
2250
  switch (action) {
1706
2251
  case "tools-state":
2252
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
1707
2253
  return toolState();
1708
2254
  case "tools-set":
1709
- return setToolState(payload);
2255
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
2256
+ return setToolState(ctx, payload);
1710
2257
  case "skills-state":
2258
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
1711
2259
  return skillState(ctx);
1712
2260
  case "skills-set":
2261
+ if (ctx.mode !== "rpc") throw new Error("Web UI resource controls require RPC mode");
1713
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) };
1714
2267
  case "sampling-state":
1715
2268
  return samplingState(ctx);
1716
2269
  case "sampling-set":
@@ -1750,9 +2303,11 @@ export default function webuiRpcHelper(pi) {
1750
2303
  });
1751
2304
 
1752
2305
  pi.on("session_start", async (_event, ctx) => {
1753
- const globalDefaults = await readGlobalResourceDefaults();
1754
- restoreToolsFromBranch(ctx, globalDefaults);
1755
- restoreSkillsFromBranch(ctx, globalDefaults);
2306
+ resourceRpcActive = ctx.mode === "rpc";
2307
+ if (resourceRpcActive) {
2308
+ if (runtimeToolBaseline === undefined) enabledTools = new Set(runtimeTools());
2309
+ await recomputeResourceState(ctx);
2310
+ }
1756
2311
  restoreSamplingParamsFromBranch(ctx);
1757
2312
  await loadSubagentLaunchSlotGuidance(ctx);
1758
2313
  subagentContext = ctx;
@@ -1760,24 +2315,41 @@ export default function webuiRpcHelper(pi) {
1760
2315
  foregroundSubagentRuns.clear();
1761
2316
  asyncSubagentRuns.clear();
1762
2317
  workflowSubagentRuns.clear();
2318
+ recoveredSubagentRuns.clear();
1763
2319
  subagentGates.clear();
2320
+ resetCanonicalAgentRunState();
2321
+ subagentFleetSummary = null;
1764
2322
  restoreRetainedSubagentRuns(ctx);
1765
2323
  lastPublishedSubagentSignature = "";
2324
+ lastPublishedSubagentAt = 0;
1766
2325
  publishSubagentStatus();
1767
2326
  scheduleSubagentStatusPoll(subagentPollGeneration, 0);
1768
2327
  });
1769
2328
 
1770
2329
  pi.on("session_tree", async (_event, ctx) => {
1771
- const globalDefaults = await readGlobalResourceDefaults();
1772
- restoreToolsFromBranch(ctx, globalDefaults);
1773
- restoreSkillsFromBranch(ctx, globalDefaults);
2330
+ resourceRpcActive = ctx.mode === "rpc";
2331
+ if (resourceRpcActive) await recomputeResourceState(ctx);
1774
2332
  restoreSamplingParamsFromBranch(ctx);
1775
2333
  subagentContext = ctx;
2334
+ subagentPollGeneration += 1;
1776
2335
  foregroundSubagentRuns.clear();
1777
2336
  asyncSubagentRuns.clear();
2337
+ workflowSubagentRuns.clear();
2338
+ recoveredSubagentRuns.clear();
2339
+ subagentGates.clear();
2340
+ resetCanonicalAgentRunState();
2341
+ subagentFleetSummary = null;
1778
2342
  restoreRetainedSubagentRuns(ctx);
1779
2343
  lastPublishedSubagentSignature = "";
2344
+ lastPublishedSubagentAt = 0;
1780
2345
  publishSubagentStatus();
2346
+ scheduleSubagentStatusPoll(subagentPollGeneration, 0);
2347
+ });
2348
+
2349
+ pi.on("model_select", async (event, ctx) => {
2350
+ if (ctx.mode !== "rpc") return;
2351
+ resourceRpcActive = true;
2352
+ await recomputeResourceState(ctx, event.model);
1781
2353
  });
1782
2354
 
1783
2355
  pi.on("tool_execution_start", (event, ctx) => {
@@ -1785,6 +2357,7 @@ export default function webuiRpcHelper(pi) {
1785
2357
  const id = subagentText(event.toolCallId, 160);
1786
2358
  if (!id) return;
1787
2359
  subagentContext = ctx;
2360
+ const workflowProvisional = typeof event.args?.workflowScript === "string" && event.args.workflowScript.trim().length > 0;
1788
2361
  const initialAgents = subagentInitialAgentsFromArgs(event.args).map((agent, index) => ({
1789
2362
  id: `${id}:${index}:${agent.name}`,
1790
2363
  name: agent.name,
@@ -1794,6 +2367,9 @@ export default function webuiRpcHelper(pi) {
1794
2367
  thinking: agent.thinking,
1795
2368
  nested: false,
1796
2369
  }));
2370
+ if (!initialAgents.length && workflowProvisional) {
2371
+ initialAgents.push({ id: `${id}:0:workflow`, name: "workflow", status: "running", index: 0, nested: false });
2372
+ }
1797
2373
  if (!initialAgents.length) return;
1798
2374
  foregroundSubagentRuns.set(id, {
1799
2375
  id,
@@ -1802,6 +2378,7 @@ export default function webuiRpcHelper(pi) {
1802
2378
  status: "running",
1803
2379
  startedAt: Date.now(),
1804
2380
  controlRunId: undefined,
2381
+ workflowProvisional,
1805
2382
  agents: initialAgents,
1806
2383
  });
1807
2384
  publishSubagentStatus();
@@ -1810,12 +2387,38 @@ export default function webuiRpcHelper(pi) {
1810
2387
  pi.on("tool_execution_update", (event, ctx) => {
1811
2388
  if (event.toolName !== "subagent") return;
1812
2389
  const id = subagentText(event.toolCallId, 160);
1813
- 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
+ }
1814
2418
  if (!run || run.status !== "running") return;
1815
2419
  subagentContext = ctx;
1816
- const details = event.partialResult?.details || event.result?.details;
1817
- const agents = subagentRunningAgentsFromDetails(details, details?.runId || id);
1818
2420
  if (agents.length) {
2421
+ run.workflowProvisional = false;
1819
2422
  const runningAgents = agents.map((agent) => {
1820
2423
  const previous = run.agents.find((candidate) => candidate.index === agent.index && candidate.name === agent.name);
1821
2424
  return {
@@ -1831,9 +2434,9 @@ export default function webuiRpcHelper(pi) {
1831
2434
  .map((agent) => ({ ...agent, status: agent.status === "running" ? "done" : agent.status }));
1832
2435
  run.agents = [...completedAgents, ...runningAgents];
1833
2436
  }
1834
- if (details?.runId) {
1835
- run.controlRunId = subagentText(details.runId, 160);
1836
- run.id = run.controlRunId;
2437
+ if (controlRunId) {
2438
+ run.controlRunId = controlRunId;
2439
+ run.id = controlRunId;
1837
2440
  }
1838
2441
  run.mode = subagentMode(details?.mode, run.mode);
1839
2442
  publishSubagentStatus();
@@ -1842,12 +2445,16 @@ export default function webuiRpcHelper(pi) {
1842
2445
  pi.on("tool_execution_end", (event) => {
1843
2446
  if (event.toolName !== "subagent") return;
1844
2447
  const toolCallId = subagentText(event.toolCallId, 160);
1845
- const run = [...foregroundSubagentRuns.values()].find((candidate) => candidate?.id === toolCallId) || foregroundSubagentRuns.get(toolCallId);
1846
- if (run) finishSubagentRun(run, event.isError === true || event.result?.isError === true ? "failed" : "done");
2448
+ const entry = [...foregroundSubagentRuns.entries()].find(([key, candidate]) => candidate?.id === toolCallId || key === toolCallId);
2449
+ const run = entry?.[1];
2450
+ if (run?.workflowProvisional) foregroundSubagentRuns.delete(entry[0]);
2451
+ else if (run) finishSubagentRun(run, event.isError === true || event.result?.isError === true ? "failed" : "done");
1847
2452
  publishSubagentStatus();
1848
2453
  });
1849
2454
 
1850
2455
  pi.on("session_shutdown", () => {
2456
+ resourceRpcActive = false;
2457
+ resourceGeneration += 1;
1851
2458
  subagentContext = null;
1852
2459
  subagentLaunchSlotGuidance = "";
1853
2460
  subagentPollGeneration += 1;
@@ -1856,7 +2463,10 @@ export default function webuiRpcHelper(pi) {
1856
2463
  foregroundSubagentRuns.clear();
1857
2464
  asyncSubagentRuns.clear();
1858
2465
  workflowSubagentRuns.clear();
2466
+ recoveredSubagentRuns.clear();
1859
2467
  subagentGates.clear();
2468
+ resetCanonicalAgentRunState();
2469
+ subagentFleetSummary = null;
1860
2470
  for (const unsubscribe of subagentEventUnsubscribers) unsubscribe();
1861
2471
  });
1862
2472
 
@@ -1868,6 +2478,7 @@ export default function webuiRpcHelper(pi) {
1868
2478
  });
1869
2479
 
1870
2480
  pi.on("input", async (event, ctx) => {
2481
+ if (!resourceRpcActive || ctx.mode !== "rpc") return { action: "continue" };
1871
2482
  const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
1872
2483
  if (!match) return { action: "continue" };
1873
2484
  const skillName = match[1];
@@ -1879,11 +2490,11 @@ export default function webuiRpcHelper(pi) {
1879
2490
  pi.on("before_agent_start", async (event) => {
1880
2491
  let nextPrompt = event.systemPrompt;
1881
2492
  let changed = false;
1882
- if (disabledSkills.size !== 0 || inheritedEnabledSkills !== null) {
2493
+ if (resourceRpcActive && (disabledSkills.size !== 0 || inheritedEnabledSkills !== null)) {
1883
2494
  const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
1884
2495
  const disabledNames = allSkills.filter((skill) => !isSkillEnabled(skill.name)).map((skill) => skill.name);
1885
- if (disabledNames.length) {
1886
- 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) {
1887
2498
  nextPrompt = replaceAvailableSkillsSection(nextPrompt, filteredSkills);
1888
2499
  for (const name of disabledNames) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
1889
2500
  changed = true;