pi-agent-swarm 0.2.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/LICENSE CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2026 narumiruna
4
+ Copyright (c) 2026 fishing-dev-sm
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -143,7 +143,9 @@ Edit user settings in `<getAgentDir()>/pi-agent-swarm.json`, normally `~/.pi/age
143
143
  "colorPalette": "muted",
144
144
  "externalCommand": "alacritty -e",
145
145
  "confirmSessionLaunch": true,
146
- "pinToLeadWorkspace": false
146
+ "pinToLeadWorkspace": false,
147
+ "autoName": true,
148
+ "autoNameModel": "anthropic/claude-haiku-4-5"
147
149
  }
148
150
  ```
149
151
 
@@ -153,6 +155,8 @@ Edit user settings in `<getAgentDir()>/pi-agent-swarm.json`, normally `~/.pi/age
153
155
  | `externalCommand` | any terminal command | `alacritty -e` | Command used to open each new window. |
154
156
  | `confirmSessionLaunch` | `true`, `false` | `true` | Shows or skips the final launch preview for tool launches. |
155
157
  | `pinToLeadWorkspace` | `true`, `false` | `false` | Moves each new window onto the lead session's workspace instead of the focused one. |
158
+ | `autoName` | `true`, `false` | `true` | Renames a human-started session from the bootstrap `MANAGER-<id>` name to a `MAN-<title>` summary of its first three completed turns. The rename uses a one-shot completion, retries on later turns if the completion fails, and steps aside forever as soon as you set a name yourself. Spawned child sessions keep their launch names. |
159
+ | `autoNameModel` | `provider/id` | unset | Model used for the `MAN-<title>` completion. When unset, the session's current model is used, so no extra authentication is needed. An unresolvable value keeps the default name and reports a warning. |
156
160
 
157
161
  Pi Agent Swarm does not read project settings or extension-specific environment-variable overrides.
158
162
  A missing file uses the defaults without creating the file.
package/dist/index.ts CHANGED
@@ -643,15 +643,130 @@ import { constants } from "node:fs";
643
643
  import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
644
644
  import { basename, dirname, join } from "node:path";
645
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
646
758
  var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
647
759
  var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
648
760
  var DEFAULT_SWARM_SETTINGS = Object.freeze({
761
+ autoName: true,
649
762
  colorPalette: "muted",
650
763
  confirmSessionLaunch: true,
651
764
  externalCommand: "alacritty -e",
652
765
  pinToLeadWorkspace: false
653
766
  });
654
767
  var SETTING_FIELDS = [
768
+ "autoName",
769
+ "autoNameModel",
655
770
  "colorPalette",
656
771
  "confirmSessionLaunch",
657
772
  "externalCommand",
@@ -662,9 +777,21 @@ function swarmSettingsFilePath() {
662
777
  return join(getAgentDir(), SWARM_SETTINGS_FILE);
663
778
  }
664
779
  function normalizeSwarmSettingsDocument(value) {
665
- if (!isRecord2(value)) return void 0;
780
+ if (!isRecord3(value)) return void 0;
666
781
  const settings = { ...DEFAULT_SWARM_SETTINGS };
667
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
+ }
668
795
  if (Object.hasOwn(value, "colorPalette")) {
669
796
  if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return void 0;
670
797
  settings.colorPalette = value.colorPalette;
@@ -709,7 +836,7 @@ async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
709
836
  try {
710
837
  const document = JSON.parse(text);
711
838
  const normalized = normalizeSwarmSettingsDocument(document);
712
- if (!normalized || !isRecord2(document)) {
839
+ if (!normalized || !isRecord3(document)) {
713
840
  return invalidLoad(path2, "the document is malformed or contains an invalid setting");
714
841
  }
715
842
  return { kind: "loaded", path: path2, document, ...normalized };
@@ -733,6 +860,8 @@ function createInMemorySwarmSettingsRuntime() {
733
860
  settings: { ...state.settings, ...canonical },
734
861
  sources: {
735
862
  ...state.sources,
863
+ ...canonical.autoName !== void 0 ? { autoName: "user" } : {},
864
+ ...canonical.autoNameModel !== void 0 ? { autoNameModel: "user" } : {},
736
865
  ...canonical.colorPalette !== void 0 ? { colorPalette: "user" } : {},
737
866
  ...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
738
867
  ...canonical.externalCommand ? { externalCommand: "user" } : {},
@@ -806,7 +935,7 @@ function createSwarmSettingsRuntime(options = {}) {
806
935
  };
807
936
  }
808
937
  function normalizePatch(patch) {
809
- 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))) {
810
939
  throw new Error("Refusing to update unknown Pi Agent Swarm settings.");
811
940
  }
812
941
  const normalized = normalizeSwarmSettingsDocument(patch);
@@ -891,6 +1020,8 @@ function invalidLoad(path2, reason) {
891
1020
  }
892
1021
  function builtInSources() {
893
1022
  return {
1023
+ autoName: "built-in",
1024
+ autoNameModel: "built-in",
894
1025
  colorPalette: "built-in",
895
1026
  confirmSessionLaunch: "built-in",
896
1027
  externalCommand: "built-in",
@@ -904,7 +1035,7 @@ function freezeState(state) {
904
1035
  sources: Object.freeze({ ...state.sources })
905
1036
  });
906
1037
  }
907
- function isRecord2(value) {
1038
+ function isRecord3(value) {
908
1039
  return typeof value === "object" && value !== null && !Array.isArray(value);
909
1040
  }
910
1041
  function isNodeError(error) {
@@ -1293,14 +1424,14 @@ function readManifest(packageDirectory) {
1293
1424
  } catch {
1294
1425
  throw resolutionError(packageDirectory, "the package manifest is unavailable or invalid");
1295
1426
  }
1296
- if (!isRecord3(value) || value.name !== CORE_PACKAGE_NAME) {
1427
+ if (!isRecord4(value) || value.name !== CORE_PACKAGE_NAME) {
1297
1428
  throw resolutionError(packageDirectory, "the package manifest has an unexpected package name");
1298
1429
  }
1299
1430
  return value;
1300
1431
  }
1301
1432
  function resolveDeclaredBin(packageDirectory, manifest) {
1302
1433
  const bin = manifest.bin;
1303
- const piBin = isRecord3(bin) ? bin.pi : void 0;
1434
+ const piBin = isRecord4(bin) ? bin.pi : void 0;
1304
1435
  if (typeof piBin !== "string" || !piBin.trim()) {
1305
1436
  throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
1306
1437
  }
@@ -1353,7 +1484,7 @@ function resolutionError(packageDirectory, reason) {
1353
1484
  `Unable to resolve the Pi CLI from ${JSON.stringify(displayed)}: ${reason}. Reinstall the matching Pi core package before spawning a session.`
1354
1485
  );
1355
1486
  }
1356
- function isRecord3(value) {
1487
+ function isRecord4(value) {
1357
1488
  return typeof value === "object" && value !== null && !Array.isArray(value);
1358
1489
  }
1359
1490
 
@@ -2723,6 +2854,12 @@ var SwarmController = class {
2723
2854
  leadSessionId;
2724
2855
  /** A human-started session is the default lead of its own (not yet started) group. */
2725
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;
2726
2863
  leadWatcher;
2727
2864
  resizeListener = () => this.onTerminalResize();
2728
2865
  resizeWatching = false;
@@ -2740,6 +2877,10 @@ var SwarmController = class {
2740
2877
  this.parentSessionId = void 0;
2741
2878
  this.leadSessionId = void 0;
2742
2879
  this.defaultLead = false;
2880
+ this.autoNamer.reset();
2881
+ this.autoNameEligible = false;
2882
+ this.applyingAutoName = void 0;
2883
+ this.autoNameInFlight = false;
2743
2884
  this.pendingKickoffIds.clear();
2744
2885
  this.relayChain = Promise.resolve();
2745
2886
  this.startLeadWatcher();
@@ -2767,6 +2908,7 @@ var SwarmController = class {
2767
2908
  this.pi.setSessionName(`MANAGER-${ctx.sessionManager.getSessionId().slice(0, 8)}`);
2768
2909
  }
2769
2910
  this.defaultLead = true;
2911
+ this.autoNameEligible = true;
2770
2912
  await this.renderFooterStatus(ctx);
2771
2913
  return;
2772
2914
  }
@@ -3553,6 +3695,78 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3553
3695
  this.membership?.transport.setName(normalized);
3554
3696
  await this.renderFooterStatus(ctx);
3555
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
+ }
3556
3770
  /**
3557
3771
  * Best-effort, ordered relay of a direct user steer to the parent session so it
3558
3772
  * stays aligned. This returns immediately: sends are chained so ordering is
@@ -3665,11 +3879,11 @@ function recentSwarmState(ctx) {
3665
3879
  const messageIds = [];
3666
3880
  const consumedLaunchIds = /* @__PURE__ */ new Set();
3667
3881
  for (const entry of ctx.sessionManager.getBranch().slice(-1024)) {
3668
- 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) {
3669
3883
  continue;
3670
3884
  }
3671
3885
  const details = entry.details;
3672
- if (!isRecord4(details) || !isRecord4(details.message) || typeof details.message.id !== "string") {
3886
+ if (!isRecord5(details) || !isRecord5(details.message) || typeof details.message.id !== "string") {
3673
3887
  continue;
3674
3888
  }
3675
3889
  messageIds.push(details.message.id);
@@ -3713,7 +3927,7 @@ function truncateToBytes(value, maxBytes) {
3713
3927
  if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
3714
3928
  return Buffer.from(value, "utf8").subarray(0, maxBytes).toString("utf8");
3715
3929
  }
3716
- function isRecord4(value) {
3930
+ function isRecord5(value) {
3717
3931
  return typeof value === "object" && value !== null && !Array.isArray(value);
3718
3932
  }
3719
3933
 
@@ -3959,6 +4173,12 @@ function createPiSwarmExtension(dependencies = {}) {
3959
4173
  pi.on("session_shutdown", async (event, ctx) => {
3960
4174
  await controller.sessionShutdown(event, ctx);
3961
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
+ });
3962
4182
  pi.on("input", async (event, ctx) => {
3963
4183
  if (event.source !== "interactive") return;
3964
4184
  void controller.relaySteerInput(event.text, ctx);