pi-agent-swarm 0.1.0 → 0.3.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
@@ -1,63 +1,17 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
+ badge,
5
+ contrastTextColor,
4
6
  normalizeOptionalText,
7
+ normalizeSwarmColor,
8
+ pickSwarmColor,
5
9
  safeError,
6
10
  safeTerminalLine,
7
- safeTerminalText
8
- } from "./chunks/chunk-XD4GFZPB.ts";
9
-
10
- // src/color.ts
11
- import { getTerminalColorMode, parseColor, styleText } from "@earendil-works/pi-tui";
12
- var SWARM_COLORS = [
13
- { name: "red", hex: "#ef4444" },
14
- { name: "orange", hex: "#f97316" },
15
- { name: "yellow", hex: "#eab308" },
16
- { name: "green", hex: "#22c55e" },
17
- { name: "cyan", hex: "#06b6d4" },
18
- { name: "blue", hex: "#3b82f6" },
19
- { name: "magenta", hex: "#d946ef" },
20
- { name: "purple", hex: "#8b5cf6" }
21
- ];
22
- var HEX_RE = /^#[0-9a-f]{6}$/u;
23
- var NAME_TO_HEX = new Map(SWARM_COLORS.map((c) => [c.name, c.hex]));
24
- var HEX_TO_NAME = new Map(SWARM_COLORS.map((c) => [c.hex, c.name]));
25
- function normalizeSwarmColor(value) {
26
- if (typeof value !== "string") return void 0;
27
- const trimmed = value.trim().toLowerCase();
28
- const named = NAME_TO_HEX.get(trimmed);
29
- if (named) return named;
30
- if (HEX_RE.test(trimmed)) return trimmed;
31
- return void 0;
32
- }
33
- function pickSwarmColor(seed) {
34
- let hash = 0;
35
- for (let i = 0; i < seed.length; i += 1) hash = hash * 31 + seed.charCodeAt(i) >>> 0;
36
- return SWARM_COLORS[hash % SWARM_COLORS.length].hex;
37
- }
38
- function swarmColorName(hex) {
39
- return HEX_TO_NAME.get(hex.toLowerCase());
40
- }
41
- function contrastTextColor(bgHex) {
42
- const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/u.exec(bgHex.toLowerCase());
43
- if (!match) return "#ffffff";
44
- const [r, g, b] = match.slice(1).map((pair) => Number.parseInt(pair, 16));
45
- const channel = (value) => {
46
- const s = value / 255;
47
- return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
48
- };
49
- const luminance = 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
50
- const onBlack = (luminance + 0.05) / 0.05;
51
- const onWhite = 1.05 / (luminance + 0.05);
52
- return onBlack >= onWhite ? "#000000" : "#ffffff";
53
- }
54
- function badge(text, bgHex, fgHex) {
55
- try {
56
- return styleText(text, { fg: parseColor(fgHex), bg: parseColor(bgHex) }, getTerminalColorMode());
57
- } catch {
58
- return text;
59
- }
60
- }
11
+ safeTerminalText,
12
+ swarmColorName,
13
+ swarmColorPalette
14
+ } from "./chunks/chunk-77JHO3GV.ts";
61
15
 
62
16
  // src/protocol.ts
63
17
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -689,14 +643,131 @@ import { constants } from "node:fs";
689
643
  import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
690
644
  import { basename, dirname, join } from "node:path";
691
645
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
646
+
647
+ // src/auto-name.ts
648
+ import { contentText } from "@earendil-works/pi-ai";
649
+ var AUTO_NAME_PREFIX = "MAN-";
650
+ var AUTO_NAME_TURN_THRESHOLD = 3;
651
+ var AUTO_NAME_MAX_TITLE_CHARS = 24;
652
+ var AUTO_NAME_MAX_MESSAGE_CHARS = 500;
653
+ var AUTO_NAME_MAX_CONTEXT_CHARS = 2e3;
654
+ var AUTO_NAME_TIMEOUT_MS = 12e4;
655
+ var AUTO_NAME_MAX_ATTEMPTS = 3;
656
+ var DEFAULT_MANAGER_NAME_PATTERN = /^MANAGER-\S{8}$/u;
657
+ var AUTO_NAME_MODEL_PATTERN = /^[^\s/]+\/[^\s/]+$/u;
658
+ function isDefaultManagerName(name) {
659
+ return name !== void 0 && DEFAULT_MANAGER_NAME_PATTERN.test(name);
660
+ }
661
+ function isAutoNameModel(value) {
662
+ return AUTO_NAME_MODEL_PATTERN.test(value);
663
+ }
664
+ function toAutoName(raw) {
665
+ if (!raw) return void 0;
666
+ const line = safeTerminalLine(raw).replace(/^[\s"'`“”‘’#>*_~-]+/u, "").replace(/[\s"'`“”‘’.,;:!?。,;:!?…·#>*_~-]+$/u, "").trim();
667
+ if (!line) return void 0;
668
+ const title = [...line].slice(0, AUTO_NAME_MAX_TITLE_CHARS).join("");
669
+ return `${AUTO_NAME_PREFIX}${title}`;
670
+ }
671
+ function collectAutoNameMessages(ctx) {
672
+ const messages = [];
673
+ let total = 0;
674
+ for (const entry of ctx.sessionManager.getBranch()) {
675
+ if (messages.length >= AUTO_NAME_TURN_THRESHOLD || total >= AUTO_NAME_MAX_CONTEXT_CHARS) break;
676
+ if (entry.type !== "message") continue;
677
+ const message = entry.message;
678
+ if (!isRecord2(message) || message.role !== "user") continue;
679
+ const content = message.content;
680
+ if (typeof content !== "string" && !Array.isArray(content)) continue;
681
+ const text = safeTerminalLine(contentText(content));
682
+ if (!text) continue;
683
+ const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
684
+ messages.push(clipped);
685
+ total += clipped.length;
686
+ }
687
+ return messages;
688
+ }
689
+ function buildAutoNamePrompt(messages) {
690
+ return [
691
+ "Summarize the user's goal in this conversation as a short session title.",
692
+ "",
693
+ "Rules:",
694
+ "- Reply with only the title: no quotes, no prefix, no trailing punctuation.",
695
+ "- Use the same language as the user messages.",
696
+ `- Keep it under ${AUTO_NAME_MAX_TITLE_CHARS} characters.`,
697
+ '- Name the task or topic, for example "\u4FEE\u590D\u767B\u5F55\u9875\u6837\u5F0F" or "Add payments API retry".',
698
+ "",
699
+ "User messages:",
700
+ ...messages.map((message, index) => `${index + 1}. ${message}`)
701
+ ].join("\n");
702
+ }
703
+ function resolveAutoNameModel(ctx, configured) {
704
+ if (!configured) return ctx.model;
705
+ const slash = configured.indexOf("/");
706
+ return ctx.modelRegistry.find(configured.slice(0, slash), configured.slice(slash + 1));
707
+ }
708
+ async function completeSessionTitle(ctx, model, prompt, signal) {
709
+ const message = await ctx.modelRegistry.complete(
710
+ model,
711
+ { messages: [{ role: "user", content: prompt, timestamp: Date.now() }] },
712
+ { signal }
713
+ );
714
+ return contentText(message.content);
715
+ }
716
+ var AutoNamer = class {
717
+ turnsSeen = 0;
718
+ attempts = 0;
719
+ userNamed = false;
720
+ reset() {
721
+ this.turnsSeen = 0;
722
+ this.attempts = 0;
723
+ this.userNamed = false;
724
+ }
725
+ /**
726
+ * Record a name change produced outside the auto-namer. A default manager
727
+ * name is the extension's own bootstrap and ignored; anything else means the
728
+ * user (or a handoff) owns the name and auto-naming stays out of the way.
729
+ */
730
+ noteExternalName(name) {
731
+ if (isDefaultManagerName(name)) return;
732
+ this.userNamed = true;
733
+ }
734
+ /**
735
+ * Count one completed turn and report whether an auto-name attempt should
736
+ * start now. Each returned true consumes one attempt; after a successful
737
+ * naming the session no longer carries the default name, so later turns
738
+ * permanently settle via the userNamed path.
739
+ */
740
+ noteTurn(currentName, enabled) {
741
+ if (this.userNamed) return false;
742
+ this.turnsSeen += 1;
743
+ if (this.turnsSeen < AUTO_NAME_TURN_THRESHOLD) return false;
744
+ if (currentName !== void 0 && !isDefaultManagerName(currentName)) {
745
+ this.userNamed = true;
746
+ return false;
747
+ }
748
+ if (!enabled || this.attempts >= AUTO_NAME_MAX_ATTEMPTS) return false;
749
+ this.attempts += 1;
750
+ return true;
751
+ }
752
+ };
753
+ function isRecord2(value) {
754
+ return typeof value === "object" && value !== null && !Array.isArray(value);
755
+ }
756
+
757
+ // src/settings.ts
692
758
  var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
693
759
  var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
694
760
  var DEFAULT_SWARM_SETTINGS = Object.freeze({
761
+ autoName: true,
762
+ colorPalette: "muted",
695
763
  confirmSessionLaunch: true,
696
764
  externalCommand: "alacritty -e",
697
765
  pinToLeadWorkspace: false
698
766
  });
699
767
  var SETTING_FIELDS = [
768
+ "autoName",
769
+ "autoNameModel",
770
+ "colorPalette",
700
771
  "confirmSessionLaunch",
701
772
  "externalCommand",
702
773
  "pinToLeadWorkspace"
@@ -706,9 +777,26 @@ function swarmSettingsFilePath() {
706
777
  return join(getAgentDir(), SWARM_SETTINGS_FILE);
707
778
  }
708
779
  function normalizeSwarmSettingsDocument(value) {
709
- if (!isRecord2(value)) return void 0;
780
+ if (!isRecord3(value)) return void 0;
710
781
  const settings = { ...DEFAULT_SWARM_SETTINGS };
711
782
  const sources = builtInSources();
783
+ if (Object.hasOwn(value, "autoName")) {
784
+ if (typeof value.autoName !== "boolean") return void 0;
785
+ settings.autoName = value.autoName;
786
+ sources.autoName = "user";
787
+ }
788
+ if (Object.hasOwn(value, "autoNameModel")) {
789
+ if (typeof value.autoNameModel !== "string" || !isAutoNameModel(value.autoNameModel.trim())) {
790
+ return void 0;
791
+ }
792
+ settings.autoNameModel = value.autoNameModel.trim();
793
+ sources.autoNameModel = "user";
794
+ }
795
+ if (Object.hasOwn(value, "colorPalette")) {
796
+ if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return void 0;
797
+ settings.colorPalette = value.colorPalette;
798
+ sources.colorPalette = "user";
799
+ }
712
800
  if (Object.hasOwn(value, "confirmSessionLaunch")) {
713
801
  if (typeof value.confirmSessionLaunch !== "boolean") return void 0;
714
802
  settings.confirmSessionLaunch = value.confirmSessionLaunch;
@@ -748,7 +836,7 @@ async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
748
836
  try {
749
837
  const document = JSON.parse(text);
750
838
  const normalized = normalizeSwarmSettingsDocument(document);
751
- if (!normalized || !isRecord2(document)) {
839
+ if (!normalized || !isRecord3(document)) {
752
840
  return invalidLoad(path2, "the document is malformed or contains an invalid setting");
753
841
  }
754
842
  return { kind: "loaded", path: path2, document, ...normalized };
@@ -772,6 +860,9 @@ function createInMemorySwarmSettingsRuntime() {
772
860
  settings: { ...state.settings, ...canonical },
773
861
  sources: {
774
862
  ...state.sources,
863
+ ...canonical.autoName !== void 0 ? { autoName: "user" } : {},
864
+ ...canonical.autoNameModel !== void 0 ? { autoNameModel: "user" } : {},
865
+ ...canonical.colorPalette !== void 0 ? { colorPalette: "user" } : {},
775
866
  ...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
776
867
  ...canonical.externalCommand ? { externalCommand: "user" } : {},
777
868
  ...canonical.pinToLeadWorkspace !== void 0 ? { pinToLeadWorkspace: "user" } : {}
@@ -844,7 +935,7 @@ function createSwarmSettingsRuntime(options = {}) {
844
935
  };
845
936
  }
846
937
  function normalizePatch(patch) {
847
- if (!isRecord2(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
938
+ if (!isRecord3(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
848
939
  throw new Error("Refusing to update unknown Pi Agent Swarm settings.");
849
940
  }
850
941
  const normalized = normalizeSwarmSettingsDocument(patch);
@@ -929,6 +1020,9 @@ function invalidLoad(path2, reason) {
929
1020
  }
930
1021
  function builtInSources() {
931
1022
  return {
1023
+ autoName: "built-in",
1024
+ autoNameModel: "built-in",
1025
+ colorPalette: "built-in",
932
1026
  confirmSessionLaunch: "built-in",
933
1027
  externalCommand: "built-in",
934
1028
  pinToLeadWorkspace: "built-in"
@@ -941,7 +1035,7 @@ function freezeState(state) {
941
1035
  sources: Object.freeze({ ...state.sources })
942
1036
  });
943
1037
  }
944
- function isRecord2(value) {
1038
+ function isRecord3(value) {
945
1039
  return typeof value === "object" && value !== null && !Array.isArray(value);
946
1040
  }
947
1041
  function isNodeError(error) {
@@ -1073,6 +1167,32 @@ function throwIfAborted2(signal, message) {
1073
1167
  throw error;
1074
1168
  }
1075
1169
 
1170
+ // src/footer.ts
1171
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
1172
+ var ROLE_BADGE_BACKGROUND = "#ffc85a";
1173
+ var FOOTER_WIDTH_FRACTION = 0.55;
1174
+ var SHORT_ID_LENGTH = 8;
1175
+ var DEFAULT_TERMINAL_COLUMNS = 80;
1176
+ var MIN_NAME_BUDGET = 8;
1177
+ var NAME_BADGE_OVERHEAD = 4;
1178
+ function buildRosterBadge(input) {
1179
+ const name = input.name ? safeTerminalLine(input.name) : "";
1180
+ const sessionId = safeTerminalLine(input.sessionId);
1181
+ const roleBadge = badge(` ${input.role} `, ROLE_BADGE_BACKGROUND, "#000000");
1182
+ const nameBadge = (value) => badge(value ? ` \u25CF ${value} ` : " \u25CF ", input.color, contrastTextColor(input.color));
1183
+ const available = Math.max(0, Math.floor(input.columns * FOOTER_WIDTH_FRACTION));
1184
+ const full = `${nameBadge(name)}${badge(` ${sessionId} `, "#ffffff", "#000000")}${roleBadge}`;
1185
+ if (visibleWidth(full) <= available) return full;
1186
+ const shortId = [...sessionId].slice(0, SHORT_ID_LENGTH).join("");
1187
+ const shortIdBadge = badge(` ${shortId} `, "#ffffff", "#000000");
1188
+ const nameBudget = available - visibleWidth(roleBadge) - visibleWidth(shortIdBadge) - NAME_BADGE_OVERHEAD;
1189
+ if (nameBudget >= MIN_NAME_BUDGET) {
1190
+ const truncated = visibleWidth(name) > nameBudget ? truncateToWidth(name, nameBudget, "\u2026") : name;
1191
+ return `${nameBadge(truncated)}${shortIdBadge}${roleBadge}`;
1192
+ }
1193
+ return `${nameBadge("")}${roleBadge}`;
1194
+ }
1195
+
1076
1196
  // src/launch-envelope.ts
1077
1197
  var SWARM_LAUNCH_ENV_KEYS = [
1078
1198
  "PI_SWARM_INVITE",
@@ -1304,14 +1424,14 @@ function readManifest(packageDirectory) {
1304
1424
  } catch {
1305
1425
  throw resolutionError(packageDirectory, "the package manifest is unavailable or invalid");
1306
1426
  }
1307
- if (!isRecord3(value) || value.name !== CORE_PACKAGE_NAME) {
1427
+ if (!isRecord4(value) || value.name !== CORE_PACKAGE_NAME) {
1308
1428
  throw resolutionError(packageDirectory, "the package manifest has an unexpected package name");
1309
1429
  }
1310
1430
  return value;
1311
1431
  }
1312
1432
  function resolveDeclaredBin(packageDirectory, manifest) {
1313
1433
  const bin = manifest.bin;
1314
- const piBin = isRecord3(bin) ? bin.pi : void 0;
1434
+ const piBin = isRecord4(bin) ? bin.pi : void 0;
1315
1435
  if (typeof piBin !== "string" || !piBin.trim()) {
1316
1436
  throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
1317
1437
  }
@@ -1364,7 +1484,7 @@ function resolutionError(packageDirectory, reason) {
1364
1484
  `Unable to resolve the Pi CLI from ${JSON.stringify(displayed)}: ${reason}. Reinstall the matching Pi core package before spawning a session.`
1365
1485
  );
1366
1486
  }
1367
- function isRecord3(value) {
1487
+ function isRecord4(value) {
1368
1488
  return typeof value === "object" && value !== null && !Array.isArray(value);
1369
1489
  }
1370
1490
 
@@ -2038,6 +2158,9 @@ var SwarmTransport = class {
2038
2158
  setColor(color) {
2039
2159
  this.peer.color = color;
2040
2160
  }
2161
+ setName(name) {
2162
+ this.peer.name = name;
2163
+ }
2041
2164
  get peerDescription() {
2042
2165
  return { ...this.peer };
2043
2166
  }
@@ -2691,7 +2814,6 @@ function assertPositiveDuration2(value, label) {
2691
2814
  // src/swarm-controller.ts
2692
2815
  var STATUS_KEY = "swarm";
2693
2816
  var ROSTER_STATUS_KEY = "swarm-roster";
2694
- var ROLE_BADGE_BACKGROUND = "#ffc85a";
2695
2817
  var DEFAULT_LAUNCH_TIMEOUT_MS = 15e3;
2696
2818
  var DEFAULT_POLL_INTERVAL_MS2 = 100;
2697
2819
  var RELOAD_HANDOFF_TTL_MS = 3e4;
@@ -2707,7 +2829,8 @@ function defaultSwarmControllerDependencies(pi) {
2707
2829
  randomId: (prefix) => `${prefix}_${randomBytes5(16).toString("hex")}`,
2708
2830
  sleep: abortableSleep2,
2709
2831
  launchTimeoutMs: DEFAULT_LAUNCH_TIMEOUT_MS,
2710
- environment: process.env
2832
+ environment: process.env,
2833
+ terminalColumns: () => process.stdout.isTTY ? process.stdout.columns : void 0
2711
2834
  };
2712
2835
  }
2713
2836
  var SwarmController = class {
@@ -2731,7 +2854,15 @@ var SwarmController = class {
2731
2854
  leadSessionId;
2732
2855
  /** A human-started session is the default lead of its own (not yet started) group. */
2733
2856
  defaultLead = false;
2857
+ autoNamer = new AutoNamer();
2858
+ /** Auto-naming applies only to human-started sessions, never to spawned children. */
2859
+ autoNameEligible = false;
2860
+ /** Set while the auto-namer applies its own name so the change is not read as manual. */
2861
+ applyingAutoName;
2862
+ autoNameInFlight = false;
2734
2863
  leadWatcher;
2864
+ resizeListener = () => this.onTerminalResize();
2865
+ resizeWatching = false;
2735
2866
  pendingKickoffIds = /* @__PURE__ */ new Set();
2736
2867
  relayChain = Promise.resolve();
2737
2868
  async sessionStart(event, ctx) {
@@ -2746,9 +2877,14 @@ var SwarmController = class {
2746
2877
  this.parentSessionId = void 0;
2747
2878
  this.leadSessionId = void 0;
2748
2879
  this.defaultLead = false;
2880
+ this.autoNamer.reset();
2881
+ this.autoNameEligible = false;
2882
+ this.applyingAutoName = void 0;
2883
+ this.autoNameInFlight = false;
2749
2884
  this.pendingKickoffIds.clear();
2750
2885
  this.relayChain = Promise.resolve();
2751
2886
  this.startLeadWatcher();
2887
+ this.startResizeWatcher();
2752
2888
  const owner = ctx.sessionManager;
2753
2889
  const ownerGeneration = this.generation;
2754
2890
  let envelope;
@@ -2772,6 +2908,7 @@ var SwarmController = class {
2772
2908
  this.pi.setSessionName(`MANAGER-${ctx.sessionManager.getSessionId().slice(0, 8)}`);
2773
2909
  }
2774
2910
  this.defaultLead = true;
2911
+ this.autoNameEligible = true;
2775
2912
  await this.renderFooterStatus(ctx);
2776
2913
  return;
2777
2914
  }
@@ -2823,6 +2960,7 @@ var SwarmController = class {
2823
2960
  async sessionShutdown(event, ctx) {
2824
2961
  if (ctx.sessionManager !== this.activeSessionManager) return;
2825
2962
  this.stopLeadWatcher();
2963
+ this.stopResizeWatcher();
2826
2964
  if (event.reason === "reload" && this.membership) {
2827
2965
  const membership = this.membership;
2828
2966
  const peerName = this.pi.getSessionName() ?? membership.transport.peerDescription.name;
@@ -3018,7 +3156,8 @@ var SwarmController = class {
3018
3156
  const launchId = this.deps.randomId("launch");
3019
3157
  const kickoffCapability = this.deps.randomId("kickoff");
3020
3158
  const name = normalizeOptionalText(input.name, "name", 200) ?? `Swarm ${launchId.slice(-6)}`;
3021
- const color = normalizeSwarmColor(input.color) ?? pickSwarmColor(name);
3159
+ const palette = this.activePalette();
3160
+ const color = normalizeSwarmColor(input.color, palette) ?? pickSwarmColor(name, palette);
3022
3161
  const modelSpec = normalizeOptionalText(input.model, "model", 200);
3023
3162
  let childModel;
3024
3163
  if (modelSpec) {
@@ -3211,7 +3350,7 @@ var SwarmController = class {
3211
3350
  protocolVersion: SWARM_PROTOCOL_VERSION,
3212
3351
  sessionId: ctx.sessionManager.getSessionId(),
3213
3352
  ...this.pi.getSessionName() ? { name: this.pi.getSessionName() } : {},
3214
- color: this.color ?? pickSwarmColor(ctx.sessionManager.getSessionId()),
3353
+ color: this.color ?? pickSwarmColor(ctx.sessionManager.getSessionId(), this.activePalette()),
3215
3354
  cwd: ctx.cwd,
3216
3355
  pid: process.pid,
3217
3356
  ...launchId ? { launchId } : {},
@@ -3356,12 +3495,12 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3356
3495
  assertCurrentContext(ctx) {
3357
3496
  if (!this.isCurrent(ctx)) throw staleError();
3358
3497
  }
3359
- async cleanupActive(_reloading) {
3498
+ async cleanupActive(reloading) {
3360
3499
  this.generation += 1;
3361
3500
  this.controller.abort();
3362
3501
  let cleanupError;
3363
3502
  try {
3364
- await this.leaveGroupInternal();
3503
+ await this.leaveGroupInternal(reloading);
3365
3504
  } catch (error) {
3366
3505
  cleanupError = error;
3367
3506
  }
@@ -3371,7 +3510,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3371
3510
  this.activeSessionManager = void 0;
3372
3511
  if (cleanupError) throw cleanupError;
3373
3512
  }
3374
- leaveGroupInternal() {
3513
+ leaveGroupInternal(reloading = false) {
3375
3514
  return this.mutateMembership(async () => {
3376
3515
  const membership = this.membership;
3377
3516
  const directory = membership?.transport.endpointManifest?.directory;
@@ -3383,7 +3522,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3383
3522
  } finally {
3384
3523
  membership?.group.secret.fill(0);
3385
3524
  }
3386
- if (directory && self && this.leadSessionId === self.sessionId) {
3525
+ if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
3387
3526
  await rm5(join7(directory, "lead.json"), { force: true }).catch(() => void 0);
3388
3527
  }
3389
3528
  this.leadSessionId = void 0;
@@ -3473,13 +3612,12 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3473
3612
  }
3474
3613
  const sessionId = self?.sessionId ?? ctx.sessionManager.getSessionId();
3475
3614
  const name = self?.name ?? this.pi.getSessionName();
3476
- const color = this.color ?? self?.color ?? pickSwarmColor(sessionId);
3615
+ const color = this.color ?? self?.color ?? pickSwarmColor(sessionId, this.activePalette());
3477
3616
  const role = this.leadSessionId === sessionId || !self && this.defaultLead ? "LEADER" : "WORKER";
3478
- const nameBadge = badge(name ? ` \u25CF ${name} ` : " \u25CF ", color, contrastTextColor(color));
3479
- const idBadge = badge(` ${sessionId} `, "#ffffff", "#000000");
3480
- const roleBadge = badge(` ${role} `, ROLE_BADGE_BACKGROUND, "#000000");
3617
+ const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
3618
+ const status = buildRosterBadge({ name, sessionId, color, role, columns });
3481
3619
  try {
3482
- ctx.ui.setStatus(ROSTER_STATUS_KEY, `${nameBadge}${idBadge}${roleBadge}`);
3620
+ ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
3483
3621
  } catch {
3484
3622
  }
3485
3623
  }
@@ -3513,12 +3651,122 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3513
3651
  await this.broadcastLeadChange(target);
3514
3652
  await this.renderFooterStatus(ctx);
3515
3653
  }
3516
- async setOwnColor(ctx, color) {
3654
+ /** Resolve a palette name or #rrggbb hex against the active `colorPalette` setting. */
3655
+ normalizeColor(value) {
3656
+ return normalizeSwarmColor(value, this.activePalette());
3657
+ }
3658
+ activePalette() {
3659
+ return swarmColorPalette(this.settings.get().settings.colorPalette);
3660
+ }
3661
+ /**
3662
+ * Persist the roster palette and keep this session on the same hue slot under
3663
+ * the new palette. Peers keep their announced colors; their own sessions decide
3664
+ * locally whether to follow a palette change.
3665
+ */
3666
+ async setColorPalette(ctx, palette, signal) {
3517
3667
  this.assertCurrentContext(ctx);
3668
+ throwIfAborted5(signal, "Pi Agent Swarm palette change aborted");
3669
+ await this.settings.update({ colorPalette: palette });
3670
+ this.assertCurrentContext(ctx);
3671
+ throwIfAborted5(signal, "Pi Agent Swarm palette change aborted");
3672
+ const slot = this.color ? swarmColorName(this.color) : void 0;
3673
+ if (slot) {
3674
+ const next = this.activePalette().find((color) => color.name === slot);
3675
+ if (next && next.hex !== this.color) {
3676
+ this.color = next.hex;
3677
+ this.membership?.transport.setColor(next.hex);
3678
+ }
3679
+ }
3680
+ await this.renderFooterStatus(ctx);
3681
+ }
3682
+ async setOwnColor(ctx, color, signal) {
3683
+ this.assertCurrentContext(ctx);
3684
+ throwIfAborted5(signal, "Pi Agent Swarm color change aborted");
3518
3685
  this.color = color;
3519
3686
  this.membership?.transport.setColor(color);
3520
3687
  await this.renderFooterStatus(ctx);
3521
3688
  }
3689
+ async setOwnName(ctx, name, signal) {
3690
+ this.assertCurrentContext(ctx);
3691
+ throwIfAborted5(signal, "Pi Agent Swarm rename aborted");
3692
+ const normalized = normalizeOptionalText(name, "name", 200);
3693
+ if (!normalized) throw new Error("Pi Agent Swarm session name must not be empty");
3694
+ this.pi.setSessionName(normalized);
3695
+ this.membership?.transport.setName(normalized);
3696
+ await this.renderFooterStatus(ctx);
3697
+ }
3698
+ /**
3699
+ * Count completed turns and start the one-shot auto-name attempt for a
3700
+ * human-started session. The attempt runs in the background as an owned task
3701
+ * so shutdown waits for it; it never blocks the turn_end event path. The
3702
+ * returned promise resolves when the attempt settles (tests await it).
3703
+ */
3704
+ noteTurnEnd(ctx) {
3705
+ if (!this.isCurrent(ctx)) return Promise.resolve();
3706
+ if (!this.autoNameEligible) return Promise.resolve();
3707
+ if (this.autoNameInFlight) return Promise.resolve();
3708
+ if (!this.autoNamer.noteTurn(this.pi.getSessionName(), this.settings.get().settings.autoName)) {
3709
+ return Promise.resolve();
3710
+ }
3711
+ this.autoNameInFlight = true;
3712
+ const task = this.runAutoName(ctx, ctx.sessionManager, this.generation).finally(() => {
3713
+ this.autoNameInFlight = false;
3714
+ });
3715
+ return this.track(task);
3716
+ }
3717
+ /**
3718
+ * Keep the roster peer name and the footer badge in sync when the session
3719
+ * name changes outside the extension (for example `/name`), and treat a
3720
+ * custom name as the user taking over so auto-naming steps aside.
3721
+ */
3722
+ async noteSessionInfoChanged(name, ctx) {
3723
+ if (!this.isCurrent(ctx)) return;
3724
+ if (name === void 0 || name !== this.applyingAutoName) this.autoNamer.noteExternalName(name);
3725
+ if (name) this.membership?.transport.setName(name);
3726
+ await this.renderFooterStatus(ctx);
3727
+ }
3728
+ /**
3729
+ * Best-effort naming: summarize the first turns into `MAN-<title>` with the
3730
+ * current (or configured) model. Any failure keeps the default MANAGER-<id>
3731
+ * name, is recorded as a session entry for diagnosis, and is retried on a
3732
+ * later turn until the attempt budget runs out. The session name is
3733
+ * re-checked right before applying so a rename that happened during the
3734
+ * completion always wins.
3735
+ */
3736
+ async runAutoName(ctx, owner, ownerGeneration) {
3737
+ try {
3738
+ const configured = this.settings.get().settings.autoNameModel;
3739
+ const model = resolveAutoNameModel(ctx, configured);
3740
+ if (!model) {
3741
+ if (configured) {
3742
+ this.notify(
3743
+ ctx,
3744
+ `Pi Agent Swarm could not resolve autoNameModel "${configured}"; keeping the default session name.`,
3745
+ "warning"
3746
+ );
3747
+ }
3748
+ return;
3749
+ }
3750
+ const messages = collectAutoNameMessages(ctx);
3751
+ if (messages.length === 0) return;
3752
+ const signal = AbortSignal.any([this.controller.signal, AbortSignal.timeout(AUTO_NAME_TIMEOUT_MS)]);
3753
+ const complete = this.deps.completeSessionTitle ?? completeSessionTitle;
3754
+ const raw = await complete(ctx, model, buildAutoNamePrompt(messages), signal);
3755
+ if (!this.isCurrent(owner, ownerGeneration)) return;
3756
+ const name = toAutoName(raw);
3757
+ if (!name) return;
3758
+ const currentName = this.pi.getSessionName();
3759
+ if (currentName !== void 0 && !isDefaultManagerName(currentName)) return;
3760
+ this.applyingAutoName = name;
3761
+ try {
3762
+ await this.setOwnName(ctx, name, signal);
3763
+ } finally {
3764
+ this.applyingAutoName = void 0;
3765
+ }
3766
+ } catch (error) {
3767
+ this.pi.appendEntry("pi-swarm-auto-name", { ok: false, error: safeTerminalLine(safeError(error)) });
3768
+ }
3769
+ }
3522
3770
  /**
3523
3771
  * Best-effort, ordered relay of a direct user steer to the parent session so it
3524
3772
  * stays aligned. This returns immediately: sends are chained so ordering is
@@ -3598,6 +3846,27 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3598
3846
  this.leadWatcher = void 0;
3599
3847
  }
3600
3848
  }
3849
+ // A resized terminal can cross a footer tier boundary, so re-render the badge with
3850
+ // the new width. The listener is TTY-only and session-owned: attached at session
3851
+ // start, detached at shutdown, and idempotent against repeated calls.
3852
+ startResizeWatcher() {
3853
+ this.stopResizeWatcher();
3854
+ if (!process.stdout.isTTY || typeof process.stdout.on !== "function") return;
3855
+ process.stdout.on("resize", this.resizeListener);
3856
+ this.resizeWatching = true;
3857
+ }
3858
+ stopResizeWatcher() {
3859
+ if (this.resizeWatching) {
3860
+ process.stdout.off("resize", this.resizeListener);
3861
+ this.resizeWatching = false;
3862
+ }
3863
+ }
3864
+ onTerminalResize() {
3865
+ if (this.controller.signal.aborted) return;
3866
+ const activeContext = this.activeContext;
3867
+ if (!activeContext) return;
3868
+ void this.renderFooterStatus(activeContext);
3869
+ }
3601
3870
  notify(ctx, message, level) {
3602
3871
  if (!ctx.hasUI) return;
3603
3872
  try {
@@ -3610,11 +3879,11 @@ function recentSwarmState(ctx) {
3610
3879
  const messageIds = [];
3611
3880
  const consumedLaunchIds = /* @__PURE__ */ new Set();
3612
3881
  for (const entry of ctx.sessionManager.getBranch().slice(-1024)) {
3613
- if (!isRecord4(entry) || entry.type !== "custom_message" || entry.customType !== SWARM_MESSAGE_TYPE) {
3882
+ if (!isRecord5(entry) || entry.type !== "custom_message" || entry.customType !== SWARM_MESSAGE_TYPE) {
3614
3883
  continue;
3615
3884
  }
3616
3885
  const details = entry.details;
3617
- if (!isRecord4(details) || !isRecord4(details.message) || typeof details.message.id !== "string") {
3886
+ if (!isRecord5(details) || !isRecord5(details.message) || typeof details.message.id !== "string") {
3618
3887
  continue;
3619
3888
  }
3620
3889
  messageIds.push(details.message.id);
@@ -3658,7 +3927,7 @@ function truncateToBytes(value, maxBytes) {
3658
3927
  if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
3659
3928
  return Buffer.from(value, "utf8").subarray(0, maxBytes).toString("utf8");
3660
3929
  }
3661
- function isRecord4(value) {
3930
+ function isRecord5(value) {
3662
3931
  return typeof value === "object" && value !== null && !Array.isArray(value);
3663
3932
  }
3664
3933
 
@@ -3895,7 +4164,7 @@ function createPiSwarmExtension(dependencies = {}) {
3895
4164
  return function piSwarmExtension(pi) {
3896
4165
  const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
3897
4166
  const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
3898
- const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-MZS6N2VS.ts")));
4167
+ const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-RH6GY6U4.ts")));
3899
4168
  pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
3900
4169
  registerSwarmTools(pi, controller);
3901
4170
  pi.on("session_start", async (event, ctx) => {
@@ -3904,12 +4173,18 @@ function createPiSwarmExtension(dependencies = {}) {
3904
4173
  pi.on("session_shutdown", async (event, ctx) => {
3905
4174
  await controller.sessionShutdown(event, ctx);
3906
4175
  });
4176
+ pi.on("turn_end", async (_event, ctx) => {
4177
+ controller.noteTurnEnd(ctx);
4178
+ });
4179
+ pi.on("session_info_changed", async (event, ctx) => {
4180
+ await controller.noteSessionInfoChanged(event.name, ctx);
4181
+ });
3907
4182
  pi.on("input", async (event, ctx) => {
3908
4183
  if (event.source !== "interactive") return;
3909
4184
  void controller.relaySteerInput(event.text, ctx);
3910
4185
  });
3911
4186
  pi.registerCommand("swarm", {
3912
- description: "Spawn and connect local Pi sessions",
4187
+ description: "Spawn a worker Pi session, or start/join a local group",
3913
4188
  handler: async (rawArgs, ctx) => {
3914
4189
  const args = rawArgs.trim();
3915
4190
  if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
@@ -3926,7 +4201,7 @@ function createPiSwarmExtension(dependencies = {}) {
3926
4201
  const ownerSignal = controller.sessionSignal;
3927
4202
  const menuModule = await loadMenu();
3928
4203
  if (ownerSignal.aborted || !controller.isCurrent(ctx)) return;
3929
- await menuModule.showSwarmMenu(ctx, menuSource(controller, settings, ctx), {
4204
+ await menuModule.showSwarmMenu(ctx, menuSource(controller), {
3930
4205
  signal: ownerSignal,
3931
4206
  isCurrent: () => controller.isCurrent(ctx) && !ownerSignal.aborted
3932
4207
  });
@@ -3947,7 +4222,7 @@ function createPiSwarmExtension(dependencies = {}) {
3947
4222
  pi.registerCommand("color", {
3948
4223
  description: "Set this session's color (palette name or #rrggbb)",
3949
4224
  handler: async (rawArgs, ctx) => {
3950
- const color = normalizeSwarmColor(rawArgs.trim());
4225
+ const color = controller.normalizeColor(rawArgs.trim());
3951
4226
  if (!color) {
3952
4227
  throw new Error("Usage: /color <red|orange|yellow|green|cyan|blue|magenta|purple|#rrggbb>");
3953
4228
  }
@@ -3984,13 +4259,9 @@ async function startGroupDirectly(controller, ctx) {
3984
4259
  ctx.ui.notify("Started a local Pi Agent Swarm group. You are its lead.", "info");
3985
4260
  }
3986
4261
  }
3987
- function menuSource(controller, settings, ctx) {
4262
+ function menuSource(controller) {
3988
4263
  return {
3989
- snapshot: async (signal) => ({
3990
- ...await controller.snapshot(signal),
3991
- ...settings.get(),
3992
- settingsPath: settings.getPath()
3993
- }),
4264
+ snapshot: (signal) => controller.snapshot(signal),
3994
4265
  spawn: async (commandContext, input, signal) => {
3995
4266
  const result = await controller.spawn(commandContext, input, signal);
3996
4267
  if (controller.isCurrent(commandContext)) {
@@ -4000,38 +4271,26 @@ function menuSource(controller, settings, ctx) {
4000
4271
  );
4001
4272
  }
4002
4273
  },
4003
- start: async (commandContext, signal) => {
4004
- await controller.startNewGroup(commandContext, false, signal);
4274
+ rename: async (commandContext, name, signal) => {
4275
+ await controller.setOwnName(commandContext, name, signal);
4005
4276
  if (controller.isCurrent(commandContext)) {
4006
- commandContext.ui.notify("Started a local Pi Agent Swarm group.", "info");
4277
+ commandContext.ui.notify(`Session renamed to ${safeTerminalLine(name)}.`, "info");
4007
4278
  }
4008
4279
  },
4009
- join: async (commandContext, invite, signal) => {
4010
- try {
4011
- await controller.joinInvite(commandContext, invite, false, signal);
4012
- } catch (error) {
4013
- throw new Error(`Could not join Pi Agent Swarm: ${safeError(error)}`);
4280
+ setColor: async (commandContext, color, signal) => {
4281
+ const normalized = controller.normalizeColor(color);
4282
+ if (!normalized) throw new Error("Pi Agent Swarm color is invalid");
4283
+ await controller.setOwnColor(commandContext, normalized, signal);
4284
+ if (controller.isCurrent(commandContext)) {
4285
+ commandContext.ui.notify(`Color set to ${normalized}.`, "info");
4014
4286
  }
4015
4287
  },
4016
- send: async (commandContext, options, signal) => {
4017
- const result = await controller.send(commandContext, options, signal);
4018
- if (!result.acknowledgement.accepted) {
4019
- throw new Error(
4020
- `Target rejected the message: ${safeTerminalLine(result.acknowledgement.error ?? "unknown reason")}`
4021
- );
4022
- }
4288
+ setPalette: async (commandContext, palette, signal) => {
4289
+ await controller.setColorPalette(commandContext, palette, signal);
4023
4290
  if (controller.isCurrent(commandContext)) {
4024
- commandContext.ui.notify(
4025
- `Target accepted ${safeTerminalLine(result.message.id)}. This does not prove task completion.`,
4026
- "info"
4027
- );
4291
+ commandContext.ui.notify(`Theme set to ${palette}.`, "info");
4028
4292
  }
4029
- },
4030
- updateSettings: async (patch) => {
4031
- await settings.update(patch);
4032
- },
4033
- setAcceptsRequests: (value) => controller.setAcceptsRequests(ctx, value),
4034
- leave: () => controller.leave(ctx)
4293
+ }
4035
4294
  };
4036
4295
  }
4037
4296
  function cachedModuleLoader(load) {