pi-agent-swarm 0.6.0 → 0.7.0

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.
@@ -13,6 +13,7 @@ import type {
13
13
  ToolCallEvent,
14
14
  ToolCallEventResult,
15
15
  } from "@earendil-works/pi-coding-agent";
16
+ import { visibleWidth } from "@earendil-works/pi-tui";
16
17
  import {
17
18
  AUTO_NAME_EXTERNAL_MIN_CHARS,
18
19
  AUTO_NAME_EXTERNAL_TURN_EVENT,
@@ -84,7 +85,6 @@ import {
84
85
  archiveMission,
85
86
  checkMissionSpawnGate,
86
87
  FINAL_WRAP_UP_AUTO_CLOSE_FACTOR,
87
- formatMissionStatusBadge,
88
88
  formatMissionTimeoutInjection,
89
89
  isMissionConverging,
90
90
  isMissionLive,
@@ -95,6 +95,7 @@ import {
95
95
  validateMissionStartInput,
96
96
  writeActiveMission,
97
97
  } from "./mission.js";
98
+ import { formatMissionStatusBadge, nextMissionTickDelayMs } from "./mission-badge.js";
98
99
  import {
99
100
  buildModelCatalog,
100
101
  type ExternalRuntimeSnapshot,
@@ -166,6 +167,7 @@ import { type ProvisionedWorktree, provisionTaskWorktree } from "./worktree.js";
166
167
 
167
168
  const STATUS_KEY = "swarm";
168
169
  const ROSTER_STATUS_KEY = "swarm-roster";
170
+ const LEADER_GEN_STATUS_KEY = "swarm-leader-gen";
169
171
  const MISSION_STATUS_KEY = "swarm-mission";
170
172
  const MISSION_CUSTOM_TYPE = "pi-agent-swarm:mission-timeout";
171
173
  const DEFAULT_LAUNCH_TIMEOUT_MS = 15_000;
@@ -413,7 +415,12 @@ export class SwarmController {
413
415
  >();
414
416
  private activeMission: SwarmMissionRecord | undefined;
415
417
  private missionTimer: ReturnType<typeof setTimeout> | undefined;
416
- private missionTicker: ReturnType<typeof setInterval> | undefined;
418
+ private missionTicker: ReturnType<typeof setTimeout> | undefined;
419
+ private lastRosterBadgeWidth = 0;
420
+ private lastLeaderGenWidth = 0;
421
+ private lastTransientStatusWidth = 0;
422
+ private postTimeoutHandoffRequired = false;
423
+ private leaderGenerationNumber: number | undefined;
417
424
  private sessionRole: SwarmRole = "lead";
418
425
  private sessionProfile = "default";
419
426
  private sessionRuntime: SwarmEngineKind = "pi";
@@ -477,6 +484,13 @@ export class SwarmController {
477
484
  const activeSid = ctx.sessionManager.getSessionId();
478
485
  if (report.sessionId && report.sessionId !== activeSid) return;
479
486
  this.externalLeaderUsage = report;
487
+ if (this.activeDirectRuntime && report.pendingCount !== undefined) {
488
+ this.activeDirectRuntime = {
489
+ ...this.activeDirectRuntime,
490
+ pendingCount: report.pendingCount,
491
+ updatedAt: report.updatedAt,
492
+ };
493
+ }
480
494
  if (report.settled) {
481
495
  const totalTokens =
482
496
  report.usage?.totalTokens ??
@@ -539,13 +553,30 @@ export class SwarmController {
539
553
  ...(direct.mode ? { mode: direct.mode } : {}),
540
554
  };
541
555
  },
542
- deliverExternalLeaderPrompt: (ctx, prompt, source) => {
556
+ externalPendingCount: (ctx) => {
557
+ if (!this.isExternalDirectLeadActive(ctx)) return 0;
558
+ if (this.activeDirectRuntime?.pendingCount !== undefined) {
559
+ return this.activeDirectRuntime.pendingCount;
560
+ }
561
+ return this.externalLeaderUsage?.pendingCount ?? 0;
562
+ },
563
+ isPostTimeoutHandoffPending: () => this.postTimeoutHandoffRequired,
564
+ clearExternalLeaderQueue: (ctx, replaceTag) => {
565
+ if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return;
566
+ this.externalRuntime.clearDirectQueue({
567
+ runtimeId: this.activeDirectRuntime.runtimeId,
568
+ sessionId: ctx.sessionManager.getSessionId(),
569
+ ...(replaceTag ? { replaceTag } : {}),
570
+ });
571
+ },
572
+ deliverExternalLeaderPrompt: (ctx, prompt, source, replaceTag) => {
543
573
  if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return false;
544
574
  this.externalRuntime.deliverToDirect({
545
575
  runtimeId: this.activeDirectRuntime.runtimeId,
546
576
  sessionId: ctx.sessionManager.getSessionId(),
547
577
  prompt,
548
578
  source,
579
+ ...(replaceTag ? { replaceTag } : {}),
549
580
  });
550
581
  return true;
551
582
  },
@@ -646,6 +677,11 @@ export class SwarmController {
646
677
  this.pendingReviewTasks.clear();
647
678
  this.stopMissionTimers();
648
679
  this.activeMission = undefined;
680
+ this.lastRosterBadgeWidth = 0;
681
+ this.lastLeaderGenWidth = 0;
682
+ this.lastTransientStatusWidth = 0;
683
+ this.postTimeoutHandoffRequired = false;
684
+ this.leaderGenerationNumber = undefined;
649
685
  this.sessionRole = "lead";
650
686
  this.sessionProfile = "default";
651
687
  this.sessionRuntime = "pi";
@@ -1095,6 +1131,9 @@ export class SwarmController {
1095
1131
  }
1096
1132
 
1097
1133
  private currentModelRef(ctx: ExtensionContext): string {
1134
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime?.model) {
1135
+ return `${this.activeDirectRuntime.runtimeId}:${this.activeDirectRuntime.model}`;
1136
+ }
1098
1137
  if (this.sessionRuntime === "agy" && this.sessionRuntimeModel) {
1099
1138
  return `agy:${this.sessionRuntimeModel}`;
1100
1139
  }
@@ -1122,6 +1161,7 @@ export class SwarmController {
1122
1161
  }
1123
1162
  const result = await this.leaderRuntime.publish(effectiveContent, ctx);
1124
1163
  if (!this.isCurrent(ctx)) throw staleError();
1164
+ this.postTimeoutHandoffRequired = false;
1125
1165
  // Publishing a leader handoff ends the predecessor generation's countdown;
1126
1166
  // the successor leader will establish its own fresh estimate from the handoff document.
1127
1167
  await this.closeActiveMission(ctx, "closed_by_handoff", "handoff", "Closed on leader generation handoff", []);
@@ -1179,6 +1219,17 @@ export class SwarmController {
1179
1219
  `Mission "${this.activeMission.missionId}" is already ${this.activeMission.state}. Complete it before starting a new mission.`,
1180
1220
  );
1181
1221
  }
1222
+ if (this.postTimeoutHandoffRequired) {
1223
+ const canRecycle = await this.leaderRuntime.canRecycleLeader(ctx);
1224
+ if (!this.isCurrent(ctx)) throw staleError();
1225
+ if (canRecycle) {
1226
+ const handoffToolName = this.isExternalDirectLeadActive(ctx) ? "swarm_leader_handoff" : "leader_handoff";
1227
+ throw new Error(
1228
+ `The previous mission countdown expired and closed. Do not start a second countdown on the old leader session — call ${handoffToolName} first to rotate into a fresh successor session, then start the new mission there.`,
1229
+ );
1230
+ }
1231
+ this.postTimeoutHandoffRequired = false;
1232
+ }
1182
1233
  const validated = validateMissionStartInput(
1183
1234
  {
1184
1235
  firstPrinciples: input.firstPrinciples ?? "",
@@ -1321,6 +1372,20 @@ export class SwarmController {
1321
1372
  this.activeMission = undefined;
1322
1373
  this.renderMissionStatus(ctx);
1323
1374
  if (!current) return undefined;
1375
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime) {
1376
+ this.externalRuntime.clearDirectQueue({
1377
+ runtimeId: this.activeDirectRuntime.runtimeId,
1378
+ sessionId: ctx.sessionManager.getSessionId(),
1379
+ replaceTag: `mission-timeout:${current.missionId}`,
1380
+ });
1381
+ }
1382
+ const wasTimedOut =
1383
+ current.state === "converging" || current.state === "final_wrap_up" || current.convergingAt !== undefined;
1384
+ if (finalState === "auto_completed" || (finalState === "completed" && wasTimedOut)) {
1385
+ this.postTimeoutHandoffRequired = true;
1386
+ } else if (finalState === "closed_by_handoff") {
1387
+ this.postTimeoutHandoffRequired = false;
1388
+ }
1324
1389
  const now = this.deps.now();
1325
1390
  const archived: SwarmMissionRecord = {
1326
1391
  ...current,
@@ -1379,13 +1444,25 @@ export class SwarmController {
1379
1444
  this.missionTimer.unref?.();
1380
1445
  }
1381
1446
 
1382
- this.missionTicker = setInterval(() => {
1447
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
1448
+ }
1449
+
1450
+ private scheduleNextMissionTick(ctx: ExtensionContext, owner: object, ownerGeneration: number): void {
1451
+ if (this.missionTicker !== undefined) {
1452
+ clearTimeout(this.missionTicker);
1453
+ this.missionTicker = undefined;
1454
+ }
1455
+ const delayMs = nextMissionTickDelayMs(this.activeMission, this.deps.now());
1456
+ if (delayMs === undefined) return;
1457
+ this.missionTicker = setTimeout(() => {
1458
+ this.missionTicker = undefined;
1383
1459
  if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(this.activeMission)) {
1384
1460
  this.stopMissionTimers();
1385
1461
  return;
1386
1462
  }
1387
1463
  this.renderMissionStatus(ctx);
1388
- }, 15_000);
1464
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
1465
+ }, delayMs);
1389
1466
  this.missionTicker.unref?.();
1390
1467
  }
1391
1468
 
@@ -1443,6 +1520,7 @@ export class SwarmController {
1443
1520
  sessionId: ctx.sessionManager.getSessionId(),
1444
1521
  prompt: injection,
1445
1522
  source: "leader_advisory",
1523
+ replaceTag: `mission-timeout:${updated.missionId}`,
1446
1524
  });
1447
1525
  } else {
1448
1526
  this.pi.sendMessage(
@@ -1472,6 +1550,19 @@ export class SwarmController {
1472
1550
  "Autonomously closed after final wrap-up convergence timeout (with residuals).",
1473
1551
  residuals,
1474
1552
  );
1553
+ if (!this.isCurrent(owner, ownerGeneration)) return;
1554
+ // If leader recycling is in auto mode and the leader is currently idle (not mid-turn and no queued prompts),
1555
+ // trigger an immediate handoff evaluation so the timed-out leader rotates cleanly to a fresh session.
1556
+ const recyclingConfig = this.settings.get().settings.leaderRecycling;
1557
+ if (recyclingConfig.enabled && recyclingConfig.mode === "auto" && this.postTimeoutHandoffRequired) {
1558
+ const extActive = this.isExternalDirectLeadActive(ctx);
1559
+ const extIdle =
1560
+ !extActive || (this.activeDirectRuntime?.busy !== true && (this.activeDirectRuntime?.pendingCount ?? 0) === 0);
1561
+ const nativeIdle = extActive || (typeof ctx.isIdle === "function" ? ctx.isIdle() : true);
1562
+ if (extIdle && nativeIdle) {
1563
+ void this.track(this.leaderRuntime.agentSettled(ctx, false));
1564
+ }
1565
+ }
1475
1566
  }
1476
1567
 
1477
1568
  private stopMissionTimers(): void {
@@ -1480,14 +1571,27 @@ export class SwarmController {
1480
1571
  this.missionTimer = undefined;
1481
1572
  }
1482
1573
  if (this.missionTicker !== undefined) {
1483
- clearInterval(this.missionTicker);
1574
+ clearTimeout(this.missionTicker);
1484
1575
  this.missionTicker = undefined;
1485
1576
  }
1486
1577
  }
1487
1578
 
1579
+ private missionAvailableColumns(): number {
1580
+ const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
1581
+ let occupied = 0;
1582
+ if (this.lastRosterBadgeWidth > 0) occupied += this.lastRosterBadgeWidth + 1;
1583
+ if (this.lastLeaderGenWidth > 0) occupied += this.lastLeaderGenWidth + 1;
1584
+ if (this.lastTransientStatusWidth > 0) occupied += this.lastTransientStatusWidth + 1;
1585
+ return Math.max(0, columns - occupied);
1586
+ }
1587
+
1488
1588
  private renderMissionStatus(ctx: ExtensionContext): void {
1489
1589
  if (!ctx.hasUI) return;
1490
- const badge = formatMissionStatusBadge(this.activeMission, this.deps.now());
1590
+ const settings = this.settings.get().settings.missionCountdown;
1591
+ const badge = formatMissionStatusBadge(this.activeMission, this.deps.now(), {
1592
+ availableColumns: this.missionAvailableColumns(),
1593
+ wrapUpGraceMs: settings.wrapUpGraceMs,
1594
+ });
1491
1595
  try {
1492
1596
  ctx.ui.setStatus(MISSION_STATUS_KEY, badge);
1493
1597
  } catch {
@@ -1576,6 +1680,16 @@ export class SwarmController {
1576
1680
  this.defaultLead = !entry.invite;
1577
1681
  this.color = entry.color;
1578
1682
  this.autoNameEligible = false;
1683
+ this.leaderGenerationNumber = entry.generation + 1;
1684
+ this.postTimeoutHandoffRequired = false;
1685
+ const prevShort = entry.previousSessionId.slice(0, 8);
1686
+ const nextShort = sessionId.slice(0, 8);
1687
+ const extSuffix = entry.externalRuntime ? ` [${entry.externalRuntime.runtimeId} fresh session]` : "";
1688
+ this.notify(
1689
+ ctx,
1690
+ `Leader handoff applied: G${entry.generation} (${prevShort}) → G${entry.generation + 1} (${nextShort})${extSuffix}`,
1691
+ "info",
1692
+ );
1579
1693
  const recover = async (label: string, action: () => void | Promise<void>): Promise<boolean> => {
1580
1694
  if (!this.isCurrent(ctx)) return false;
1581
1695
  try {
@@ -2629,7 +2743,8 @@ export class SwarmController {
2629
2743
  claimedMembership = membership;
2630
2744
  const directory = membership.transport.endpointManifest?.directory;
2631
2745
  if (!directory) throw new Error("Pi Agent Swarm runtime directory is unavailable");
2632
- const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs]);
2746
+ const extraWorkerPiArgs = launchSettings.workerPiArgs ? [...launchSettings.workerPiArgs] : [];
2747
+ const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs, ...extraWorkerPiArgs]);
2633
2748
  const envelope: SwarmLaunchEnvelope = {
2634
2749
  invite: membership.invite,
2635
2750
  parentSessionId: ctx.sessionManager.getSessionId(),
@@ -3719,45 +3834,57 @@ export class SwarmController {
3719
3834
 
3720
3835
  private beginStatus(ctx: ExtensionContext, text: string): { ctx: ExtensionContext; text: string } {
3721
3836
  const token = { ctx, text };
3837
+ this.lastTransientStatusWidth = text ? visibleWidth(text) + 2 : 0;
3722
3838
  try {
3723
3839
  ctx.ui.setStatus(STATUS_KEY, text);
3724
3840
  } catch {
3725
3841
  // A replaced UI is allowed to reject best-effort cleanup.
3726
3842
  }
3843
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
3727
3844
  return token;
3728
3845
  }
3729
3846
 
3730
3847
  private updateStatus(token: { ctx: ExtensionContext; text: string }, text: string): void {
3731
3848
  token.text = text;
3849
+ this.lastTransientStatusWidth = text ? visibleWidth(text) + 2 : 0;
3732
3850
  try {
3733
3851
  token.ctx.ui.setStatus(STATUS_KEY, text);
3734
3852
  } catch {
3735
3853
  // A replaced UI is allowed to reject best-effort updates.
3736
3854
  }
3855
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
3737
3856
  }
3738
3857
 
3739
3858
  private endStatus(token: { ctx: ExtensionContext; text: string }): void {
3859
+ this.lastTransientStatusWidth = 0;
3740
3860
  try {
3741
3861
  token.ctx.ui.setStatus(STATUS_KEY, undefined);
3742
3862
  } catch {
3743
3863
  // A replaced UI is allowed to reject best-effort cleanup.
3744
3864
  }
3865
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
3745
3866
  }
3746
3867
 
3747
3868
  private clearStatus(ctx: ExtensionContext): void {
3869
+ this.lastTransientStatusWidth = 0;
3748
3870
  try {
3749
3871
  ctx.ui.setStatus(STATUS_KEY, undefined);
3750
3872
  } catch {
3751
3873
  // A replaced UI is allowed to reject best-effort cleanup.
3752
3874
  }
3875
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
3753
3876
  }
3754
3877
 
3755
3878
  private clearRosterStatus(ctx: ExtensionContext): void {
3879
+ this.lastRosterBadgeWidth = 0;
3880
+ this.lastLeaderGenWidth = 0;
3756
3881
  try {
3757
3882
  ctx.ui.setStatus(ROSTER_STATUS_KEY, undefined);
3883
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, undefined);
3758
3884
  } catch {
3759
3885
  // A replaced UI is allowed to reject best-effort cleanup.
3760
3886
  }
3887
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
3761
3888
  }
3762
3889
 
3763
3890
  private leadPath(): string | undefined {
@@ -3843,8 +3970,15 @@ export class SwarmController {
3843
3970
  // terminal width (see footer.ts); the role badge always survives.
3844
3971
  const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
3845
3972
  const status = buildRosterBadge({ name, sessionId, color, role, columns });
3973
+ this.lastRosterBadgeWidth = visibleWidth(status);
3974
+ const leaderGenText =
3975
+ role === "LEADER" && this.leaderGenerationNumber && this.leaderGenerationNumber > 1
3976
+ ? `G${this.leaderGenerationNumber}`
3977
+ : undefined;
3978
+ this.lastLeaderGenWidth = leaderGenText ? visibleWidth(leaderGenText) + 2 : 0;
3846
3979
  try {
3847
3980
  ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
3981
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, leaderGenText);
3848
3982
  } catch {
3849
3983
  // A replaced UI is allowed to reject best-effort status.
3850
3984
  }