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.
package/dist/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  badge,
5
+ colorize,
5
6
  contrastTextColor,
6
7
  normalizeOptionalText,
7
8
  normalizeSwarmColor,
@@ -11,7 +12,7 @@ import {
11
12
  safeTerminalText,
12
13
  swarmColorName,
13
14
  swarmColorPalette
14
- } from "./chunks/chunk-77JHO3GV.ts";
15
+ } from "./chunks/chunk-CV4VP4UE.ts";
15
16
 
16
17
  // src/protocol.ts
17
18
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -1832,17 +1833,6 @@ function formatMissionTimeoutInjection(params) {
1832
1833
  }
1833
1834
  return lines.join("\n");
1834
1835
  }
1835
- function formatMissionStatusBadge(record3, now) {
1836
- if (!isMissionLive(record3)) return void 0;
1837
- if (record3.state === "final_wrap_up") return "\u23F1 FINAL";
1838
- if (record3.state === "converging") return "\u23F1 WRAP-UP";
1839
- const remainMs = Math.max(0, record3.deadlineAt - now);
1840
- if (remainMs <= 0) return "\u23F1 WRAP-UP";
1841
- const remainSec = Math.ceil(remainMs / 1e3);
1842
- if (remainSec < 120) return `\u23F1 ${remainSec}s`;
1843
- const remainMin = Math.ceil(remainMs / 6e4);
1844
- return `\u23F1 ${remainMin}m`;
1845
- }
1846
1836
 
1847
1837
  // src/settings.ts
1848
1838
  var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
@@ -1894,9 +1884,32 @@ var SETTING_FIELDS = [
1894
1884
  "missionCountdown",
1895
1885
  "reviewPolicy",
1896
1886
  "profilesDir",
1897
- "allowedProfiles"
1887
+ "allowedProfiles",
1888
+ "workerPiArgs"
1898
1889
  ];
1899
1890
  var SETTING_FIELD_SET = new Set(SETTING_FIELDS);
1891
+ var RESERVED_WORKER_PI_FLAGS = /* @__PURE__ */ new Set([
1892
+ "--",
1893
+ "--name",
1894
+ "-n",
1895
+ "--mode",
1896
+ "--print",
1897
+ "-p",
1898
+ "--no-session",
1899
+ "--session",
1900
+ "--session-id",
1901
+ "--continue",
1902
+ "-c",
1903
+ "--resume",
1904
+ "-r",
1905
+ "--fork",
1906
+ "--help",
1907
+ "-h",
1908
+ "--version",
1909
+ "-v"
1910
+ ]);
1911
+ var MAX_WORKER_PI_ARGS = 32;
1912
+ var MAX_WORKER_PI_ARG_LENGTH = 256;
1900
1913
  function swarmSettingsFilePath() {
1901
1914
  return join4(getAgentDir(), SWARM_SETTINGS_FILE);
1902
1915
  }
@@ -2229,6 +2242,24 @@ function normalizeSwarmSettingsDocument(value) {
2229
2242
  settings.allowedProfiles = [...new Set(value.allowedProfiles)];
2230
2243
  sources.allowedProfiles = "user";
2231
2244
  }
2245
+ if (Object.hasOwn(value, "workerPiArgs")) {
2246
+ if (!Array.isArray(value.workerPiArgs) || value.workerPiArgs.length > MAX_WORKER_PI_ARGS) {
2247
+ return void 0;
2248
+ }
2249
+ const normalizedArgs = [];
2250
+ for (const item of value.workerPiArgs) {
2251
+ if (typeof item !== "string") return void 0;
2252
+ const trimmed = item.trim();
2253
+ if (trimmed.length === 0 || trimmed.length > MAX_WORKER_PI_ARG_LENGTH || trimmed.includes("\0") || trimmed.includes("\n") || trimmed.includes("\r")) {
2254
+ return void 0;
2255
+ }
2256
+ const flagHead = trimmed.includes("=") ? trimmed.slice(0, trimmed.indexOf("=")) : trimmed;
2257
+ if (RESERVED_WORKER_PI_FLAGS.has(flagHead)) return void 0;
2258
+ normalizedArgs.push(trimmed);
2259
+ }
2260
+ settings.workerPiArgs = normalizedArgs;
2261
+ sources.workerPiArgs = "user";
2262
+ }
2232
2263
  const warnings = [
2233
2264
  ...leaderRecycling.warnings,
2234
2265
  ...ledger.warnings,
@@ -2292,6 +2323,7 @@ function createInMemorySwarmSettingsRuntime(initial = {}) {
2292
2323
  ...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
2293
2324
  ...canonical.externalCommand ? { externalCommand: "user" } : {},
2294
2325
  ...canonical.pinToLeadWorkspace !== void 0 ? { pinToLeadWorkspace: "user" } : {},
2326
+ ...canonical.workerPiArgs !== void 0 ? { workerPiArgs: "user" } : {},
2295
2327
  ...canonical.exposeLeadMcp !== void 0 ? { exposeLeadMcp: "user" } : {},
2296
2328
  ...canonical.isolation !== void 0 ? { isolation: "user" } : {},
2297
2329
  ...canonical.resourceLeases !== void 0 ? { resourceLeases: "user" } : {},
@@ -2503,7 +2535,8 @@ function builtInSources() {
2503
2535
  missionCountdown: "built-in",
2504
2536
  reviewPolicy: "built-in",
2505
2537
  profilesDir: "built-in",
2506
- allowedProfiles: "built-in"
2538
+ allowedProfiles: "built-in",
2539
+ workerPiArgs: "built-in"
2507
2540
  };
2508
2541
  }
2509
2542
  function defaultSettings() {
@@ -2535,7 +2568,8 @@ function freezeState(state) {
2535
2568
  }),
2536
2569
  cacheWarming: Object.freeze({ ...state.settings.cacheWarming }),
2537
2570
  missionCountdown: Object.freeze({ ...state.settings.missionCountdown }),
2538
- ...state.settings.allowedProfiles ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) } : {}
2571
+ ...state.settings.allowedProfiles ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) } : {},
2572
+ ...state.settings.workerPiArgs ? { workerPiArgs: Object.freeze([...state.settings.workerPiArgs]) } : {}
2539
2573
  }),
2540
2574
  sources: Object.freeze({ ...state.sources }),
2541
2575
  ...state.warnings ? { warnings: Object.freeze([...state.warnings]) } : {}
@@ -2555,6 +2589,7 @@ function formatError(error) {
2555
2589
  import { randomBytes as randomBytes9 } from "node:crypto";
2556
2590
  import { readdir as readdir4, readFile as readFile7, realpath as realpath3, rename as rename5, rm as rm11, stat as stat4, writeFile as writeFile5 } from "node:fs/promises";
2557
2591
  import { basename as basename7, dirname as dirname7, join as join16, resolve as resolve13, sep as sep3 } from "node:path";
2592
+ import { visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
2558
2593
 
2559
2594
  // src/cache-warming.ts
2560
2595
  function classifyModelCacheTier(model) {
@@ -2903,7 +2938,16 @@ var ExternalRuntimeHost = class {
2903
2938
  prompt: params.prompt,
2904
2939
  source: params.source,
2905
2940
  ...params.messageId ? { messageId: params.messageId } : {},
2906
- ...params.fromSessionId ? { fromSessionId: params.fromSessionId } : {}
2941
+ ...params.fromSessionId ? { fromSessionId: params.fromSessionId } : {},
2942
+ ...params.replaceTag ? { replaceTag: params.replaceTag } : {}
2943
+ });
2944
+ }
2945
+ clearDirectQueue(params) {
2946
+ this.emit({
2947
+ type: "direct_clear_queue",
2948
+ runtimeId: params.runtimeId,
2949
+ sessionId: params.sessionId,
2950
+ ...params.replaceTag ? { replaceTag: params.replaceTag } : {}
2907
2951
  });
2908
2952
  }
2909
2953
  restoreDirect(params, signal) {
@@ -2982,6 +3026,7 @@ var ExternalRuntimeHost = class {
2982
3026
  ...typeof msg.thoughtLevel === "string" && msg.thoughtLevel.length > 0 ? { thoughtLevel: msg.thoughtLevel } : {},
2983
3027
  ...typeof msg.mode === "string" && msg.mode.length > 0 ? { mode: msg.mode } : {},
2984
3028
  ...typeof msg.busy === "boolean" ? { busy: msg.busy } : {},
3029
+ ...typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0 ? { pendingCount: msg.pendingCount } : {},
2985
3030
  updatedAt: this.handlers.now()
2986
3031
  });
2987
3032
  return;
@@ -3013,6 +3058,7 @@ var ExternalRuntimeHost = class {
3013
3058
  ...usage ? { usage } : {},
3014
3059
  settled: msg.settled === true,
3015
3060
  aborted: msg.aborted === true,
3061
+ ...typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0 ? { pendingCount: msg.pendingCount } : {},
3016
3062
  updatedAt: this.handlers.now()
3017
3063
  });
3018
3064
  return;
@@ -4853,6 +4899,7 @@ var LeaderRuntime = class {
4853
4899
  replacingSession = false;
4854
4900
  autoDispatch;
4855
4901
  autoResponsePending = false;
4902
+ postTimeoutAdvisoryDispatched = false;
4856
4903
  /** Set once the user was told that automatic handoffs are circuit-broken. */
4857
4904
  autoCircuitWarningShown = false;
4858
4905
  reset(ctx) {
@@ -4879,6 +4926,7 @@ var LeaderRuntime = class {
4879
4926
  this.turnDeferred = [];
4880
4927
  this.autoDispatch = void 0;
4881
4928
  this.autoResponsePending = false;
4929
+ this.postTimeoutAdvisoryDispatched = false;
4882
4930
  this.autoCircuitWarningShown = false;
4883
4931
  this.advisoryMilestones.clear();
4884
4932
  this.handoffBatch = void 0;
@@ -4992,21 +5040,40 @@ var LeaderRuntime = class {
4992
5040
  this.scheduleApplyDispatch(staged, ctx);
4993
5041
  return;
4994
5042
  }
5043
+ const externalPending = this.host.externalPendingCount?.(ctx) ?? 0;
5044
+ if (externalPending > 0) {
5045
+ return;
5046
+ }
4995
5047
  if (this.autoResponsePending && !this.staged && !this.applying) {
4996
5048
  this.autoResponsePending = false;
4997
5049
  if (!aborted) {
4998
5050
  await this.noteAutoFailure(ctx, "The model did not publish a leader handoff before the automatic turn ended.");
4999
5051
  this.advisoryMilestones.clear();
5052
+ this.postTimeoutAdvisoryDispatched = false;
5000
5053
  }
5001
5054
  }
5002
5055
  if (aborted || this.staged || this.applying) return;
5003
5056
  const config = this.settings.get().settings.leaderRecycling;
5004
- if (config.mode !== "auto") return;
5057
+ if (!config.enabled || config.mode !== "auto") return;
5005
5058
  const sessionId = ctx.sessionManager.getSessionId();
5006
- const advisory = await this.createAdvisory(ctx);
5007
- if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
5008
5059
  const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
5009
5060
  const handoffToolName = activeExternal ? "swarm_leader_handoff" : "leader_handoff";
5061
+ let advisory = await this.createAdvisory(ctx);
5062
+ if (!advisory && this.host.isPostTimeoutHandoffPending?.(ctx) && !this.postTimeoutAdvisoryDispatched) {
5063
+ const canRecycle = await this.canRecycleLeader(ctx);
5064
+ if (canRecycle && this.isCurrent(ctx, sessionId) && !this.staged && !this.applying) {
5065
+ this.postTimeoutAdvisoryDispatched = true;
5066
+ advisory = {
5067
+ priority: "high",
5068
+ content: [
5069
+ "[Pi Agent Swarm post-timeout leader handoff]",
5070
+ "The previous mission countdown expired and closed in convergence mode.",
5071
+ "End this leader generation cleanly and hand off to a fresh successor session before starting a new mission countdown."
5072
+ ].join("\n")
5073
+ };
5074
+ }
5075
+ }
5076
+ if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
5010
5077
  const automatic = `${advisory.content}
5011
5078
 
5012
5079
  Automatic leader recycling is enabled. Call ${handoffToolName} now with all ten sections; do not answer the user first.`;
@@ -5015,7 +5082,7 @@ Automatic leader recycling is enabled. Call ${handoffToolName} now with all ten
5015
5082
  if (!this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
5016
5083
  try {
5017
5084
  this.autoResponsePending = true;
5018
- if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory")) {
5085
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory", "leader-advisory")) {
5019
5086
  return;
5020
5087
  }
5021
5088
  this.pi.sendMessage(
@@ -5031,6 +5098,20 @@ Automatic leader recycling is enabled. Call ${handoffToolName} now with all ten
5031
5098
  if (this.autoDispatch) clearTimeout(this.autoDispatch);
5032
5099
  this.autoDispatch = dispatch;
5033
5100
  }
5101
+ /** True when leader recycling is enabled, persisted, within replacement budget, and not circuit-broken. */
5102
+ async canRecycleLeader(ctx) {
5103
+ const config = this.settings.get().settings.leaderRecycling;
5104
+ if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead) return false;
5105
+ if (!ctx.sessionManager.getSessionFile()) return false;
5106
+ const sessionId = ctx.sessionManager.getSessionId();
5107
+ const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
5108
+ if (!this.isCurrent(ctx, sessionId)) return false;
5109
+ if (lineage) {
5110
+ if (lineage.replacementCount >= config.maxReplacements) return false;
5111
+ if (config.mode === "auto" && (lineage.autoCircuitOpen || (lineage.autoFailures ?? 0) >= 3)) return false;
5112
+ }
5113
+ return true;
5114
+ }
5034
5115
  isLeaderReplacementShutdown() {
5035
5116
  return this.replacingSession;
5036
5117
  }
@@ -5175,6 +5256,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
5175
5256
  editorDraft: ctx.hasUI ? ctx.ui.getEditorText() : void 0
5176
5257
  });
5177
5258
  this.staged = { entry, applySent: false, applyAttempts: 0, automatic };
5259
+ this.host.clearExternalLeaderQueue?.(ctx);
5178
5260
  if (this.turnDeferred.length > 0) {
5179
5261
  entry.deferredFollowUps = [...entry.deferredFollowUps ?? [], ...this.turnDeferred];
5180
5262
  this.turnDeferred = [];
@@ -5202,7 +5284,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
5202
5284
  if (!this.host.leaderSnapshot(ctx).isLead) throw new Error("Only the lead session can hand off.");
5203
5285
  const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
5204
5286
  const handoffPrompt = activeExternal ? "The user requested a leader context handoff. Call swarm_leader_handoff now with all ten required sections, then stop. Do not answer the user first." : "The user requested a leader context handoff. Call leader_handoff now with all ten required sections, then stop. Do not answer the user first.";
5205
- if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory")) {
5287
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory", "leader-advisory")) {
5206
5288
  return;
5207
5289
  }
5208
5290
  await this.pi.sendMessage(
@@ -5771,6 +5853,247 @@ function errorMessage(error) {
5771
5853
  return error instanceof Error ? error.message : String(error);
5772
5854
  }
5773
5855
 
5856
+ // src/mission-badge.ts
5857
+ import { truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth2 } from "@earendil-works/pi-tui";
5858
+ var SHORT_BUDGET_SEC_MODE_MS = 3 * 6e4;
5859
+ var ACTIVE_SEC_SWITCH_SECONDS = 120;
5860
+ var CLOSING_WINDOW_MS = 5 * 6e4;
5861
+ var FINAL_FLASH_PERIOD_MS = 400;
5862
+ var MISSION_BADGE_TIER_MIN_WIDTH = Object.freeze({
5863
+ full: 51,
5864
+ L1: 40,
5865
+ L2: 27,
5866
+ L3: 18,
5867
+ L4: 13
5868
+ });
5869
+ function hexToRgb(hex) {
5870
+ return [
5871
+ Number.parseInt(hex.slice(1, 3), 16),
5872
+ Number.parseInt(hex.slice(3, 5), 16),
5873
+ Number.parseInt(hex.slice(5, 7), 16)
5874
+ ];
5875
+ }
5876
+ function rgbToHex(r, g, b) {
5877
+ return `#${[r, g, b].map(
5878
+ (v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")
5879
+ ).join("")}`;
5880
+ }
5881
+ function hexToHsl(hex) {
5882
+ const [r, g, b] = hexToRgb(hex).map((v) => v / 255);
5883
+ const max = Math.max(r, g, b);
5884
+ const min = Math.min(r, g, b);
5885
+ const l = (max + min) / 2;
5886
+ if (max === min) return [0, 0, l * 100];
5887
+ const d = max - min;
5888
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
5889
+ let h = 0;
5890
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
5891
+ else if (max === g) h = (b - r) / d + 2;
5892
+ else h = (r - g) / d + 4;
5893
+ return [h * 60, s * 100, l * 100];
5894
+ }
5895
+ function hslToHex(h, s, l) {
5896
+ const hue = (h % 360 + 360) % 360;
5897
+ const sat = s / 100;
5898
+ const lig = l / 100;
5899
+ const c = (1 - Math.abs(2 * lig - 1)) * sat;
5900
+ const x = c * (1 - Math.abs(hue / 60 % 2 - 1));
5901
+ const m = lig - c / 2;
5902
+ let r = 0;
5903
+ let g = 0;
5904
+ let b = 0;
5905
+ if (hue < 60) {
5906
+ r = c;
5907
+ g = x;
5908
+ } else if (hue < 120) {
5909
+ r = x;
5910
+ g = c;
5911
+ } else if (hue < 180) {
5912
+ g = c;
5913
+ b = x;
5914
+ } else if (hue < 240) {
5915
+ g = x;
5916
+ b = c;
5917
+ } else if (hue < 300) {
5918
+ r = x;
5919
+ b = c;
5920
+ } else {
5921
+ r = c;
5922
+ b = x;
5923
+ }
5924
+ return rgbToHex((r + m) * 255, (g + m) * 255, (b + m) * 255);
5925
+ }
5926
+ function shiftLightness(hex, deltaL) {
5927
+ const [h, s, l] = hexToHsl(hex);
5928
+ return hslToHex(h, s, Math.max(0, Math.min(100, l + deltaL)));
5929
+ }
5930
+ function derivePhase(main) {
5931
+ return {
5932
+ main,
5933
+ hi: shiftLightness(main, 18),
5934
+ sub: shiftLightness(main, -18)
5935
+ };
5936
+ }
5937
+ var PALETTE = {
5938
+ green: derivePhase("#41b883"),
5939
+ // Vue
5940
+ yellow: derivePhase("#ffc85a"),
5941
+ // ROLE_BADGE_BACKGROUND
5942
+ orange: derivePhase("#dea584"),
5943
+ // Rust
5944
+ red: derivePhase("#c22d40"),
5945
+ // Scala
5946
+ dangerBg: shiftLightness("#c22d40", -18)
5947
+ };
5948
+ var ACTIVE_STATUS_FULL = {
5949
+ healthy: " \u63A8\u9032 ACTIVE ",
5950
+ mid: " \u5DE1\u822A CRUISE ",
5951
+ closing: " \u53CE\u675F CLOSE "
5952
+ };
5953
+ var ACTIVE_STATUS_ZH = {
5954
+ healthy: " \u63A8\u9032 ",
5955
+ mid: " \u5DE1\u822A ",
5956
+ closing: " \u53CE\u675F "
5957
+ };
5958
+ function pickMissionBadgeTier(availableColumns) {
5959
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.full) return "full";
5960
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L1) return "L1";
5961
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L2) return "L2";
5962
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L3) return "L3";
5963
+ return "L4";
5964
+ }
5965
+ function clamp01(value) {
5966
+ if (!Number.isFinite(value)) return 0;
5967
+ return Math.max(0, Math.min(1, value));
5968
+ }
5969
+ function formatMmSs(remainMs) {
5970
+ const sec = Math.max(0, Math.ceil(remainMs / 1e3));
5971
+ const mm = String(Math.floor(sec / 60)).padStart(2, "0");
5972
+ const ss = String(sec % 60).padStart(2, "0");
5973
+ return `${mm}:${ss}`;
5974
+ }
5975
+ function flashBadge(text, now) {
5976
+ const on = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
5977
+ return on ? badge(text, PALETTE.dangerBg, "#ffffff") : badge(text, PALETTE.red.hi, PALETTE.dangerBg);
5978
+ }
5979
+ function renderActiveBadge(budgetMs, remainMs, tier) {
5980
+ const safeBudget = Math.max(1, budgetMs);
5981
+ const frac = clamp01(remainMs / safeBudget);
5982
+ const stage = frac <= 0.25 || safeBudget > CLOSING_WINDOW_MS && remainMs <= CLOSING_WINDOW_MS ? "closing" : frac <= 0.5 ? "mid" : "healthy";
5983
+ const phase = stage === "healthy" ? PALETTE.green : stage === "mid" ? PALETTE.yellow : PALETTE.orange;
5984
+ const fg = contrastTextColor(phase.main);
5985
+ const remainSec = Math.max(0, Math.ceil(remainMs / 1e3));
5986
+ const secMode = safeBudget <= SHORT_BUDGET_SEC_MODE_MS || remainSec < ACTIVE_SEC_SWITCH_SECONDS;
5987
+ const mainTime = secMode ? formatMmSs(remainMs) : `${Math.max(1, Math.ceil(remainMs / 6e4))}m`;
5988
+ if (tier === "L4") {
5989
+ return badge(` SWM ${mainTime} `, phase.main, fg);
5990
+ }
5991
+ const cells = tier === "full" ? 10 : tier === "L1" ? 6 : tier === "L2" ? 4 : 2;
5992
+ const filled = Math.max(1, Math.round(frac * cells));
5993
+ let bar = "";
5994
+ for (let i = 0; i < cells; i += 1) {
5995
+ bar += colorize(i < filled ? "\u25B0" : "\u25B1", i < filled ? phase.main : phase.sub);
5996
+ }
5997
+ const sym = colorize("\u25B8", phase.hi);
5998
+ if (tier === "L3") {
5999
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)}`;
6000
+ }
6001
+ if (tier === "L2") {
6002
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_ZH[stage], phase.main, fg)}`;
6003
+ }
6004
+ if (tier === "L1") {
6005
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
6006
+ }
6007
+ const head = badge(" SWM \u8702\u7FA4 ", phase.main, fg);
6008
+ const budgetMin = Math.max(1, Math.round(safeBudget / 6e4));
6009
+ const timeBadge = secMode ? badge(` ${mainTime} `, phase.main, fg) : badge(` ${mainTime}`, phase.main, fg) + badge(`/${budgetMin}m `, phase.main, phase.sub);
6010
+ return `${head} ${bar} ${sym} ${timeBadge} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
6011
+ }
6012
+ function renderConvergingBadge(graceTotalMs, remainMs, tier) {
6013
+ const safeTotal = Math.max(1, graceTotalMs);
6014
+ const frac = clamp01(remainMs / safeTotal);
6015
+ const mainTime = formatMmSs(remainMs);
6016
+ const orangeFg = contrastTextColor(PALETTE.orange.main);
6017
+ const renderBar = (cells) => {
6018
+ const left = Math.max(1, Math.round(frac * cells));
6019
+ let out = "";
6020
+ for (let i = 0; i < cells; i += 1) {
6021
+ out += colorize(i < left ? "\u2571" : "\u2504", i < left ? PALETTE.red.hi : PALETTE.red.sub);
6022
+ }
6023
+ return out;
6024
+ };
6025
+ if (tier === "L4") {
6026
+ return badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff") + badge(` ${mainTime} `, PALETTE.red.main, "#ffffff");
6027
+ }
6028
+ if (tier === "L3") {
6029
+ return `${badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff")} ${renderBar(2)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
6030
+ }
6031
+ if (tier === "L2") {
6032
+ const head2 = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6033
+ return `${head2} ${renderBar(4)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
6034
+ }
6035
+ if (tier === "L1") {
6036
+ const head2 = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6037
+ return `${head2} ${renderBar(6)} ${colorize("\u2298", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" \u53CE\u6582 ", PALETTE.dangerBg, "#ffffff")}`;
6038
+ }
6039
+ const head = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6040
+ return `${head} ${renderBar(10)} ${colorize("\u2298", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" \u53CE\u6582 WRAP ", PALETTE.dangerBg, "#ffffff")}`;
6041
+ }
6042
+ function renderFinalBadge(remainMs, now, tier) {
6043
+ const mainTime = formatMmSs(remainMs);
6044
+ const blink = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
6045
+ const xColor = blink ? PALETTE.red.hi : PALETTE.dangerBg;
6046
+ const xBar = (cells) => colorize("\u2573".repeat(cells), xColor);
6047
+ if (tier === "L4") {
6048
+ return flashBadge(` FINAL ${mainTime} `, now);
6049
+ }
6050
+ if (tier === "L3") {
6051
+ return `${flashBadge(" FINAL ", now)} ${xBar(2)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
6052
+ }
6053
+ if (tier === "L2") {
6054
+ const head2 = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
6055
+ return `${head2} ${xBar(4)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
6056
+ }
6057
+ const head = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
6058
+ return `${head} ${xBar(6)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")} ${flashBadge(" AUTO ", now)}`;
6059
+ }
6060
+ function nextMissionTickDelayMs(record3, now) {
6061
+ if (!isMissionLive(record3)) return void 0;
6062
+ if (record3.state === "final_wrap_up") return FINAL_FLASH_PERIOD_MS;
6063
+ if (record3.state === "converging") return 1e3;
6064
+ const budgetMs = Math.max(1, record3.deadlineAt - record3.startedAt);
6065
+ const remainMs = Math.max(0, record3.deadlineAt - now);
6066
+ if (budgetMs <= SHORT_BUDGET_SEC_MODE_MS || remainMs <= 125e3) return 1e3;
6067
+ return Math.min(15e3, Math.max(1e3, remainMs - 12e4));
6068
+ }
6069
+ function formatMissionStatusBadge(record3, now, options = {}) {
6070
+ if (!isMissionLive(record3)) return void 0;
6071
+ const availableColumns = options.availableColumns ?? 80;
6072
+ const tier = pickMissionBadgeTier(availableColumns);
6073
+ const wrapUpGraceMs = options.wrapUpGraceMs ?? DEFAULT_MISSION_COUNTDOWN_SETTINGS.wrapUpGraceMs;
6074
+ const finalWrapUpMs = options.finalWrapUpMs ?? Math.max(MIN_FINAL_WRAP_UP_MS, Math.round(wrapUpGraceMs * FINAL_WRAP_UP_AUTO_CLOSE_FACTOR));
6075
+ let rendered;
6076
+ if (record3.state === "final_wrap_up") {
6077
+ const finalTargetAt = (record3.finalWrapUpAt ?? now) + finalWrapUpMs;
6078
+ rendered = renderFinalBadge(Math.max(0, finalTargetAt - now), now, tier);
6079
+ } else if (record3.state === "converging") {
6080
+ const graceTargetAt = (record3.convergingAt ?? record3.deadlineAt) + wrapUpGraceMs;
6081
+ rendered = renderConvergingBadge(wrapUpGraceMs, Math.max(0, graceTargetAt - now), tier);
6082
+ } else {
6083
+ const budgetMs = Math.max(1, record3.deadlineAt - record3.startedAt);
6084
+ const remainMs = Math.max(0, record3.deadlineAt - now);
6085
+ if (remainMs <= 0) {
6086
+ rendered = renderConvergingBadge(wrapUpGraceMs, wrapUpGraceMs, tier);
6087
+ } else {
6088
+ rendered = renderActiveBadge(budgetMs, remainMs, tier);
6089
+ }
6090
+ }
6091
+ if (availableColumns > 0 && visibleWidth2(rendered) > availableColumns) {
6092
+ return truncateToWidth2(rendered, availableColumns, "\u2026");
6093
+ }
6094
+ return rendered;
6095
+ }
6096
+
5774
6097
  // src/model-catalog.ts
5775
6098
  var AGY_MODEL_ID_RE = /^[A-Za-z0-9._:-]{1,160}$/u;
5776
6099
  function parseModelRef(raw) {
@@ -8335,6 +8658,7 @@ async function cleanupTaskWorktree(repoRoot, worktreePath) {
8335
8658
  // src/swarm-controller.ts
8336
8659
  var STATUS_KEY = "swarm";
8337
8660
  var ROSTER_STATUS_KEY = "swarm-roster";
8661
+ var LEADER_GEN_STATUS_KEY = "swarm-leader-gen";
8338
8662
  var MISSION_STATUS_KEY = "swarm-mission";
8339
8663
  var MISSION_CUSTOM_TYPE = "pi-agent-swarm:mission-timeout";
8340
8664
  var DEFAULT_LAUNCH_TIMEOUT_MS = 15e3;
@@ -8394,6 +8718,13 @@ var SwarmController = class {
8394
8718
  const activeSid = ctx.sessionManager.getSessionId();
8395
8719
  if (report.sessionId && report.sessionId !== activeSid) return;
8396
8720
  this.externalLeaderUsage = report;
8721
+ if (this.activeDirectRuntime && report.pendingCount !== void 0) {
8722
+ this.activeDirectRuntime = {
8723
+ ...this.activeDirectRuntime,
8724
+ pendingCount: report.pendingCount,
8725
+ updatedAt: report.updatedAt
8726
+ };
8727
+ }
8397
8728
  if (report.settled) {
8398
8729
  const totalTokens = report.usage?.totalTokens ?? (typeof report.usage?.inputTokens === "number" || typeof report.usage?.outputTokens === "number" ? (report.usage?.inputTokens ?? 0) + (report.usage?.outputTokens ?? 0) : report.tokens);
8399
8730
  this.recordLedger(ctx.cwd, {
@@ -8452,13 +8783,30 @@ var SwarmController = class {
8452
8783
  ...direct.mode ? { mode: direct.mode } : {}
8453
8784
  };
8454
8785
  },
8455
- deliverExternalLeaderPrompt: (ctx, prompt, source) => {
8786
+ externalPendingCount: (ctx) => {
8787
+ if (!this.isExternalDirectLeadActive(ctx)) return 0;
8788
+ if (this.activeDirectRuntime?.pendingCount !== void 0) {
8789
+ return this.activeDirectRuntime.pendingCount;
8790
+ }
8791
+ return this.externalLeaderUsage?.pendingCount ?? 0;
8792
+ },
8793
+ isPostTimeoutHandoffPending: () => this.postTimeoutHandoffRequired,
8794
+ clearExternalLeaderQueue: (ctx, replaceTag) => {
8795
+ if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return;
8796
+ this.externalRuntime.clearDirectQueue({
8797
+ runtimeId: this.activeDirectRuntime.runtimeId,
8798
+ sessionId: ctx.sessionManager.getSessionId(),
8799
+ ...replaceTag ? { replaceTag } : {}
8800
+ });
8801
+ },
8802
+ deliverExternalLeaderPrompt: (ctx, prompt, source, replaceTag) => {
8456
8803
  if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return false;
8457
8804
  this.externalRuntime.deliverToDirect({
8458
8805
  runtimeId: this.activeDirectRuntime.runtimeId,
8459
8806
  sessionId: ctx.sessionManager.getSessionId(),
8460
8807
  prompt,
8461
- source
8808
+ source,
8809
+ ...replaceTag ? { replaceTag } : {}
8462
8810
  });
8463
8811
  return true;
8464
8812
  },
@@ -8553,6 +8901,11 @@ var SwarmController = class {
8553
8901
  activeMission;
8554
8902
  missionTimer;
8555
8903
  missionTicker;
8904
+ lastRosterBadgeWidth = 0;
8905
+ lastLeaderGenWidth = 0;
8906
+ lastTransientStatusWidth = 0;
8907
+ postTimeoutHandoffRequired = false;
8908
+ leaderGenerationNumber;
8556
8909
  sessionRole = "lead";
8557
8910
  sessionProfile = "default";
8558
8911
  sessionRuntime = "pi";
@@ -8612,6 +8965,11 @@ var SwarmController = class {
8612
8965
  this.pendingReviewTasks.clear();
8613
8966
  this.stopMissionTimers();
8614
8967
  this.activeMission = void 0;
8968
+ this.lastRosterBadgeWidth = 0;
8969
+ this.lastLeaderGenWidth = 0;
8970
+ this.lastTransientStatusWidth = 0;
8971
+ this.postTimeoutHandoffRequired = false;
8972
+ this.leaderGenerationNumber = void 0;
8615
8973
  this.sessionRole = "lead";
8616
8974
  this.sessionProfile = "default";
8617
8975
  this.sessionRuntime = "pi";
@@ -9006,6 +9364,9 @@ var SwarmController = class {
9006
9364
  });
9007
9365
  }
9008
9366
  currentModelRef(ctx) {
9367
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime?.model) {
9368
+ return `${this.activeDirectRuntime.runtimeId}:${this.activeDirectRuntime.model}`;
9369
+ }
9009
9370
  if (this.sessionRuntime === "agy" && this.sessionRuntimeModel) {
9010
9371
  return `agy:${this.sessionRuntimeModel}`;
9011
9372
  }
@@ -9033,6 +9394,7 @@ ${pendingLines.join("\n")}`;
9033
9394
  }
9034
9395
  const result = await this.leaderRuntime.publish(effectiveContent, ctx);
9035
9396
  if (!this.isCurrent(ctx)) throw staleError();
9397
+ this.postTimeoutHandoffRequired = false;
9036
9398
  await this.closeActiveMission(ctx, "closed_by_handoff", "handoff", "Closed on leader generation handoff", []);
9037
9399
  return result;
9038
9400
  }
@@ -9067,6 +9429,17 @@ ${pendingLines.join("\n")}`;
9067
9429
  `Mission "${this.activeMission.missionId}" is already ${this.activeMission.state}. Complete it before starting a new mission.`
9068
9430
  );
9069
9431
  }
9432
+ if (this.postTimeoutHandoffRequired) {
9433
+ const canRecycle = await this.leaderRuntime.canRecycleLeader(ctx);
9434
+ if (!this.isCurrent(ctx)) throw staleError();
9435
+ if (canRecycle) {
9436
+ const handoffToolName = this.isExternalDirectLeadActive(ctx) ? "swarm_leader_handoff" : "leader_handoff";
9437
+ throw new Error(
9438
+ `The previous mission countdown expired and closed. Do not start a second countdown on the old leader session \u2014 call ${handoffToolName} first to rotate into a fresh successor session, then start the new mission there.`
9439
+ );
9440
+ }
9441
+ this.postTimeoutHandoffRequired = false;
9442
+ }
9070
9443
  const validated = validateMissionStartInput(
9071
9444
  {
9072
9445
  firstPrinciples: input.firstPrinciples ?? "",
@@ -9191,6 +9564,19 @@ ${pendingLines.join("\n")}`;
9191
9564
  this.activeMission = void 0;
9192
9565
  this.renderMissionStatus(ctx);
9193
9566
  if (!current) return void 0;
9567
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime) {
9568
+ this.externalRuntime.clearDirectQueue({
9569
+ runtimeId: this.activeDirectRuntime.runtimeId,
9570
+ sessionId: ctx.sessionManager.getSessionId(),
9571
+ replaceTag: `mission-timeout:${current.missionId}`
9572
+ });
9573
+ }
9574
+ const wasTimedOut = current.state === "converging" || current.state === "final_wrap_up" || current.convergingAt !== void 0;
9575
+ if (finalState === "auto_completed" || finalState === "completed" && wasTimedOut) {
9576
+ this.postTimeoutHandoffRequired = true;
9577
+ } else if (finalState === "closed_by_handoff") {
9578
+ this.postTimeoutHandoffRequired = false;
9579
+ }
9194
9580
  const now = this.deps.now();
9195
9581
  const archived = {
9196
9582
  ...current,
@@ -9246,13 +9632,24 @@ ${pendingLines.join("\n")}`;
9246
9632
  }, delayMs);
9247
9633
  this.missionTimer.unref?.();
9248
9634
  }
9249
- this.missionTicker = setInterval(() => {
9635
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
9636
+ }
9637
+ scheduleNextMissionTick(ctx, owner, ownerGeneration) {
9638
+ if (this.missionTicker !== void 0) {
9639
+ clearTimeout(this.missionTicker);
9640
+ this.missionTicker = void 0;
9641
+ }
9642
+ const delayMs = nextMissionTickDelayMs(this.activeMission, this.deps.now());
9643
+ if (delayMs === void 0) return;
9644
+ this.missionTicker = setTimeout(() => {
9645
+ this.missionTicker = void 0;
9250
9646
  if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(this.activeMission)) {
9251
9647
  this.stopMissionTimers();
9252
9648
  return;
9253
9649
  }
9254
9650
  this.renderMissionStatus(ctx);
9255
- }, 15e3);
9651
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
9652
+ }, delayMs);
9256
9653
  this.missionTicker.unref?.();
9257
9654
  }
9258
9655
  async handleMissionTimeout(ctx, owner, ownerGeneration, stage) {
@@ -9299,7 +9696,8 @@ ${pendingLines.join("\n")}`;
9299
9696
  runtimeId: this.activeDirectRuntime.runtimeId,
9300
9697
  sessionId: ctx.sessionManager.getSessionId(),
9301
9698
  prompt: injection,
9302
- source: "leader_advisory"
9699
+ source: "leader_advisory",
9700
+ replaceTag: `mission-timeout:${updated.missionId}`
9303
9701
  });
9304
9702
  } else {
9305
9703
  this.pi.sendMessage(
@@ -9327,6 +9725,16 @@ ${pendingLines.join("\n")}`;
9327
9725
  "Autonomously closed after final wrap-up convergence timeout (with residuals).",
9328
9726
  residuals
9329
9727
  );
9728
+ if (!this.isCurrent(owner, ownerGeneration)) return;
9729
+ const recyclingConfig = this.settings.get().settings.leaderRecycling;
9730
+ if (recyclingConfig.enabled && recyclingConfig.mode === "auto" && this.postTimeoutHandoffRequired) {
9731
+ const extActive = this.isExternalDirectLeadActive(ctx);
9732
+ const extIdle = !extActive || this.activeDirectRuntime?.busy !== true && (this.activeDirectRuntime?.pendingCount ?? 0) === 0;
9733
+ const nativeIdle = extActive || (typeof ctx.isIdle === "function" ? ctx.isIdle() : true);
9734
+ if (extIdle && nativeIdle) {
9735
+ void this.track(this.leaderRuntime.agentSettled(ctx, false));
9736
+ }
9737
+ }
9330
9738
  }
9331
9739
  stopMissionTimers() {
9332
9740
  if (this.missionTimer !== void 0) {
@@ -9334,13 +9742,25 @@ ${pendingLines.join("\n")}`;
9334
9742
  this.missionTimer = void 0;
9335
9743
  }
9336
9744
  if (this.missionTicker !== void 0) {
9337
- clearInterval(this.missionTicker);
9745
+ clearTimeout(this.missionTicker);
9338
9746
  this.missionTicker = void 0;
9339
9747
  }
9340
9748
  }
9749
+ missionAvailableColumns() {
9750
+ const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
9751
+ let occupied = 0;
9752
+ if (this.lastRosterBadgeWidth > 0) occupied += this.lastRosterBadgeWidth + 1;
9753
+ if (this.lastLeaderGenWidth > 0) occupied += this.lastLeaderGenWidth + 1;
9754
+ if (this.lastTransientStatusWidth > 0) occupied += this.lastTransientStatusWidth + 1;
9755
+ return Math.max(0, columns - occupied);
9756
+ }
9341
9757
  renderMissionStatus(ctx) {
9342
9758
  if (!ctx.hasUI) return;
9343
- const badge2 = formatMissionStatusBadge(this.activeMission, this.deps.now());
9759
+ const settings = this.settings.get().settings.missionCountdown;
9760
+ const badge2 = formatMissionStatusBadge(this.activeMission, this.deps.now(), {
9761
+ availableColumns: this.missionAvailableColumns(),
9762
+ wrapUpGraceMs: settings.wrapUpGraceMs
9763
+ });
9344
9764
  try {
9345
9765
  ctx.ui.setStatus(MISSION_STATUS_KEY, badge2);
9346
9766
  } catch {
@@ -9415,6 +9835,16 @@ ${pendingLines.join("\n")}`;
9415
9835
  this.defaultLead = !entry.invite;
9416
9836
  this.color = entry.color;
9417
9837
  this.autoNameEligible = false;
9838
+ this.leaderGenerationNumber = entry.generation + 1;
9839
+ this.postTimeoutHandoffRequired = false;
9840
+ const prevShort = entry.previousSessionId.slice(0, 8);
9841
+ const nextShort = sessionId.slice(0, 8);
9842
+ const extSuffix = entry.externalRuntime ? ` [${entry.externalRuntime.runtimeId} fresh session]` : "";
9843
+ this.notify(
9844
+ ctx,
9845
+ `Leader handoff applied: G${entry.generation} (${prevShort}) \u2192 G${entry.generation + 1} (${nextShort})${extSuffix}`,
9846
+ "info"
9847
+ );
9418
9848
  const recover = async (label, action) => {
9419
9849
  if (!this.isCurrent(ctx)) return false;
9420
9850
  try {
@@ -10334,7 +10764,8 @@ ${pendingLines.join("\n")}`;
10334
10764
  claimedMembership = membership;
10335
10765
  const directory = membership.transport.endpointManifest?.directory;
10336
10766
  if (!directory) throw new Error("Pi Agent Swarm runtime directory is unavailable");
10337
- const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs]);
10767
+ const extraWorkerPiArgs = launchSettings.workerPiArgs ? [...launchSettings.workerPiArgs] : [];
10768
+ const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs, ...extraWorkerPiArgs]);
10338
10769
  const envelope = {
10339
10770
  invite: membership.invite,
10340
10771
  parentSessionId: ctx.sessionManager.getSessionId(),
@@ -11296,36 +11727,48 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
11296
11727
  }
11297
11728
  beginStatus(ctx, text) {
11298
11729
  const token = { ctx, text };
11730
+ this.lastTransientStatusWidth = text ? visibleWidth3(text) + 2 : 0;
11299
11731
  try {
11300
11732
  ctx.ui.setStatus(STATUS_KEY, text);
11301
11733
  } catch {
11302
11734
  }
11735
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
11303
11736
  return token;
11304
11737
  }
11305
11738
  updateStatus(token, text) {
11306
11739
  token.text = text;
11740
+ this.lastTransientStatusWidth = text ? visibleWidth3(text) + 2 : 0;
11307
11741
  try {
11308
11742
  token.ctx.ui.setStatus(STATUS_KEY, text);
11309
11743
  } catch {
11310
11744
  }
11745
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
11311
11746
  }
11312
11747
  endStatus(token) {
11748
+ this.lastTransientStatusWidth = 0;
11313
11749
  try {
11314
11750
  token.ctx.ui.setStatus(STATUS_KEY, void 0);
11315
11751
  } catch {
11316
11752
  }
11753
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
11317
11754
  }
11318
11755
  clearStatus(ctx) {
11756
+ this.lastTransientStatusWidth = 0;
11319
11757
  try {
11320
11758
  ctx.ui.setStatus(STATUS_KEY, void 0);
11321
11759
  } catch {
11322
11760
  }
11761
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
11323
11762
  }
11324
11763
  clearRosterStatus(ctx) {
11764
+ this.lastRosterBadgeWidth = 0;
11765
+ this.lastLeaderGenWidth = 0;
11325
11766
  try {
11326
11767
  ctx.ui.setStatus(ROSTER_STATUS_KEY, void 0);
11768
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, void 0);
11327
11769
  } catch {
11328
11770
  }
11771
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
11329
11772
  }
11330
11773
  leadPath() {
11331
11774
  const directory = this.membership?.transport.endpointManifest?.directory;
@@ -11395,8 +11838,12 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
11395
11838
  const role = this.leadSessionId === sessionId || !self && this.defaultLead ? "LEADER" : "WORKER";
11396
11839
  const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
11397
11840
  const status = buildRosterBadge({ name, sessionId, color, role, columns });
11841
+ this.lastRosterBadgeWidth = visibleWidth3(status);
11842
+ const leaderGenText = role === "LEADER" && this.leaderGenerationNumber && this.leaderGenerationNumber > 1 ? `G${this.leaderGenerationNumber}` : void 0;
11843
+ this.lastLeaderGenWidth = leaderGenText ? visibleWidth3(leaderGenText) + 2 : 0;
11398
11844
  try {
11399
11845
  ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
11846
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, leaderGenText);
11400
11847
  } catch {
11401
11848
  }
11402
11849
  this.renderMissionStatus(ctx);
@@ -12274,7 +12721,7 @@ function createPiSwarmExtension(dependencies = {}) {
12274
12721
  return function piSwarmExtension(pi) {
12275
12722
  const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
12276
12723
  const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
12277
- const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-NLK5I2DA.ts")));
12724
+ const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-A2TQAWN6.ts")));
12278
12725
  pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
12279
12726
  registerSwarmTools(pi, controller);
12280
12727
  pi.on("session_start", async (event, ctx) => {