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.
package/src/tools.ts CHANGED
@@ -2,13 +2,14 @@ import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
4
  import { swarmColorName } from "./color.js";
5
+ import type { WorkerHandoffContent, WorkerTaskStatus } from "./context-recycling.js";
5
6
  import type { SwarmMessage } from "./protocol.js";
6
7
  import type { SpawnSessionInput, SpawnSessionResult, SwarmSnapshot } from "./swarm-controller.js";
7
8
  import { safeTerminalLine } from "./text.js";
8
9
  import type { SwarmDeliveryAck } from "./transport.js";
9
10
 
10
11
  const DIRECTIONS = ["right", "down", "left", "up"] as const;
11
- const BUS_ACTIONS = ["list", "send", "reply", "shutdown"] as const;
12
+ const BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff"] as const;
12
13
  const SEND_MODES = ["notify", "request"] as const;
13
14
  const MAX_LISTED_PEERS = 64;
14
15
  const MAX_LIST_RESULT_BYTES = 40 * 1024;
@@ -23,6 +24,8 @@ export interface SwarmToolController {
23
24
  text: string;
24
25
  mode: "notify" | "request" | "reply";
25
26
  replyTo?: string;
27
+ taskStatus?: WorkerTaskStatus;
28
+ handoff?: WorkerHandoffContent;
26
29
  },
27
30
  signal?: AbortSignal,
28
31
  ): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }>;
@@ -31,11 +34,66 @@ export interface SwarmToolController {
31
34
  targetSessionId: string,
32
35
  signal?: AbortSignal,
33
36
  ): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }>;
37
+ publishHandoff(
38
+ ctx: ExtensionContext,
39
+ handoff: WorkerHandoffContent,
40
+ signal?: AbortSignal,
41
+ ): Promise<{ handoffPath: string }>;
34
42
  }
35
43
 
44
+ const handoffSchema = Type.Object(
45
+ {
46
+ originalObjective: Type.String({ maxLength: 8_192 }),
47
+ currentState: Type.String({ maxLength: 8_192 }),
48
+ completedWork: Type.String({ maxLength: 8_192 }),
49
+ remainingWork: Type.String({ maxLength: 8_192 }),
50
+ modifiedFiles: Type.String({ maxLength: 8_192 }),
51
+ verification: Type.String({ maxLength: 8_192 }),
52
+ decisions: Type.String({ maxLength: 8_192 }),
53
+ blocker: Type.String({ maxLength: 8_192 }),
54
+ nextAction: Type.String({ maxLength: 8_192 }),
55
+ artifacts: Type.Array(Type.String({ maxLength: 4_096 }), { maxItems: 32 }),
56
+ },
57
+ { additionalProperties: false },
58
+ );
59
+
36
60
  const spawnSchema = Type.Object(
37
61
  {
38
62
  direction: Type.Optional(StringEnum(DIRECTIONS, { description: "Terminal window direction" })),
63
+ allowRequests: Type.Optional(
64
+ Type.Boolean({
65
+ description:
66
+ "Allow trusted peers to request follow-up turns in the child after its initial task; defaults to false. This can incur model charges and concurrent workspace edits.",
67
+ }),
68
+ ),
69
+ contextRecycling: Type.Optional(
70
+ Type.Object(
71
+ {
72
+ taskProfile: Type.Union([Type.Literal("short"), Type.Literal("long"), Type.Literal("auto")], {
73
+ description: "Leader's assessment of the assignment duration",
74
+ }),
75
+ maxContextPercent: Type.Optional(
76
+ Type.Number({
77
+ description: "Soft handoff threshold; defaults to 50 and never aborts the current turn",
78
+ minimum: 1,
79
+ maximum: 100,
80
+ }),
81
+ ),
82
+ maxReplacements: Type.Optional(
83
+ Type.Integer({
84
+ description: "Maximum authorized automatic successors; defaults to 3, maximum 10",
85
+ minimum: 0,
86
+ maximum: 10,
87
+ }),
88
+ ),
89
+ },
90
+ {
91
+ additionalProperties: false,
92
+ description:
93
+ "Authorize bounded automatic worker replacement after a stable-boundary handoff. Omit to disable recycling.",
94
+ },
95
+ ),
96
+ ),
39
97
  task: Type.Optional(
40
98
  Type.String({
41
99
  description: "Optional first task sent after child readiness",
@@ -80,6 +138,12 @@ const busSchema = Type.Object(
80
138
  replyTo: Type.Optional(
81
139
  Type.String({ description: "Original message id for a reply", minLength: 1, maxLength: 128 }),
82
140
  ),
141
+ taskStatus: Type.Optional(
142
+ Type.Union([Type.Literal("working"), Type.Literal("completed")], {
143
+ description: "Worker task state for context recycling; completed prevents successor creation",
144
+ }),
145
+ ),
146
+ handoff: Type.Optional(handoffSchema),
83
147
  },
84
148
  { additionalProperties: false },
85
149
  );
@@ -94,6 +158,8 @@ export function registerSwarmTools(pi: ExtensionAPI, controller: SwarmToolContro
94
158
  promptGuidelines: [
95
159
  "Use session_spawn only when the user explicitly asks to open or start another Pi session.",
96
160
  "Do not claim the child is ready until session_spawn returns authenticated readiness metadata.",
161
+ "Use allowRequests only when the user wants this worker to accept follow-up tasks in the same session; it defaults to false.",
162
+ "Use contextRecycling only with explicit user authorization for bounded automatic worker replacement; the threshold is soft and never interrupts a healthy turn.",
97
163
  ],
98
164
  parameters: spawnSchema,
99
165
  executionMode: "sequential",
@@ -129,6 +195,7 @@ export function registerSwarmTools(pi: ExtensionAPI, controller: SwarmToolContro
129
195
  promptGuidelines: [
130
196
  "Use session_bus to communicate with sessions already connected through Pi Agent Swarm.",
131
197
  "Treat session_bus accepted acknowledgements as extension delivery only, not proof that a remote task succeeded.",
198
+ "Workers with contextRecycling must report taskStatus=completed when done; unfinished workers publish a structured handoff when asked.",
132
199
  ],
133
200
  parameters: busSchema,
134
201
  executionMode: "sequential",
@@ -138,6 +205,8 @@ export function registerSwarmTools(pi: ExtensionAPI, controller: SwarmToolContro
138
205
  assertAbsent(params.message, "message", "list");
139
206
  assertAbsent(params.mode, "mode", "list");
140
207
  assertAbsent(params.replyTo, "replyTo", "list");
208
+ assertAbsent(params.taskStatus, "taskStatus", "list");
209
+ assertAbsent(params.handoff, "handoff", "list");
141
210
  const snapshot = await controller.snapshot(signal);
142
211
  if (!snapshot.connected) {
143
212
  return {
@@ -152,22 +221,51 @@ export function registerSwarmTools(pi: ExtensionAPI, controller: SwarmToolContro
152
221
  assertAbsent(params.message, "message", "shutdown");
153
222
  assertAbsent(params.mode, "mode", "shutdown");
154
223
  assertAbsent(params.replyTo, "replyTo", "shutdown");
224
+ assertAbsent(params.taskStatus, "taskStatus", "shutdown");
225
+ assertAbsent(params.handoff, "handoff", "shutdown");
155
226
  const shutdownTarget = required(params.targetSessionId, "targetSessionId");
156
227
  const result = await controller.shutdownPeer(ctx, shutdownTarget, signal);
157
228
  return shutdownResult(result, shutdownTarget);
158
229
  }
159
230
 
231
+ if (params.action === "handoff") {
232
+ assertAbsent(params.targetSessionId, "targetSessionId", "handoff");
233
+ assertAbsent(params.message, "message", "handoff");
234
+ assertAbsent(params.mode, "mode", "handoff");
235
+ assertAbsent(params.replyTo, "replyTo", "handoff");
236
+ assertAbsent(params.taskStatus, "taskStatus", "handoff");
237
+ if (!params.handoff) throw new Error("session_bus handoff is required for this action");
238
+ const result = await controller.publishHandoff(ctx, params.handoff, signal);
239
+ return {
240
+ content: [{ type: "text", text: `Worker handoff is ready: ${safeTerminalLine(result.handoffPath)}` }],
241
+ details: result,
242
+ };
243
+ }
244
+
160
245
  const targetSessionId = required(params.targetSessionId, "targetSessionId");
161
246
  const message = required(params.message, "message");
162
247
  if (params.action === "send") {
163
248
  assertAbsent(params.replyTo, "replyTo", "send");
249
+ assertAbsent(params.taskStatus, "taskStatus", "send");
250
+ assertAbsent(params.handoff, "handoff", "send");
164
251
  const mode = params.mode ?? "notify";
165
252
  const result = await controller.send(ctx, { targetSessionId, text: message, mode }, signal);
166
253
  return deliveryResult(result, targetSessionId);
167
254
  }
168
255
  assertAbsent(params.mode, "mode", "reply");
169
256
  const replyTo = required(params.replyTo, "replyTo");
170
- const result = await controller.send(ctx, { targetSessionId, text: message, mode: "reply", replyTo }, signal);
257
+ const result = await controller.send(
258
+ ctx,
259
+ {
260
+ targetSessionId,
261
+ text: message,
262
+ mode: "reply",
263
+ replyTo,
264
+ ...(params.taskStatus ? { taskStatus: params.taskStatus } : {}),
265
+ ...(params.handoff ? { handoff: params.handoff } : {}),
266
+ },
267
+ signal,
268
+ );
171
269
  return deliveryResult(result, targetSessionId);
172
270
  },
173
271
  });
@@ -270,6 +368,6 @@ function required(value: string | undefined, field: string): string {
270
368
  return value;
271
369
  }
272
370
 
273
- function assertAbsent(value: string | undefined, field: string, action: string): void {
371
+ function assertAbsent(value: unknown, field: string, action: string): void {
274
372
  if (value !== undefined) throw new Error(`session_bus ${field} is not accepted for action ${action}`);
275
373
  }
package/src/transport.ts CHANGED
@@ -76,6 +76,13 @@ export interface SwarmTransportOptions {
76
76
  onMessage(message: SwarmMessage, signal: AbortSignal): Promise<void> | void;
77
77
  /** Resolve whether a shutdown control message from the given sender is authorized. */
78
78
  authorizeShutdown?: (message: SwarmMessage) => boolean;
79
+ /** Handoff publication is accepted only by the current coordinating leader. */
80
+ authorizeHandoff?: (message: SwarmMessage) => boolean;
81
+ /**
82
+ * Report the stable reason a request is refused while a lifecycle freeze is active,
83
+ * for example `context_handoff` while a worker waits for its successor.
84
+ */
85
+ rejectRequest?: (message: SwarmMessage) => SwarmAckPayload | undefined;
79
86
  seenMessageIds?: readonly string[];
80
87
  kickoffConsumed?: boolean;
81
88
  now?: () => number;
@@ -555,6 +562,14 @@ export class SwarmTransport {
555
562
  }
556
563
 
557
564
  private messagePolicyError(message: SwarmMessage, kickoffCapability?: string): SwarmAckPayload | undefined {
565
+ if (message.kind === "handoff" && !(this.options.authorizeHandoff?.(message) ?? false)) {
566
+ return {
567
+ kind: "ack",
568
+ status: "rejected",
569
+ code: "context_handoff",
570
+ error: "Target session is not the authorized handoff leader",
571
+ };
572
+ }
558
573
  if (message.kind === "shutdown" && !(this.options.authorizeShutdown?.(message) ?? false)) {
559
574
  return {
560
575
  kind: "ack",
@@ -564,6 +579,8 @@ export class SwarmTransport {
564
579
  };
565
580
  }
566
581
  if (message.mode === "request" && !this.peer.acceptsRequests) {
582
+ const lifecycleRejection = this.options.rejectRequest?.(message);
583
+ if (lifecycleRejection) return lifecycleRejection;
567
584
  return {
568
585
  kind: "ack",
569
586
  status: "rejected",
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/menu.ts"],
4
- "sourcesContent": ["import type { ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport type { MenuDefinition } from \"@narumitw/pi-tui-kit\";\nimport { SWARM_COLORS, type SwarmColorPaletteName } from \"./color.js\";\nimport type { SpawnSessionInput, SwarmSnapshot } from \"./swarm-controller.js\";\nimport { safeError } from \"./text.js\";\n\nexport interface SwarmMenuState extends SwarmSnapshot {}\n\nexport interface SwarmMenuSource {\n snapshot(signal?: AbortSignal): Promise<SwarmMenuState>;\n spawn(ctx: ExtensionCommandContext, input: SpawnSessionInput, signal?: AbortSignal): Promise<void>;\n rename(ctx: ExtensionCommandContext, name: string, signal?: AbortSignal): Promise<void>;\n setColor(ctx: ExtensionCommandContext, color: string, signal?: AbortSignal): Promise<void>;\n setPalette(ctx: ExtensionCommandContext, palette: SwarmColorPaletteName, signal?: AbortSignal): Promise<void>;\n}\n\ntype Screen = \"main\";\ntype Action = \"spawn\" | \"rename\" | \"setColor\" | \"setTheme\";\n\nconst DIRECTION_OPTIONS = [\"Right\", \"Down\", \"Left\", \"Up\"] as const;\nconst PALETTE_OPTIONS = [\n { label: \"muted (default, low-saturation GitHub colors)\", value: \"muted\" },\n { label: \"bright (vivid GitHub colors)\", value: \"bright\" },\n] as const satisfies readonly { label: string; value: SwarmColorPaletteName }[];\n\nexport function createSwarmMenu(source: SwarmMenuSource) {\n const getState = ({ signal }: { signal?: AbortSignal } = {}) => source.snapshot(signal);\n const menu: MenuDefinition<SwarmMenuState, Screen, Action> = {\n start: \"main\",\n screens: {\n main: () => ({\n kind: \"actions\",\n title: \"Pi Agent Swarm\",\n lines: [\"Spawn workers and manage this session's badge.\"],\n items: [\n {\n id: \"spawn\",\n label: \"Spawn\",\n action: \"spawn\",\n },\n {\n id: \"rename\",\n label: \"Rename\",\n action: \"rename\",\n },\n {\n id: \"color\",\n label: \"Set color\",\n action: \"setColor\",\n },\n {\n id: \"theme\",\n label: \"Set theme\",\n action: \"setTheme\",\n },\n ],\n hint: \"close\",\n }),\n },\n actions: {\n spawn: async ({ ctx, signal }) => {\n const directionChoice = await ctx.ui.select(\"Terminal window direction\", [...DIRECTION_OPTIONS], {\n signal,\n });\n if (!directionChoice || signal.aborted) return { kind: \"stay\" };\n const task = await ctx.ui.input(\"Optional first task\", \"Submit an empty value for an idle child session\", {\n signal,\n });\n if (task === undefined || signal.aborted) return { kind: \"stay\" };\n await source.spawn(\n ctx,\n {\n direction: directionChoice.toLowerCase() as SpawnSessionInput[\"direction\"],\n ...(task ? { task } : {}),\n },\n signal,\n );\n return { kind: \"close\" };\n },\n rename: async ({ ctx, signal, state }) => {\n const name = await ctx.ui.input(\"Rename session\", state.self?.name ?? \"Enter a new session name\", {\n signal,\n });\n if (name === undefined || !name.trim() || signal.aborted) return { kind: \"stay\" };\n await source.rename(ctx, name, signal);\n return { kind: \"stay\" };\n },\n setColor: async ({ ctx, signal }) => {\n const choice = await ctx.ui.select(\"Session color\", [...SWARM_COLORS.map((color) => color.name)], {\n signal,\n });\n if (!choice || signal.aborted) return { kind: \"stay\" };\n await source.setColor(ctx, choice, signal);\n return { kind: \"stay\" };\n },\n setTheme: async ({ ctx, signal }) => {\n const choice = await ctx.ui.select(\n \"Roster theme (badge palette)\",\n PALETTE_OPTIONS.map((option) => option.label),\n { signal },\n );\n if (!choice || signal.aborted) return { kind: \"stay\" };\n const palette = PALETTE_OPTIONS.find((option) => option.label === choice)?.value;\n if (!palette) return { kind: \"stay\" };\n await source.setPalette(ctx, palette, signal);\n return { kind: \"stay\" };\n },\n },\n };\n return { menu, getState };\n}\n\nexport async function showSwarmMenu(\n ctx: ExtensionCommandContext,\n source: SwarmMenuSource,\n ownership: { signal: AbortSignal; isCurrent(): boolean },\n): Promise<void> {\n const { runMenu } = await import(\"@narumitw/pi-tui-kit\");\n if (ownership.signal.aborted || !ownership.isCurrent()) return;\n const controller = createSwarmMenu(source);\n await runMenu(ctx, controller.menu, {\n getState: controller.getState,\n signal: ownership.signal,\n isCurrent: ownership.isCurrent,\n onError: (_ctx, error) => {\n if (ownership.isCurrent() && !ownership.signal.aborted) {\n ctx.ui.notify(`Pi Agent Swarm failed: ${safeError(error)}`, \"error\");\n }\n },\n });\n}\n"],
5
- "mappings": ";;;;;;;;AAmBA,IAAM,oBAAoB,CAAC,SAAS,QAAQ,QAAQ,IAAI;AACxD,IAAM,kBAAkB;AAAA,EACtB,EAAE,OAAO,iDAAiD,OAAO,QAAQ;AAAA,EACzE,EAAE,OAAO,gCAAgC,OAAO,SAAS;AAC3D;AAEO,SAAS,gBAAgB,QAAyB;AACvD,QAAM,WAAW,CAAC,EAAE,OAAO,IAA8B,CAAC,MAAM,OAAO,SAAS,MAAM;AACtF,QAAM,OAAuD;AAAA,IAC3D,OAAO;AAAA,IACP,SAAS;AAAA,MACP,MAAM,OAAO;AAAA,QACX,MAAM;AAAA,QACN,OAAO;AAAA,QACP,OAAO,CAAC,gDAAgD;AAAA,QACxD,OAAO;AAAA,UACL;AAAA,YACE,IAAI;AAAA,YACJ,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,UACA;AAAA,YACE,IAAI;AAAA,YACJ,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,UACA;AAAA,YACE,IAAI;AAAA,YACJ,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,UACA;AAAA,YACE,IAAI;AAAA,YACJ,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,QACA,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP,OAAO,OAAO,EAAE,KAAK,OAAO,MAAM;AAChC,cAAM,kBAAkB,MAAM,IAAI,GAAG,OAAO,6BAA6B,CAAC,GAAG,iBAAiB,GAAG;AAAA,UAC/F;AAAA,QACF,CAAC;AACD,YAAI,CAAC,mBAAmB,OAAO,QAAS,QAAO,EAAE,MAAM,OAAO;AAC9D,cAAM,O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