@firstpick/pi-package-webui 0.6.4 → 0.6.6

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.
@@ -1,3 +1,5 @@
1
+ import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
+ import path from "node:path";
1
3
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
2
4
 
3
5
  const HELPER_COMMAND = "webui-helper";
@@ -5,6 +7,19 @@ const RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
5
7
  const TOOLS_CONFIG_TYPE = "webui-tools-config";
6
8
  const SKILLS_CONFIG_TYPE = "webui-skills-config";
7
9
  const APP_RUNNER_CONTEXT_TYPE = "webui-app-runner-output";
10
+ const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
11
+ const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
12
+ const SUBAGENT_RPC_VERSION = 1;
13
+ const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
14
+ const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
15
+ const SUBAGENT_RPC_REPLY_PREFIX = "subagents:rpc:v1:reply:";
16
+ const SUBAGENT_ASYNC_STARTED_EVENT = "subagent:async-started";
17
+ const SUBAGENT_ASYNC_COMPLETE_EVENT = "subagent:async-complete";
18
+ const SUBAGENT_STATUS_POLL_MS = 1500;
19
+ const SUBAGENT_STATUS_RPC_TIMEOUT_MS = 900;
20
+ const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
21
+ const SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
22
+ const SUBAGENT_TRANSCRIPT_TAIL_BYTES = 512 * 1024;
8
23
 
9
24
  const ACTIVE_COMMAND_SESSION_KEY = Symbol.for("pi.webui.helper.activeCommandSession");
10
25
 
@@ -177,9 +192,464 @@ function replaceAvailableSkillsSection(systemPrompt, skills) {
177
192
  return systemPrompt;
178
193
  }
179
194
 
195
+ function subagentText(value, maxLength = 240) {
196
+ const text = String(value || "").trim();
197
+ return text ? text.slice(0, maxLength) : "";
198
+ }
199
+
200
+ function subagentMode(value, fallback = "single") {
201
+ return ["single", "parallel", "chain"].includes(value) ? value : fallback;
202
+ }
203
+
204
+ function subagentAgentName(value) {
205
+ return subagentText(value, 160);
206
+ }
207
+
208
+ function subagentAgentFromDisplay(value) {
209
+ const display = subagentText(value, 240).replace(/^\[[^\]]+\]\s*/, "");
210
+ const labeled = display.match(/\(([^()]*)\)$/);
211
+ return subagentAgentName(labeled?.[1] || display);
212
+ }
213
+
214
+ function subagentCurrentTool(value) {
215
+ const match = String(value || "").match(/(?:^|\|\s*)tool\s+([^\s|]+)/i);
216
+ return subagentText(match?.[1], 120);
217
+ }
218
+
219
+ function subagentOutputLines(value) {
220
+ return (Array.isArray(value) ? value : [])
221
+ .slice(-SUBAGENT_OUTPUT_LINE_LIMIT)
222
+ .map((line) => String(line ?? "").replace(/\r/g, "").slice(0, SUBAGENT_OUTPUT_LINE_LENGTH));
223
+ }
224
+
225
+ function subagentRecentTools(value) {
226
+ return (Array.isArray(value) ? value : []).slice(-20).map((entry) => ({
227
+ tool: subagentText(entry?.tool, 120),
228
+ args: subagentText(entry?.args, 500),
229
+ endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
230
+ })).filter((entry) => entry.tool);
231
+ }
232
+
233
+ function subagentTranscriptPartLines(part) {
234
+ if (!part || typeof part !== "object") return [];
235
+ if (part.type === "text" && typeof part.text === "string") return part.text.split(/\r?\n/);
236
+ if (part.type === "toolCall") {
237
+ const name = subagentText(part.name, 120) || "tool";
238
+ let args = "";
239
+ try {
240
+ args = typeof part.arguments === "string" ? part.arguments : JSON.stringify(part.arguments || {});
241
+ } catch {
242
+ args = "";
243
+ }
244
+ return [`▶ ${name}${args && args !== "{}" ? ` ${args}` : ""}`];
245
+ }
246
+ return [];
247
+ }
248
+
249
+ function subagentTranscriptOutput(sessionFile) {
250
+ const file = String(sessionFile || "");
251
+ if (!file || !path.isAbsolute(file) || path.extname(file) !== ".jsonl") return [];
252
+ let fd;
253
+ try {
254
+ fd = openSync(file, "r");
255
+ const size = fstatSync(fd).size;
256
+ if (size <= 0) return [];
257
+ const length = Math.min(size, SUBAGENT_TRANSCRIPT_TAIL_BYTES);
258
+ const start = size - length;
259
+ const buffer = Buffer.alloc(length);
260
+ const bytesRead = readSync(fd, buffer, 0, length, start);
261
+ const rawLines = buffer.subarray(0, bytesRead).toString("utf8").split(/\r?\n/);
262
+ if (start > 0) rawLines.shift();
263
+ const output = [];
264
+ for (const rawLine of rawLines) {
265
+ if (!rawLine.trim()) continue;
266
+ let entry;
267
+ try {
268
+ entry = JSON.parse(rawLine);
269
+ } catch {
270
+ continue;
271
+ }
272
+ const message = entry?.type === "message" ? entry.message : entry?.message?.role ? entry.message : null;
273
+ if (!message || !["assistant", "toolResult"].includes(message.role)) continue;
274
+ for (const part of Array.isArray(message.content) ? message.content : []) {
275
+ for (const line of subagentTranscriptPartLines(part)) {
276
+ if (line.trim().toLowerCase() === "(no output)") continue;
277
+ output.push(line);
278
+ }
279
+ }
280
+ }
281
+ return subagentOutputLines(output);
282
+ } catch {
283
+ return [];
284
+ } finally {
285
+ if (fd !== undefined) {
286
+ try { closeSync(fd); } catch { /* Best-effort close for live session tails. */ }
287
+ }
288
+ }
289
+ }
290
+
291
+ function subagentInitialAgentsFromStep(step) {
292
+ if (!step || typeof step !== "object") return [];
293
+ if (Array.isArray(step.parallel)) {
294
+ return step.parallel.flatMap((task) => {
295
+ const name = subagentAgentName(task?.agent);
296
+ const count = Number.isInteger(task?.count) && task.count > 0 ? Math.min(task.count, 32) : 1;
297
+ return name ? Array.from({ length: count }, (_unused, index) => ({ name, index })) : [];
298
+ });
299
+ }
300
+ const name = subagentAgentName(step.agent);
301
+ return name ? [{ name, index: 0 }] : [];
302
+ }
303
+
304
+ function subagentInitialAgentsFromArgs(args = {}) {
305
+ if (Array.isArray(args.tasks) && args.tasks.length) {
306
+ return args.tasks.flatMap((task) => subagentInitialAgentsFromStep(task));
307
+ }
308
+ if (Array.isArray(args.chain) && args.chain.length) return subagentInitialAgentsFromStep(args.chain[0]);
309
+ const name = subagentAgentName(args.agent);
310
+ return name ? [{ name, index: 0 }] : [];
311
+ }
312
+
313
+ function subagentRunningAgentsFromDetails(details, runId) {
314
+ if (!details || typeof details !== "object") return [];
315
+ const candidates = [];
316
+ if (Array.isArray(details.progress)) candidates.push(...details.progress);
317
+ if (Array.isArray(details.results)) {
318
+ for (const result of details.results) {
319
+ if (result?.progress && typeof result.progress === "object") candidates.push({ agent: result.agent, ...result.progress });
320
+ }
321
+ }
322
+ return candidates.flatMap((entry, index) => {
323
+ if (String(entry?.status || "").toLowerCase() !== "running") return [];
324
+ const name = subagentAgentName(entry.agent);
325
+ if (!name) return [];
326
+ return [{
327
+ id: `${runId}:${entry.index ?? index}:${name}`,
328
+ name,
329
+ status: "running",
330
+ index: Number.isInteger(entry.index) ? entry.index : index,
331
+ currentTool: subagentText(entry.currentTool, 120) || undefined,
332
+ currentToolArgs: subagentText(entry.currentToolArgs, 500) || undefined,
333
+ currentPath: subagentText(entry.currentPath, 1000) || undefined,
334
+ activityState: subagentText(entry.activityState, 80) || undefined,
335
+ recentTools: subagentRecentTools(entry.recentTools),
336
+ recentOutput: subagentOutputLines(entry.recentOutput),
337
+ turnCount: Number.isFinite(entry.turnCount) ? entry.turnCount : undefined,
338
+ toolCount: Number.isFinite(entry.toolCount) ? entry.toolCount : undefined,
339
+ tokens: Number.isFinite(entry.tokens) ? entry.tokens : undefined,
340
+ nested: false,
341
+ }];
342
+ });
343
+ }
344
+
345
+ function subagentRunningGraphAgents(workflowGraph, runId) {
346
+ const agents = [];
347
+ const seenNodes = new Set();
348
+ const visit = (nodes) => {
349
+ for (const node of Array.isArray(nodes) ? nodes : []) {
350
+ const nodeId = subagentText(node?.id, 160);
351
+ if (nodeId && seenNodes.has(nodeId)) continue;
352
+ if (nodeId) seenNodes.add(nodeId);
353
+ if (node?.kind === "agent" && node.status === "running" && subagentAgentName(node.agent)) {
354
+ const name = subagentAgentName(node.agent);
355
+ const index = Number.isInteger(node.flatIndex) ? node.flatIndex : agents.length;
356
+ agents.push({ id: `${runId}:graph:${nodeId || index}:${name}`, name, status: "running", index, nested: false });
357
+ }
358
+ visit(node?.children);
359
+ }
360
+ };
361
+ visit(workflowGraph?.nodes);
362
+ return agents;
363
+ }
364
+
365
+ function parseSubagentStatusText(text, previousRuns = new Map()) {
366
+ const runs = [];
367
+ let current = null;
368
+ for (const rawLine of String(text || "").split(/\r?\n/)) {
369
+ const runMatch = rawLine.match(/^-\s+([^|]+?)\s+\|\s+(queued|running)\b(.*)$/i);
370
+ if (runMatch) {
371
+ const id = subagentText(runMatch[1], 160);
372
+ const segments = rawLine.split(" | ").map((part) => part.trim());
373
+ const mode = segments.find((part) => ["single", "parallel", "chain"].includes(part));
374
+ const previous = previousRuns.get(id);
375
+ current = {
376
+ id,
377
+ source: "async",
378
+ mode: subagentMode(mode, previous?.mode),
379
+ status: runMatch[2].toLowerCase(),
380
+ startedAt: previous?.startedAt || Date.now(),
381
+ agents: [],
382
+ };
383
+ runs.push(current);
384
+ continue;
385
+ }
386
+ if (!current) continue;
387
+
388
+ const nestedMatch = rawLine.match(/^\s*↳\s+(.+?)\s+\[([^\]]+)\]\s+(queued|running|complete|completed|failed|paused)\b(.*)$/i);
389
+ if (nestedMatch) {
390
+ if (nestedMatch[3].toLowerCase() !== "running") continue;
391
+ const name = subagentAgentFromDisplay(nestedMatch[1]);
392
+ if (!name) continue;
393
+ const targetRunId = subagentText(nestedMatch[2], 160);
394
+ current.agents.push({
395
+ id: `${current.id}:nested:${targetRunId}`,
396
+ targetRunId,
397
+ name,
398
+ status: "running",
399
+ index: current.agents.length,
400
+ currentTool: subagentCurrentTool(nestedMatch[4]) || undefined,
401
+ nested: true,
402
+ });
403
+ continue;
404
+ }
405
+
406
+ const stepMatch = rawLine.match(/^\s+(\d+)\.\s+(.+?)\s+\|\s+(pending|queued|running|complete|completed|failed|paused)\b(.*)$/i)
407
+ || rawLine.match(/^\s+(\d+)\.\s+(.+?)\s+(pending|queued|running|complete|completed|failed|paused)\b(.*)$/i);
408
+ if (!stepMatch || stepMatch[3].toLowerCase() !== "running") continue;
409
+ const name = subagentAgentFromDisplay(stepMatch[2]);
410
+ if (!name) continue;
411
+ const index = Math.max(0, Number.parseInt(stepMatch[1], 10) - 1);
412
+ current.agents.push({
413
+ id: `${current.id}:step:${index}:${name}`,
414
+ name,
415
+ status: "running",
416
+ index,
417
+ currentTool: subagentCurrentTool(stepMatch[4]) || undefined,
418
+ nested: /^\s{4,}\d+\./.test(rawLine),
419
+ });
420
+ }
421
+ return runs.filter((run) => run.status === "running" && run.agents.length > 0);
422
+ }
423
+
180
424
  export default function webuiRpcHelper(pi) {
181
425
  let enabledTools = new Set();
182
426
  let disabledSkills = new Set();
427
+ let subagentContext = null;
428
+ let subagentBridgeAvailable = false;
429
+ let subagentPollTimer = null;
430
+ let subagentPollGeneration = 0;
431
+ let subagentStatusRequestInFlight = false;
432
+ let lastPublishedSubagentSignature = "";
433
+ const asyncSubagentRuns = new Map();
434
+ const foregroundSubagentRuns = new Map();
435
+
436
+ function publicSubagentRuns() {
437
+ return [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()]
438
+ .map((run) => ({
439
+ id: subagentText(run.id, 160),
440
+ source: run.source === "foreground" ? "foreground" : "async",
441
+ mode: subagentMode(run.mode),
442
+ status: "running",
443
+ startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
444
+ agents: (Array.isArray(run.agents) ? run.agents : [])
445
+ .filter((agent) => agent?.status === "running" && subagentAgentName(agent.name))
446
+ .slice(0, 128)
447
+ .map((agent, index) => ({
448
+ id: subagentText(agent.id || `${run.id}:${index}`, 240),
449
+ name: subagentAgentName(agent.name),
450
+ status: "running",
451
+ index: Number.isInteger(agent.index) ? agent.index : index,
452
+ currentTool: subagentText(agent.currentTool, 120) || undefined,
453
+ activityState: subagentText(agent.activityState, 80) || undefined,
454
+ nested: agent.nested === true,
455
+ })),
456
+ }))
457
+ .filter((run) => run.id && run.agents.length > 0)
458
+ .sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
459
+ }
460
+
461
+ function publishSubagentStatus() {
462
+ if (!subagentContext?.hasUI) return;
463
+ const runs = publicSubagentRuns();
464
+ const snapshot = { version: 1, available: subagentBridgeAvailable, runs };
465
+ const signature = JSON.stringify(snapshot);
466
+ if (signature === lastPublishedSubagentSignature) return;
467
+ lastPublishedSubagentSignature = signature;
468
+ try {
469
+ subagentContext.ui.setStatus(WEBUI_SUBAGENTS_STATUS_KEY, `${WEBUI_SUBAGENTS_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: Date.now() })}`);
470
+ } catch {
471
+ // The old context may become stale while Pi replaces a session.
472
+ }
473
+ }
474
+
475
+ function requestSubagentStatus(params = {}) {
476
+ const requestId = `webui-${Date.now()}-${Math.random().toString(36).slice(2)}`;
477
+ return new Promise((resolve, reject) => {
478
+ let unsubscribe;
479
+ const timeout = setTimeout(() => {
480
+ if (typeof unsubscribe === "function") unsubscribe();
481
+ reject(new Error("Timed out waiting for pi-subagents status RPC"));
482
+ }, SUBAGENT_STATUS_RPC_TIMEOUT_MS);
483
+ unsubscribe = pi.events.on(`${SUBAGENT_RPC_REPLY_PREFIX}${requestId}`, (reply) => {
484
+ clearTimeout(timeout);
485
+ if (typeof unsubscribe === "function") unsubscribe();
486
+ if (reply?.success === false) reject(new Error(reply.error?.message || "pi-subagents status RPC failed"));
487
+ else resolve(reply?.data || {});
488
+ });
489
+ pi.events.emit(SUBAGENT_RPC_REQUEST_EVENT, {
490
+ version: SUBAGENT_RPC_VERSION,
491
+ requestId,
492
+ method: "status",
493
+ params,
494
+ source: { extension: "pi-package-webui" },
495
+ });
496
+ });
497
+ }
498
+
499
+ function findTrackedSubagent(runId, agentId) {
500
+ const run = [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()].find((candidate) => candidate?.id === runId);
501
+ if (!run) throw new Error(`Running subagent run not found: ${runId}`);
502
+ const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate?.id === agentId);
503
+ if (!agent) throw new Error(`Running subagent not found: ${agentId}`);
504
+ return { run, agent };
505
+ }
506
+
507
+ function subagentAsyncDirFromStatusText(text) {
508
+ const match = String(text || "").match(/^Dir:\s+(.+)$/m);
509
+ const value = String(match?.[1] || "").trim();
510
+ return value && path.isAbsolute(value) ? path.normalize(value) : "";
511
+ }
512
+
513
+ function subagentOutputSnapshotFromAgent(run, agent, patch = {}) {
514
+ return {
515
+ version: 1,
516
+ runId: run.id,
517
+ source: run.source === "foreground" ? "foreground" : "async",
518
+ mode: subagentMode(run.mode),
519
+ startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
520
+ updatedAt: Number.isFinite(patch.updatedAt) ? patch.updatedAt : Date.now(),
521
+ agent: {
522
+ id: agent.id,
523
+ name: subagentAgentName(patch.name || agent.name),
524
+ index: Number.isInteger(agent.index) ? agent.index : 0,
525
+ nested: agent.nested === true,
526
+ status: subagentText(patch.status || agent.status, 40) || "running",
527
+ activityState: subagentText(patch.activityState || agent.activityState, 80) || undefined,
528
+ currentTool: subagentText(patch.currentTool || agent.currentTool, 120) || undefined,
529
+ currentToolArgs: subagentText(patch.currentToolArgs || agent.currentToolArgs, 500) || undefined,
530
+ currentPath: subagentText(patch.currentPath || agent.currentPath, 1000) || undefined,
531
+ turnCount: Number.isFinite(patch.turnCount) ? patch.turnCount : Number.isFinite(agent.turnCount) ? agent.turnCount : undefined,
532
+ toolCount: Number.isFinite(patch.toolCount) ? patch.toolCount : Number.isFinite(agent.toolCount) ? agent.toolCount : undefined,
533
+ tokens: Number.isFinite(patch.tokens) ? patch.tokens : Number.isFinite(agent.tokens) ? agent.tokens : undefined,
534
+ recentTools: subagentRecentTools(patch.recentTools || agent.recentTools),
535
+ recentOutput: subagentOutputLines(patch.recentOutput || agent.recentOutput),
536
+ error: subagentText(patch.error, 1000) || undefined,
537
+ },
538
+ };
539
+ }
540
+
541
+ async function subagentOutputSnapshot(payload = {}) {
542
+ const runId = subagentText(payload.runId, 160);
543
+ const agentId = subagentText(payload.agentId, 240);
544
+ if (!runId || !agentId) throw new Error("Subagent output requires runId and agentId");
545
+ const { run, agent } = findTrackedSubagent(runId, agentId);
546
+ if (run.source === "foreground") return subagentOutputSnapshotFromAgent(run, agent);
547
+
548
+ const targetRunId = subagentText(agent.targetRunId || run.id, 160);
549
+ let asyncDir = subagentText(run.asyncDir, 4096);
550
+ if (!asyncDir) {
551
+ const data = await requestSubagentStatus({ id: targetRunId });
552
+ asyncDir = subagentAsyncDirFromStatusText(data?.text);
553
+ if (asyncDir && targetRunId === run.id) run.asyncDir = asyncDir;
554
+ }
555
+ if (!asyncDir) return subagentOutputSnapshotFromAgent(run, agent);
556
+
557
+ try {
558
+ const status = JSON.parse(readFileSync(path.join(asyncDir, "status.json"), "utf8"));
559
+ if (status?.runId && status.runId !== targetRunId) throw new Error(`Subagent status run mismatch for ${targetRunId}`);
560
+ const steps = Array.isArray(status?.steps) ? status.steps : [];
561
+ const step = agent.nested
562
+ ? steps.find((candidate) => candidate?.agent === agent.name && ["running", "queued", "pending"].includes(candidate?.status)) || steps[status.currentStep] || steps[0]
563
+ : steps[agent.index] || steps.find((candidate) => candidate?.agent === agent.name && ["running", "queued", "pending"].includes(candidate?.status));
564
+ if (!step) return subagentOutputSnapshotFromAgent(run, agent, { status: status?.state, updatedAt: status?.lastUpdate });
565
+ const transcriptOutput = subagentTranscriptOutput(step.sessionFile || (steps.length === 1 ? status.sessionFile : undefined));
566
+ return subagentOutputSnapshotFromAgent(run, agent, {
567
+ ...step,
568
+ recentOutput: transcriptOutput.length ? transcriptOutput : step.recentOutput,
569
+ status: step.status || status.state,
570
+ updatedAt: step.lastActivityAt || status.lastUpdate,
571
+ tokens: Number.isFinite(step.tokens?.total) ? step.tokens.total : step.tokens,
572
+ });
573
+ } catch (error) {
574
+ return subagentOutputSnapshotFromAgent(run, agent, { error: error instanceof Error ? error.message : String(error) });
575
+ }
576
+ }
577
+
578
+ async function refreshSubagentStatus() {
579
+ if (subagentStatusRequestInFlight) return;
580
+ subagentStatusRequestInFlight = true;
581
+ try {
582
+ const data = await requestSubagentStatus();
583
+ subagentBridgeAvailable = true;
584
+ const parsedRuns = parseSubagentStatusText(data?.text, asyncSubagentRuns);
585
+ const nextIds = new Set(parsedRuns.map((run) => run.id));
586
+ for (const id of asyncSubagentRuns.keys()) {
587
+ const run = asyncSubagentRuns.get(id);
588
+ if (!nextIds.has(id) && Date.now() - Number(run?.eventSeenAt || 0) > SUBAGENT_STATUS_POLL_MS * 2) asyncSubagentRuns.delete(id);
589
+ }
590
+ for (const run of parsedRuns) {
591
+ const previous = asyncSubagentRuns.get(run.id);
592
+ asyncSubagentRuns.set(run.id, { ...previous, ...run, eventSeenAt: previous?.eventSeenAt || Date.now() });
593
+ }
594
+ publishSubagentStatus();
595
+ } catch {
596
+ // The optional pi-subagents extension may not be loaded in this tab.
597
+ } finally {
598
+ subagentStatusRequestInFlight = false;
599
+ }
600
+ }
601
+
602
+ function scheduleSubagentStatusPoll(generation = subagentPollGeneration, delay = SUBAGENT_STATUS_POLL_MS) {
603
+ clearTimeout(subagentPollTimer);
604
+ subagentPollTimer = setTimeout(async () => {
605
+ if (generation !== subagentPollGeneration || !subagentContext) return;
606
+ await refreshSubagentStatus();
607
+ scheduleSubagentStatusPoll(generation);
608
+ }, delay);
609
+ subagentPollTimer.unref?.();
610
+ }
611
+
612
+ const subagentEventUnsubscribers = [
613
+ pi.events.on(SUBAGENT_RPC_READY_EVENT, () => {
614
+ subagentBridgeAvailable = true;
615
+ publishSubagentStatus();
616
+ void refreshSubagentStatus();
617
+ }),
618
+ pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (value) => {
619
+ const info = value && typeof value === "object" ? value : {};
620
+ const id = subagentText(info.id, 160);
621
+ if (!id) return;
622
+ let agents = subagentRunningGraphAgents(info.workflowGraph, id);
623
+ if (!agents.length) {
624
+ const names = info.mode === "parallel" && Array.isArray(info.agents) && info.agents.length
625
+ ? info.agents
626
+ : info.agent
627
+ ? [info.agent]
628
+ : Array.isArray(info.agents) && info.agents.length
629
+ ? [info.agents[0]]
630
+ : [];
631
+ agents = names.map((name, index) => ({ id: `${id}:${index}:${subagentAgentName(name)}`, name: subagentAgentName(name), status: "running", index, nested: false })).filter((agent) => agent.name);
632
+ }
633
+ foregroundSubagentRuns.clear();
634
+ asyncSubagentRuns.set(id, {
635
+ id,
636
+ source: "async",
637
+ mode: subagentMode(info.mode, Array.isArray(info.chain) ? "chain" : "single"),
638
+ status: "running",
639
+ startedAt: Date.now(),
640
+ eventSeenAt: Date.now(),
641
+ asyncDir: subagentText(info.asyncDir, 4096) || undefined,
642
+ agents,
643
+ });
644
+ subagentBridgeAvailable = true;
645
+ publishSubagentStatus();
646
+ }),
647
+ pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (value) => {
648
+ const id = subagentText(value?.id || value?.runId, 160);
649
+ if (id) asyncSubagentRuns.delete(id);
650
+ publishSubagentStatus();
651
+ }),
652
+ ].filter((unsubscribe) => typeof unsubscribe === "function");
183
653
 
184
654
  function allToolNames() {
185
655
  return pi.getAllTools().map((tool) => tool.name);
@@ -293,7 +763,7 @@ export default function webuiRpcHelper(pi) {
293
763
  };
294
764
  }
295
765
 
296
- function executeAction(action, payload, ctx) {
766
+ async function executeAction(action, payload, ctx) {
297
767
  switch (action) {
298
768
  case "tools-state":
299
769
  return toolState();
@@ -305,6 +775,8 @@ export default function webuiRpcHelper(pi) {
305
775
  return setSkillState(ctx, payload);
306
776
  case "app-runner-context":
307
777
  return transferAppRunnerContext(ctx, payload);
778
+ case "subagent-output":
779
+ return subagentOutputSnapshot(payload);
308
780
  case "queue-remove":
309
781
  return removeQueuedPrompt(payload);
310
782
  default:
@@ -319,7 +791,7 @@ export default function webuiRpcHelper(pi) {
319
791
  try {
320
792
  const request = parseHelperArgs(args);
321
793
  requestId = request.requestId;
322
- const data = executeAction(request.action, request.payload, ctx);
794
+ const data = await executeAction(request.action, request.payload, ctx);
323
795
  ctx.ui.notify(responseMessage({ requestId, ok: true, data }), "info");
324
796
  } catch (error) {
325
797
  ctx.ui.notify(responseMessage({ requestId, ok: false, error: error instanceof Error ? error.message : String(error) }), "error");
@@ -330,11 +802,73 @@ export default function webuiRpcHelper(pi) {
330
802
  pi.on("session_start", async (_event, ctx) => {
331
803
  restoreToolsFromBranch(ctx);
332
804
  restoreSkillsFromBranch(ctx);
805
+ subagentContext = ctx;
806
+ subagentPollGeneration += 1;
807
+ foregroundSubagentRuns.clear();
808
+ asyncSubagentRuns.clear();
809
+ lastPublishedSubagentSignature = "";
810
+ publishSubagentStatus();
811
+ scheduleSubagentStatusPoll(subagentPollGeneration, 0);
333
812
  });
334
813
 
335
814
  pi.on("session_tree", async (_event, ctx) => {
336
815
  restoreToolsFromBranch(ctx);
337
816
  restoreSkillsFromBranch(ctx);
817
+ subagentContext = ctx;
818
+ });
819
+
820
+ pi.on("tool_execution_start", (event, ctx) => {
821
+ if (event.toolName !== "subagent" || event.args?.action) return;
822
+ const id = subagentText(event.toolCallId, 160);
823
+ if (!id) return;
824
+ subagentContext = ctx;
825
+ const initialAgents = subagentInitialAgentsFromArgs(event.args).map((agent, index) => ({
826
+ id: `${id}:${index}:${agent.name}`,
827
+ name: agent.name,
828
+ status: "running",
829
+ index,
830
+ nested: false,
831
+ }));
832
+ if (!initialAgents.length) return;
833
+ foregroundSubagentRuns.set(id, {
834
+ id,
835
+ source: "foreground",
836
+ mode: Array.isArray(event.args?.chain) ? "chain" : Array.isArray(event.args?.tasks) ? "parallel" : "single",
837
+ status: "running",
838
+ startedAt: Date.now(),
839
+ agents: initialAgents,
840
+ });
841
+ publishSubagentStatus();
842
+ });
843
+
844
+ pi.on("tool_execution_update", (event, ctx) => {
845
+ if (event.toolName !== "subagent") return;
846
+ const id = subagentText(event.toolCallId, 160);
847
+ const run = foregroundSubagentRuns.get(id);
848
+ if (!run) return;
849
+ subagentContext = ctx;
850
+ const details = event.partialResult?.details || event.result?.details;
851
+ const agents = subagentRunningAgentsFromDetails(details, details?.runId || id);
852
+ if (agents.length) run.agents = agents;
853
+ if (details?.runId) run.id = subagentText(details.runId, 160);
854
+ run.mode = subagentMode(details?.mode, run.mode);
855
+ publishSubagentStatus();
856
+ });
857
+
858
+ pi.on("tool_execution_end", (event) => {
859
+ if (event.toolName !== "subagent") return;
860
+ foregroundSubagentRuns.delete(subagentText(event.toolCallId, 160));
861
+ publishSubagentStatus();
862
+ });
863
+
864
+ pi.on("session_shutdown", () => {
865
+ subagentContext = null;
866
+ subagentPollGeneration += 1;
867
+ clearTimeout(subagentPollTimer);
868
+ subagentPollTimer = null;
869
+ foregroundSubagentRuns.clear();
870
+ asyncSubagentRuns.clear();
871
+ for (const unsubscribe of subagentEventUnsubscribers) unsubscribe();
338
872
  });
339
873
 
340
874
  pi.on("input", async (event, ctx) => {