pi-agent-swarm 0.2.0 → 0.4.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.
@@ -1,3 +1,5 @@
1
+ import { type ContextRecyclingLaunch, normalizeContextRecyclingPolicy } from "./context-recycling.js";
2
+
1
3
  type SwarmThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
2
4
 
3
5
  export const SWARM_LAUNCH_ENV_KEYS = [
@@ -11,6 +13,7 @@ export const SWARM_LAUNCH_ENV_KEYS = [
11
13
  "PI_SWARM_MODEL_PROVIDER",
12
14
  "PI_SWARM_MODEL_ID",
13
15
  "PI_SWARM_THINKING",
16
+ "PI_SWARM_CONTEXT_RECYCLING",
14
17
  ] as const;
15
18
 
16
19
  export interface SwarmLaunchEnvelope {
@@ -21,6 +24,7 @@ export interface SwarmLaunchEnvelope {
21
24
  childName?: string;
22
25
  childColor?: string;
23
26
  acceptsRequests: boolean;
27
+ contextRecycling?: ContextRecyclingLaunch;
24
28
  model?: { provider: string; id: string; thinkingLevel?: SwarmThinkingLevel };
25
29
  }
26
30
 
@@ -43,6 +47,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
43
47
  const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
44
48
  const childColor = optionalHexColor(values.PI_SWARM_COLOR);
45
49
  const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
50
+ const contextRecycling = parseContextRecycling(values.PI_SWARM_CONTEXT_RECYCLING);
46
51
  const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
47
52
  const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
48
53
  if ((provider === undefined) !== (id === undefined)) {
@@ -63,6 +68,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
63
68
  ...(childName ? { childName } : {}),
64
69
  ...(childColor ? { childColor } : {}),
65
70
  acceptsRequests,
71
+ ...(contextRecycling ? { contextRecycling } : {}),
66
72
  ...(provider && id
67
73
  ? {
68
74
  model: {
@@ -82,6 +88,7 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
82
88
  PI_SWARM_LAUNCH_ID: envelope.launchId,
83
89
  PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
84
90
  PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
91
+ ...(envelope.contextRecycling ? { PI_SWARM_CONTEXT_RECYCLING: JSON.stringify(envelope.contextRecycling) } : {}),
85
92
  ...(envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {}),
86
93
  ...(envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {}),
87
94
  ...(envelope.model
@@ -94,6 +101,50 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
94
101
  };
95
102
  }
96
103
 
104
+ function parseContextRecycling(value: string | undefined): ContextRecyclingLaunch | undefined {
105
+ if (value === undefined) return undefined;
106
+ const boundedValue = bounded(value, "context recycling policy", 4096);
107
+ let parsed: unknown;
108
+ try {
109
+ parsed = JSON.parse(boundedValue);
110
+ } catch {
111
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
112
+ }
113
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
114
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
115
+ }
116
+ const candidate = parsed as Record<string, unknown>;
117
+ const allowed = ["lineageId", "generation", "replacementCount", "policy", "handoffPath"];
118
+ if (Object.keys(candidate).some((key) => !allowed.includes(key))) {
119
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
120
+ }
121
+ const lineageId = safeId(candidate.lineageId as string | undefined, "lineage id");
122
+ if (!Number.isInteger(candidate.generation) || (candidate.generation as number) < 1) {
123
+ throw new Error("Pi Agent Swarm launch context recycling generation is invalid");
124
+ }
125
+ if (!Number.isInteger(candidate.replacementCount) || (candidate.replacementCount as number) < 0) {
126
+ throw new Error("Pi Agent Swarm launch context recycling replacement count is invalid");
127
+ }
128
+ const handoffPath = optionalBounded(candidate.handoffPath as string | undefined, "context handoff path", 4096);
129
+ if ((candidate.generation === 1) !== (handoffPath === undefined)) {
130
+ throw new Error("Pi Agent Swarm launch context handoff path is inconsistent");
131
+ }
132
+ const policy = normalizeContextRecyclingPolicy(candidate.policy);
133
+ if (
134
+ candidate.generation !== (candidate.replacementCount as number) + 1 ||
135
+ (candidate.replacementCount as number) > policy.maxReplacements
136
+ ) {
137
+ throw new Error("Pi Agent Swarm launch context recycling generation is inconsistent");
138
+ }
139
+ return {
140
+ lineageId,
141
+ generation: candidate.generation as number,
142
+ replacementCount: candidate.replacementCount as number,
143
+ policy,
144
+ ...(handoffPath ? { handoffPath } : {}),
145
+ };
146
+ }
147
+
97
148
  function parseBoolean(value: string | undefined): boolean {
98
149
  if (value === undefined || value === "0") return false;
99
150
  if (value === "1") return true;
package/src/menu.ts CHANGED
@@ -12,23 +12,25 @@ export interface SwarmMenuSource {
12
12
  rename(ctx: ExtensionCommandContext, name: string, signal?: AbortSignal): Promise<void>;
13
13
  setColor(ctx: ExtensionCommandContext, color: string, signal?: AbortSignal): Promise<void>;
14
14
  setPalette(ctx: ExtensionCommandContext, palette: SwarmColorPaletteName, signal?: AbortSignal): Promise<void>;
15
+ setRequests(ctx: ExtensionCommandContext, value: boolean): Promise<void>;
15
16
  }
16
17
 
17
18
  type Screen = "main";
18
- type Action = "spawn" | "rename" | "setColor" | "setTheme";
19
+ type Action = "spawn" | "rename" | "setColor" | "setTheme" | "setRequests";
19
20
 
20
21
  const DIRECTION_OPTIONS = ["Right", "Down", "Left", "Up"] as const;
21
22
  const PALETTE_OPTIONS = [
22
23
  { label: "muted (default, low-saturation GitHub colors)", value: "muted" },
23
24
  { label: "bright (vivid GitHub colors)", value: "bright" },
24
25
  ] as const satisfies readonly { label: string; value: SwarmColorPaletteName }[];
26
+ const REQUEST_OPTIONS = ["Block (default)", "Allow paid turns from trusted peers"] as const;
25
27
 
26
28
  export function createSwarmMenu(source: SwarmMenuSource) {
27
29
  const getState = ({ signal }: { signal?: AbortSignal } = {}) => source.snapshot(signal);
28
30
  const menu: MenuDefinition<SwarmMenuState, Screen, Action> = {
29
31
  start: "main",
30
32
  screens: {
31
- main: () => ({
33
+ main: ({ state }) => ({
32
34
  kind: "actions",
33
35
  title: "Pi Agent Swarm",
34
36
  lines: ["Spawn workers and manage this session's badge."],
@@ -53,6 +55,11 @@ export function createSwarmMenu(source: SwarmMenuSource) {
53
55
  label: "Set theme",
54
56
  action: "setTheme",
55
57
  },
58
+ {
59
+ id: "requests",
60
+ label: `Follow-up requests: ${state.acceptsRequests ? "allowed" : "blocked"}`,
61
+ action: "setRequests",
62
+ },
56
63
  ],
57
64
  hint: "close",
58
65
  }),
@@ -63,6 +70,8 @@ export function createSwarmMenu(source: SwarmMenuSource) {
63
70
  signal,
64
71
  });
65
72
  if (!directionChoice || signal.aborted) return { kind: "stay" };
73
+ const requestChoice = await ctx.ui.select("Follow-up agent requests", [...REQUEST_OPTIONS], { signal });
74
+ if (!requestChoice || signal.aborted) return { kind: "stay" };
66
75
  const task = await ctx.ui.input("Optional first task", "Submit an empty value for an idle child session", {
67
76
  signal,
68
77
  });
@@ -71,6 +80,7 @@ export function createSwarmMenu(source: SwarmMenuSource) {
71
80
  ctx,
72
81
  {
73
82
  direction: directionChoice.toLowerCase() as SpawnSessionInput["direction"],
83
+ allowRequests: requestChoice === "Allow paid turns from trusted peers",
74
84
  ...(task ? { task } : {}),
75
85
  },
76
86
  signal,
@@ -93,6 +103,10 @@ export function createSwarmMenu(source: SwarmMenuSource) {
93
103
  await source.setColor(ctx, choice, signal);
94
104
  return { kind: "stay" };
95
105
  },
106
+ setRequests: async ({ ctx, state }) => {
107
+ await source.setRequests(ctx, !state.acceptsRequests);
108
+ return { kind: "stay" };
109
+ },
96
110
  setTheme: async ({ ctx, signal }) => {
97
111
  const choice = await ctx.ui.select(
98
112
  "Roster theme (badge palette)",
@@ -7,7 +7,7 @@ import { SwarmController, type SwarmControllerDependencies } from "./swarm-contr
7
7
  import { safeTerminalLine } from "./text.js";
8
8
  import { registerSwarmTools } from "./tools.js";
9
9
 
10
- const USAGE = "Usage: /swarm, /swarm start, or /swarm <piagentswarm:v1:invite>";
10
+ const USAGE = "Usage: /swarm, /swarm start, /swarm requests <on|off>, or /swarm <piagentswarm:v1:invite>";
11
11
 
12
12
  type SwarmMenuModule = Pick<typeof import("./menu.js"), "showSwarmMenu">;
13
13
 
@@ -32,13 +32,31 @@ export function createPiSwarmExtension(dependencies: PiSwarmDependencies = {}):
32
32
  pi.on("session_shutdown", async (event, ctx) => {
33
33
  await controller.sessionShutdown(event, ctx);
34
34
  });
35
+ pi.on("turn_end", async (_event, ctx) => {
36
+ controller.noteTurnEnd(ctx);
37
+ });
38
+ pi.on("agent_settled", async (_event, ctx) => {
39
+ await controller.agentSettled(ctx);
40
+ });
41
+ pi.on("session_info_changed", async (event, ctx) => {
42
+ await controller.noteSessionInfoChanged(event.name, ctx);
43
+ });
35
44
  pi.on("input", async (event, ctx) => {
36
45
  if (event.source !== "interactive") return;
37
46
  void controller.relaySteerInput(event.text, ctx);
38
47
  });
39
48
 
40
49
  pi.registerCommand("swarm", {
41
- description: "Spawn a worker Pi session, or start/join a local group",
50
+ description: "Spawn a worker, manage a local group, or allow follow-up requests",
51
+ getArgumentCompletions(prefix) {
52
+ const normalized = prefix.trimStart();
53
+ const separator = normalized.search(/\s/u);
54
+ if (separator < 0) return argumentCompletions(["start", "requests"], normalized);
55
+ if (normalized.slice(0, separator) !== "requests") return null;
56
+ const value = normalized.slice(separator).trimStart();
57
+ if (/\s/u.test(value)) return null;
58
+ return argumentCompletions(["on", "off"], value);
59
+ },
42
60
  handler: async (rawArgs, ctx) => {
43
61
  const args = rawArgs.trim();
44
62
  if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
@@ -48,6 +66,10 @@ export function createPiSwarmExtension(dependencies: PiSwarmDependencies = {}):
48
66
  await startGroupDirectly(controller, ctx);
49
67
  return;
50
68
  }
69
+ if (args === "requests on" || args === "requests off") {
70
+ setRequestPolicyDirectly(controller, ctx, args === "requests on");
71
+ return;
72
+ }
51
73
  if (args) {
52
74
  await joinDirectInvite(controller, args, ctx);
53
75
  return;
@@ -122,6 +144,19 @@ async function startGroupDirectly(controller: SwarmController, ctx: ExtensionCom
122
144
  }
123
145
  }
124
146
 
147
+ function argumentCompletions(values: readonly string[], prefix: string) {
148
+ const matches = values.filter((value) => value.startsWith(prefix)).map((value) => ({ value, label: value }));
149
+ return matches.length > 0 ? matches : null;
150
+ }
151
+
152
+ function setRequestPolicyDirectly(controller: SwarmController, ctx: ExtensionCommandContext, value: boolean): void {
153
+ if (controller.sessionSignal.aborted) return;
154
+ controller.setAcceptsRequests(ctx, value);
155
+ if (controller.isCurrent(ctx)) {
156
+ ctx.ui.notify(`Follow-up agent requests ${value ? "enabled" : "blocked"} for this session.`, "info");
157
+ }
158
+ }
159
+
125
160
  function menuSource(controller: SwarmController): SwarmMenuSource {
126
161
  return {
127
162
  snapshot: (signal) => controller.snapshot(signal),
@@ -154,6 +189,9 @@ function menuSource(controller: SwarmController): SwarmMenuSource {
154
189
  commandContext.ui.notify(`Theme set to ${palette}.`, "info");
155
190
  }
156
191
  },
192
+ setRequests: async (commandContext, value) => {
193
+ setRequestPolicyDirectly(controller, commandContext, value);
194
+ },
157
195
  };
158
196
  }
159
197
 
package/src/protocol.ts CHANGED
@@ -18,6 +18,7 @@ const ENDPOINT_ID = /^[a-f0-9]{24}$/u;
18
18
  const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/u;
19
19
  const BASE64URL_MAC = /^[A-Za-z0-9_-]{43}$/u;
20
20
  const ACK_CODES = new Set<SwarmAckCode>([
21
+ "context_handoff",
21
22
  "delivery_failed",
22
23
  "kickoff_consumed",
23
24
  "launch_mismatch",
@@ -36,9 +37,9 @@ export type SwarmMessageMode = "notify" | "request" | "reply" | "kickoff";
36
37
 
37
38
  /**
38
39
  * Routes a message: `undefined` or `"steer"` enter the model context, while
39
- * `"lead"` and `"shutdown"` stay on the control plane and never reach the model.
40
+ * `"lead"`, `"shutdown"`, and `"handoff"` stay on the control plane and never reach the model.
40
41
  */
41
- export type SwarmMessageKind = "lead" | "steer" | "shutdown";
42
+ export type SwarmMessageKind = "lead" | "steer" | "shutdown" | "handoff";
42
43
 
43
44
  export interface SwarmMessage {
44
45
  id: string;
@@ -72,6 +73,7 @@ export type SwarmLocalPeerDescription = Omit<SwarmPeerDescription, "endpointId">
72
73
  export type SwarmAckStatus = "accepted" | "duplicate" | "rejected" | "busy";
73
74
 
74
75
  export type SwarmAckCode =
76
+ | "context_handoff"
75
77
  | "delivery_failed"
76
78
  | "kickoff_consumed"
77
79
  | "launch_mismatch"
@@ -277,9 +279,18 @@ export function validateMessage(value: unknown): SwarmMessage {
277
279
  }
278
280
  const replyTo = optionalId(value.replyTo, "reply message id");
279
281
  const launchId = optionalId(value.launchId, "launch id");
280
- if (value.kind !== undefined && value.kind !== "lead" && value.kind !== "steer" && value.kind !== "shutdown") {
282
+ if (
283
+ value.kind !== undefined &&
284
+ value.kind !== "lead" &&
285
+ value.kind !== "steer" &&
286
+ value.kind !== "shutdown" &&
287
+ value.kind !== "handoff"
288
+ ) {
281
289
  throw new Error("Pi Agent Swarm message kind is invalid");
282
290
  }
291
+ if (value.kind === "handoff" && mode !== "notify") {
292
+ throw new Error("Pi Agent Swarm handoff must be a notify control message");
293
+ }
283
294
  if (mode === "reply" && !replyTo) throw new Error("Pi Agent Swarm reply requires a reply message id");
284
295
  if (mode === "kickoff" && !launchId) throw new Error("Pi Agent Swarm kickoff requires a launch id");
285
296
  return {
@@ -1,3 +1,5 @@
1
+ import type { ContextRecyclingLaunch } from "./context-recycling.js";
2
+
1
3
  const RELOAD_HANDOFFS = Symbol.for("pi-agent-swarm/reload-handoffs");
2
4
 
3
5
  export interface SwarmReloadHandoff {
@@ -9,6 +11,7 @@ export interface SwarmReloadHandoff {
9
11
  name?: string;
10
12
  color?: string;
11
13
  parentSessionId?: string;
14
+ contextRecycling?: ContextRecyclingLaunch;
12
15
  expiresAt: number;
13
16
  }
14
17
 
package/src/settings.ts CHANGED
@@ -3,11 +3,13 @@ import { constants } from "node:fs";
3
3
  import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import { isAutoNameModel } from "./auto-name.js";
6
7
  import type { SwarmColorPaletteName } from "./color.js";
7
8
 
8
9
  export const SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
9
10
  export const MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
10
11
  export const DEFAULT_SWARM_SETTINGS: Readonly<SwarmSettings> = Object.freeze({
12
+ autoName: true,
11
13
  colorPalette: "muted",
12
14
  confirmSessionLaunch: true,
13
15
  externalCommand: "alacritty -e",
@@ -15,6 +17,8 @@ export const DEFAULT_SWARM_SETTINGS: Readonly<SwarmSettings> = Object.freeze({
15
17
  });
16
18
 
17
19
  export interface SwarmSettings {
20
+ autoName: boolean;
21
+ autoNameModel?: string;
18
22
  colorPalette: SwarmColorPaletteName;
19
23
  confirmSessionLaunch: boolean;
20
24
  externalCommand: string;
@@ -76,6 +80,8 @@ export interface SwarmSettingsRuntimeOptions {
76
80
  }
77
81
 
78
82
  const SETTING_FIELDS = [
83
+ "autoName",
84
+ "autoNameModel",
79
85
  "colorPalette",
80
86
  "confirmSessionLaunch",
81
87
  "externalCommand",
@@ -92,6 +98,18 @@ export function normalizeSwarmSettingsDocument(value: unknown): NormalizedSwarmS
92
98
  const settings: SwarmSettings = { ...DEFAULT_SWARM_SETTINGS };
93
99
  const sources = builtInSources();
94
100
 
101
+ if (Object.hasOwn(value, "autoName")) {
102
+ if (typeof value.autoName !== "boolean") return undefined;
103
+ settings.autoName = value.autoName;
104
+ sources.autoName = "user";
105
+ }
106
+ if (Object.hasOwn(value, "autoNameModel")) {
107
+ if (typeof value.autoNameModel !== "string" || !isAutoNameModel(value.autoNameModel.trim())) {
108
+ return undefined;
109
+ }
110
+ settings.autoNameModel = value.autoNameModel.trim();
111
+ sources.autoNameModel = "user";
112
+ }
95
113
  if (Object.hasOwn(value, "colorPalette")) {
96
114
  if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return undefined;
97
115
  settings.colorPalette = value.colorPalette;
@@ -166,6 +184,8 @@ export function createInMemorySwarmSettingsRuntime(): SwarmSettingsRuntime {
166
184
  settings: { ...state.settings, ...canonical },
167
185
  sources: {
168
186
  ...state.sources,
187
+ ...(canonical.autoName !== undefined ? { autoName: "user" as const } : {}),
188
+ ...(canonical.autoNameModel !== undefined ? { autoNameModel: "user" as const } : {}),
169
189
  ...(canonical.colorPalette !== undefined ? { colorPalette: "user" as const } : {}),
170
190
  ...(canonical.confirmSessionLaunch !== undefined ? { confirmSessionLaunch: "user" as const } : {}),
171
191
  ...(canonical.externalCommand ? { externalCommand: "user" as const } : {}),
@@ -341,6 +361,8 @@ function invalidLoad(path: string, reason: string): SwarmSettingsLoadResult {
341
361
 
342
362
  function builtInSources(): Record<SwarmSettingsField, SwarmSettingsSource> {
343
363
  return {
364
+ autoName: "built-in",
365
+ autoNameModel: "built-in",
344
366
  colorPalette: "built-in",
345
367
  confirmSessionLaunch: "built-in",
346
368
  externalCommand: "built-in",