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,12 +1,23 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
- import { join, resolve } from "node:path";
2
+ import { readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import type { Api, Model } from "@earendil-works/pi-ai";
4
5
  import type {
5
6
  ExtensionAPI,
6
7
  ExtensionContext,
7
8
  SessionShutdownEvent,
8
9
  SessionStartEvent,
9
10
  } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ AUTO_NAME_TIMEOUT_MS,
13
+ AutoNamer,
14
+ buildAutoNamePrompt,
15
+ collectAutoNameMessages,
16
+ completeSessionTitle as defaultCompleteSessionTitle,
17
+ isDefaultManagerName,
18
+ resolveAutoNameModel,
19
+ toAutoName,
20
+ } from "./auto-name.js";
10
21
  import {
11
22
  normalizeSwarmColor,
12
23
  pickSwarmColor,
@@ -15,6 +26,22 @@ import {
15
26
  swarmColorName,
16
27
  swarmColorPalette,
17
28
  } from "./color.js";
29
+ import {
30
+ type ContextRecyclingLaunch,
31
+ type ContextRecyclingPolicyInput,
32
+ contextHandoffDecision,
33
+ initializeWorkerLineage,
34
+ normalizeContextRecyclingPolicy,
35
+ publishWorkerHandoff,
36
+ readWorkerLineage,
37
+ updateWorkerLineage,
38
+ verifyWorkerHandoffReadable,
39
+ type WorkerHandoffContent,
40
+ type WorkerLineage,
41
+ type WorkerLineageState,
42
+ type WorkerTaskStatus,
43
+ workerLineagePaths,
44
+ } from "./context-recycling.js";
18
45
  import { parseExternalCommand } from "./external.js";
19
46
  import { buildRosterBadge, DEFAULT_TERMINAL_COLUMNS } from "./footer.js";
20
47
  import { consumeLaunchEnvelope, launchEnvelopeEnvironment, type SwarmLaunchEnvelope } from "./launch-envelope.js";
@@ -104,6 +131,13 @@ export interface SwarmControllerDependencies {
104
131
  /** Visible terminal columns, or undefined when not attached to a TTY. */
105
132
  terminalColumns?(): number | undefined;
106
133
  runtimeBaseDirectory?: string;
134
+ /** One-shot title completion for session auto-naming; tests substitute a stub. */
135
+ completeSessionTitle?(
136
+ ctx: ExtensionContext,
137
+ model: Model<Api>,
138
+ prompt: string,
139
+ signal?: AbortSignal,
140
+ ): Promise<string>;
107
141
  }
108
142
 
109
143
  export interface SwarmSnapshot {
@@ -119,6 +153,10 @@ export interface SwarmSnapshot {
119
153
 
120
154
  export interface SpawnSessionInput {
121
155
  direction?: TerminalSplitDirection;
156
+ allowRequests?: boolean;
157
+ contextRecycling?: ContextRecyclingPolicyInput;
158
+ /** Internal continuation identity; public tools use contextRecycling instead. */
159
+ recyclingLaunch?: ContextRecyclingLaunch;
122
160
  task?: string;
123
161
  name?: string;
124
162
  color?: string;
@@ -134,6 +172,18 @@ export interface SpawnSessionResult {
134
172
  terminalId: string;
135
173
  terminalVersion: string;
136
174
  kickoffAccepted: boolean;
175
+ lineageId?: string;
176
+ }
177
+
178
+ interface ActiveWorkerRecycling {
179
+ launch: ContextRecyclingLaunch;
180
+ projectRoot: string;
181
+ leaderSessionId: string;
182
+ specification: WorkerLineage["launch"];
183
+ state: WorkerLineageState;
184
+ taskStatus?: WorkerTaskStatus;
185
+ handoff?: WorkerHandoffContent;
186
+ handoffAttempts: number;
137
187
  }
138
188
 
139
189
  interface Membership {
@@ -178,11 +228,21 @@ export class SwarmController {
178
228
  private leadSessionId: string | undefined;
179
229
  /** A human-started session is the default lead of its own (not yet started) group. */
180
230
  private defaultLead = false;
231
+ private readonly autoNamer = new AutoNamer();
232
+ /** Auto-naming applies only to human-started sessions, never to spawned children. */
233
+ private autoNameEligible = false;
234
+ /** Set while the auto-namer applies its own name so the change is not read as manual. */
235
+ private applyingAutoName: string | undefined;
236
+
237
+ private autoNameInFlight = false;
181
238
  private leadWatcher: ReturnType<typeof setInterval> | undefined;
182
239
  private readonly resizeListener = () => this.onTerminalResize();
183
240
  private resizeWatching = false;
184
241
  private readonly pendingKickoffIds = new Set<string>();
185
242
  private relayChain: Promise<void> = Promise.resolve();
243
+ private recycling: ActiveWorkerRecycling | undefined;
244
+ private recyclingChain: Promise<void> = Promise.resolve();
245
+ private readonly successorLaunches = new Map<string, Promise<void>>();
186
246
 
187
247
  constructor(
188
248
  private readonly pi: ExtensionAPI,
@@ -202,8 +262,15 @@ export class SwarmController {
202
262
  this.parentSessionId = undefined;
203
263
  this.leadSessionId = undefined;
204
264
  this.defaultLead = false;
265
+ this.autoNamer.reset();
266
+ this.autoNameEligible = false;
267
+ this.applyingAutoName = undefined;
268
+ this.autoNameInFlight = false;
205
269
  this.pendingKickoffIds.clear();
206
270
  this.relayChain = Promise.resolve();
271
+ this.recycling = undefined;
272
+ this.recyclingChain = Promise.resolve();
273
+ this.successorLaunches.clear();
207
274
  this.startLeadWatcher();
208
275
  this.startResizeWatcher();
209
276
  const owner = ctx.sessionManager;
@@ -233,6 +300,7 @@ export class SwarmController {
233
300
  this.pi.setSessionName(`MANAGER-${ctx.sessionManager.getSessionId().slice(0, 8)}`);
234
301
  }
235
302
  this.defaultLead = true;
303
+ this.autoNameEligible = true;
236
304
  await this.renderFooterStatus(ctx);
237
305
  return;
238
306
  }
@@ -268,6 +336,10 @@ export class SwarmController {
268
336
  handoff?.kickoffConsumed ?? false,
269
337
  ),
270
338
  );
339
+ const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
340
+ if (recyclingLaunch && this.parentSessionId) {
341
+ await this.initializeContextRecycling(ctx, recyclingLaunch, this.parentSessionId);
342
+ }
271
343
  } catch (error) {
272
344
  if (this.isCurrent(owner, ownerGeneration)) {
273
345
  this.notify(ctx, `Pi Agent Swarm could not join the launch group: ${safeError(error)}`, "error");
@@ -308,6 +380,7 @@ export class SwarmController {
308
380
  ...(peerName ? { name: peerName } : {}),
309
381
  ...(peerColor ? { color: peerColor } : {}),
310
382
  ...(this.parentSessionId ? { parentSessionId: this.parentSessionId } : {}),
383
+ ...(this.recycling ? { contextRecycling: this.recycling.launch } : {}),
311
384
  expiresAt: this.deps.now() + RELOAD_HANDOFF_TTL_MS,
312
385
  });
313
386
  }
@@ -348,6 +421,10 @@ export class SwarmController {
348
421
  // Best-effort: a manager can still run a group without an explicit lead record.
349
422
  }
350
423
  }
424
+ void this.track(this.recoverProjectHandoffs(ctx)).catch((error) => {
425
+ if (this.isCurrent(ctx))
426
+ this.notify(ctx, `Pi Agent Swarm handoff recovery failed: ${safeError(error)}`, "warning");
427
+ });
351
428
  return this.snapshot(signal);
352
429
  });
353
430
  }
@@ -388,9 +465,249 @@ export class SwarmController {
388
465
  setAcceptsRequests(ctx: ExtensionContext, value: boolean): void {
389
466
  this.assertCurrentContext(ctx);
390
467
  if (!this.membership) throw new Error("Pi Agent Swarm is not connected");
468
+ if (this.recycling?.state === "retired") {
469
+ throw new Error("Pi Agent Swarm retired workers cannot accept new requests");
470
+ }
391
471
  this.membership.rollbackLaunch = undefined;
392
472
  this.membership.acceptsRequests = value;
393
473
  this.membership.transport.setAcceptsRequests(value);
474
+ if (value && this.recycling && ["handoff_pending", "handoff_ready", "failed"].includes(this.recycling.state)) {
475
+ const recycling = this.recycling;
476
+ const previousState = recycling.state;
477
+ recycling.state = "working";
478
+ recycling.handoffAttempts = 0;
479
+ void updateWorkerLineage(
480
+ recycling.projectRoot,
481
+ recycling.launch.lineageId,
482
+ { state: "working" },
483
+ { generation: recycling.launch.generation, state: previousState },
484
+ ).catch((error) => {
485
+ if (this.recycling === recycling)
486
+ this.notify(ctx, `Pi Agent Swarm could not resume its lineage: ${safeError(error)}`, "error");
487
+ });
488
+ }
489
+ }
490
+
491
+ private async initializeContextRecycling(
492
+ ctx: ExtensionContext,
493
+ launch: ContextRecyclingLaunch,
494
+ leaderSessionId: string,
495
+ ): Promise<void> {
496
+ const model = ctx.model;
497
+ const specification: WorkerLineage["launch"] = {
498
+ cwd: ctx.cwd,
499
+ ...(this.pi.getSessionName() ? { name: this.pi.getSessionName() } : {}),
500
+ ...(this.color ? { color: this.color } : {}),
501
+ ...(model ? { model: `${model.provider}/${model.id}` } : {}),
502
+ allowRequests: this.membership?.acceptsRequests ?? false,
503
+ };
504
+ await verifyWorkerHandoffReadable(ctx.cwd, launch);
505
+ const lineage = await initializeWorkerLineage({
506
+ projectRoot: ctx.cwd,
507
+ launch,
508
+ leaderSessionId,
509
+ workerSessionId: ctx.sessionManager.getSessionId(),
510
+ specification,
511
+ });
512
+ if (!this.isCurrent(ctx)) return;
513
+ const staleGeneration = lineage.currentGeneration !== launch.generation;
514
+ this.recycling = {
515
+ launch,
516
+ projectRoot: ctx.cwd,
517
+ leaderSessionId,
518
+ specification,
519
+ state: staleGeneration ? "retired" : lineage.state,
520
+ handoffAttempts: 0,
521
+ };
522
+ if (staleGeneration || ["handoff_pending", "handoff_ready", "replacing", "failed"].includes(lineage.state)) {
523
+ this.freezeForHandoff();
524
+ }
525
+ }
526
+
527
+ async agentSettled(ctx: ExtensionContext): Promise<void> {
528
+ if (!this.isCurrent(ctx) || !this.recycling) return;
529
+ const run = this.recyclingChain.then(() => this.agentSettledOwned(ctx));
530
+ this.recyclingChain = run.catch(() => undefined);
531
+ await run.catch((error) => {
532
+ if (this.isCurrent(ctx))
533
+ this.notify(ctx, `Pi Agent Swarm context recycling failed: ${safeError(error)}`, "error");
534
+ });
535
+ }
536
+
537
+ private async agentSettledOwned(ctx: ExtensionContext): Promise<void> {
538
+ const recycling = this.recycling;
539
+ if (!recycling || !this.isCurrent(ctx)) return;
540
+ if (recycling.state === "completed" || recycling.state === "retired" || recycling.state === "replacing") return;
541
+ const usage = ctx.getContextUsage();
542
+ if (usage) {
543
+ await updateWorkerLineage(
544
+ recycling.projectRoot,
545
+ recycling.launch.lineageId,
546
+ { contextUsage: { ...usage, updatedAt: new Date().toISOString() } },
547
+ { generation: recycling.launch.generation, state: recycling.state },
548
+ );
549
+ if (this.recycling !== recycling || !this.isCurrent(ctx)) return;
550
+ }
551
+ if (recycling.state === "handoff_ready" || recycling.state === "failed") return;
552
+ if (recycling.state === "handoff_pending") {
553
+ if (recycling.handoff) {
554
+ await this.publishHandoff(ctx, recycling.handoff);
555
+ } else {
556
+ await this.requestHandoffTurn(ctx, recycling);
557
+ }
558
+ return;
559
+ }
560
+ const decision = contextHandoffDecision(
561
+ usage?.percent,
562
+ recycling.taskStatus,
563
+ recycling.launch.policy.maxContextPercent,
564
+ );
565
+ if (decision === "continue") return;
566
+ if (decision === "complete") {
567
+ recycling.state = "completed";
568
+ await updateWorkerLineage(
569
+ recycling.projectRoot,
570
+ recycling.launch.lineageId,
571
+ { state: "completed" },
572
+ { generation: recycling.launch.generation, state: "working" },
573
+ );
574
+ return;
575
+ }
576
+ if (recycling.launch.replacementCount >= recycling.launch.policy.maxReplacements) {
577
+ recycling.state = "failed";
578
+ this.freezeForHandoff();
579
+ await updateWorkerLineage(
580
+ recycling.projectRoot,
581
+ recycling.launch.lineageId,
582
+ { state: "failed" },
583
+ { generation: recycling.launch.generation, state: "working" },
584
+ );
585
+ const text = `Context recycling paused for lineage ${recycling.launch.lineageId}: replacement budget ${recycling.launch.policy.maxReplacements} is exhausted.`;
586
+ this.notify(ctx, text, "warning");
587
+ await this.send(ctx, { targetSessionId: recycling.leaderSessionId, text, mode: "notify" });
588
+ return;
589
+ }
590
+ recycling.state = "handoff_pending";
591
+ recycling.handoffAttempts = 0;
592
+ this.freezeForHandoff();
593
+ await updateWorkerLineage(
594
+ recycling.projectRoot,
595
+ recycling.launch.lineageId,
596
+ { state: "handoff_pending" },
597
+ { generation: recycling.launch.generation, state: "working" },
598
+ );
599
+ if (recycling.handoff) await this.publishHandoff(ctx, recycling.handoff);
600
+ else await this.requestHandoffTurn(ctx, recycling);
601
+ }
602
+
603
+ private async requestHandoffTurn(ctx: ExtensionContext, recycling: ActiveWorkerRecycling): Promise<void> {
604
+ if (!this.isCurrent(ctx) || this.recycling !== recycling) return;
605
+ if (recycling.handoffAttempts >= 2) {
606
+ recycling.state = "failed";
607
+ this.notify(ctx, "Pi Agent Swarm could not obtain a structured handoff; the worker remains frozen.", "error");
608
+ await updateWorkerLineage(
609
+ recycling.projectRoot,
610
+ recycling.launch.lineageId,
611
+ { state: "failed" },
612
+ { generation: recycling.launch.generation, state: "handoff_pending" },
613
+ ).catch(() => undefined);
614
+ await this.send(ctx, {
615
+ targetSessionId: recycling.leaderSessionId,
616
+ text: `Context recycling stopped for lineage ${recycling.launch.lineageId}: no structured handoff after ${recycling.handoffAttempts} attempts.`,
617
+ mode: "notify",
618
+ }).catch(() => undefined);
619
+ return;
620
+ }
621
+ recycling.handoffAttempts += 1;
622
+ const paths = workerLineagePaths(recycling.projectRoot, recycling.launch.lineageId, recycling.launch.generation);
623
+ const content = [
624
+ "Pi Agent Swarm context handoff is required. Do not continue ordinary task work in this turn.",
625
+ "Call session_bus action=handoff once with a complete handoff object containing all required fields.",
626
+ `Write the handoff for: ${paths.handoffPath}`,
627
+ `Put large supporting logs under: ${paths.artifactsDirectory}`,
628
+ "Do not include invites, capabilities, credentials, environment dumps, or a raw transcript.",
629
+ "The exact nextAction must allow a fresh worker to continue without repeating completed work.",
630
+ ].join("\n");
631
+ this.pi.sendMessage(
632
+ { customType: SWARM_MESSAGE_TYPE, content, display: false, details: {} },
633
+ { deliverAs: "followUp", triggerTurn: true },
634
+ );
635
+ }
636
+
637
+ async publishHandoff(
638
+ ctx: ExtensionContext,
639
+ handoff: WorkerHandoffContent,
640
+ signal?: AbortSignal,
641
+ ): Promise<{ handoffPath: string }> {
642
+ this.assertCurrentContext(ctx);
643
+ const recycling = this.recycling;
644
+ if (recycling?.state !== "handoff_pending") {
645
+ throw new Error("Pi Agent Swarm is not waiting for a context handoff");
646
+ }
647
+ const membership = this.membership;
648
+ if (!membership) throw new Error("Pi Agent Swarm is not connected");
649
+ const paths = await publishWorkerHandoff({
650
+ projectRoot: recycling.projectRoot,
651
+ lineageId: recycling.launch.lineageId,
652
+ generation: recycling.launch.generation,
653
+ leaderSessionId: recycling.leaderSessionId,
654
+ policy: recycling.launch.policy,
655
+ launch: recycling.specification,
656
+ content: handoff,
657
+ nextAction: handoff.nextAction,
658
+ });
659
+ if (this.recycling !== recycling || !this.isCurrent(ctx)) throw staleError();
660
+ const self = membership.transport.peerDescription;
661
+ const issuedAt = this.deps.now();
662
+ try {
663
+ const acknowledgement = await membership.transport.send(
664
+ recycling.leaderSessionId,
665
+ {
666
+ id: this.deps.randomId("msg"),
667
+ fromSessionId: self.sessionId,
668
+ ...(self.name ? { fromName: self.name } : {}),
669
+ fromCwd: self.cwd,
670
+ toSessionId: recycling.leaderSessionId,
671
+ mode: "notify",
672
+ kind: "handoff",
673
+ text: paths.handoffPath,
674
+ issuedAt,
675
+ expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
676
+ },
677
+ combineSignals(signal, this.controller.signal),
678
+ );
679
+ if (!acknowledgement.accepted) {
680
+ throw new Error(`Pi Agent Swarm leader rejected the handoff: ${acknowledgement.error ?? "unknown reason"}`);
681
+ }
682
+ } catch (error) {
683
+ if (this.recycling === recycling && recycling.state === "handoff_pending" && this.isCurrent(ctx)) {
684
+ const latest = await readWorkerLineage(recycling.projectRoot, recycling.launch.lineageId);
685
+ if (latest.currentGeneration > recycling.launch.generation || latest.state === "replacing") {
686
+ recycling.state = "handoff_ready";
687
+ recycling.handoff = handoff;
688
+ return { handoffPath: paths.handoffPath };
689
+ }
690
+ if (latest.currentGeneration === recycling.launch.generation && latest.state === "handoff_ready") {
691
+ await updateWorkerLineage(
692
+ recycling.projectRoot,
693
+ recycling.launch.lineageId,
694
+ { state: "handoff_pending" },
695
+ { generation: recycling.launch.generation, state: "handoff_ready" },
696
+ );
697
+ }
698
+ }
699
+ throw error;
700
+ }
701
+ if (this.recycling !== recycling || this.membership !== membership || !this.isCurrent(ctx)) throw staleError();
702
+ recycling.state = "handoff_ready";
703
+ recycling.handoff = handoff;
704
+ return { handoffPath: paths.handoffPath };
705
+ }
706
+
707
+ private freezeForHandoff(): void {
708
+ if (!this.membership) return;
709
+ this.membership.acceptsRequests = false;
710
+ this.membership.transport.setAcceptsRequests(false);
394
711
  }
395
712
 
396
713
  async snapshot(signal?: AbortSignal): Promise<SwarmSnapshot> {
@@ -436,6 +753,8 @@ export class SwarmController {
436
753
  text: string;
437
754
  mode: Exclude<SwarmMessageMode, "kickoff">;
438
755
  replyTo?: string;
756
+ taskStatus?: WorkerTaskStatus;
757
+ handoff?: WorkerHandoffContent;
439
758
  },
440
759
  signal?: AbortSignal,
441
760
  ): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }> {
@@ -443,7 +762,12 @@ export class SwarmController {
443
762
  const membership = this.membership;
444
763
  if (!membership) throw new Error("Pi Agent Swarm is not connected");
445
764
  membership.rollbackLaunch = undefined;
446
- if (Buffer.byteLength(options.text) > MAX_MESSAGE_BYTES) {
765
+ const usage = this.recycling && options.mode === "reply" ? ctx.getContextUsage() : undefined;
766
+ const metricPrefix =
767
+ this.recycling && options.mode === "reply"
768
+ ? `[Swarm lineage ${this.recycling.launch.lineageId} generation ${this.recycling.launch.generation}; model ${ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "unknown"}; context ${usage?.percent ?? "unknown"}%${usage ? ` (${usage.tokens ?? "unknown"}/${usage.contextWindow} tokens)` : ""}; taskProfile ${this.recycling.launch.policy.taskProfile}; state ${this.recycling.state}; updatedAt ${new Date().toISOString()}]\n`
769
+ : "";
770
+ if (Buffer.byteLength(`${metricPrefix}${options.text}`) > MAX_MESSAGE_BYTES) {
447
771
  throw new Error("Pi Agent Swarm message is too large");
448
772
  }
449
773
  const self = membership.transport.peerDescription;
@@ -455,7 +779,7 @@ export class SwarmController {
455
779
  fromCwd: self.cwd,
456
780
  toSessionId: options.targetSessionId,
457
781
  mode: options.mode,
458
- text: options.text,
782
+ text: `${metricPrefix}${options.text}`,
459
783
  issuedAt,
460
784
  expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
461
785
  ...(options.replyTo ? { replyTo: options.replyTo } : {}),
@@ -467,6 +791,10 @@ export class SwarmController {
467
791
  if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
468
792
  throw staleError();
469
793
  }
794
+ if (acknowledgement.accepted && this.recycling && options.mode === "reply") {
795
+ this.recycling.taskStatus = options.taskStatus ?? "working";
796
+ this.recycling.handoff = options.handoff;
797
+ }
470
798
  return { message, acknowledgement };
471
799
  }
472
800
 
@@ -523,6 +851,16 @@ export class SwarmController {
523
851
  await this.settings.flush();
524
852
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
525
853
  const launchSettings = this.settings.get().settings;
854
+ const recyclingLaunch =
855
+ input.recyclingLaunch ??
856
+ (input.contextRecycling
857
+ ? {
858
+ lineageId: this.deps.randomId("lineage"),
859
+ generation: 1,
860
+ replacementCount: 0,
861
+ policy: normalizeContextRecyclingPolicy(input.contextRecycling),
862
+ }
863
+ : undefined);
526
864
  const direction = input.direction ?? "right";
527
865
  const windowLabel = "window";
528
866
  const launchLayoutLine = "External terminal window (the window manager places it)";
@@ -566,7 +904,7 @@ export class SwarmController {
566
904
  );
567
905
  const terminalVersion = await terminalAdapter.assertAvailable(operationSignal);
568
906
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
569
- if (launchSettings.confirmSessionLaunch) {
907
+ if (launchSettings.confirmSessionLaunch && !input.recyclingLaunch) {
570
908
  const confirmed = await ctx.ui.confirm(
571
909
  "Create a new Pi session?",
572
910
  [
@@ -575,6 +913,8 @@ export class SwarmController {
575
913
  `Color: ${safeTerminalLine(color)}`,
576
914
  `Cwd: ${safeTerminalLine(cwd)}`,
577
915
  `Model: ${safeTerminalLine(childModel ? `${childModel.provider}/${childModel.id}` : "Pi default")}`,
916
+ `Follow-up requests: ${input.allowRequests ? "allowed for trusted peers" : "blocked"}.`,
917
+ `Context recycling: ${recyclingLaunch ? `${recyclingLaunch.policy.maxContextPercent}% soft handoff, at most ${recyclingLaunch.policy.maxReplacements} replacements` : "disabled"}.`,
578
918
  "The child may spend model tokens and edit the same workspace concurrently.",
579
919
  ].join("\n"),
580
920
  { signal: operationSignal },
@@ -602,7 +942,8 @@ export class SwarmController {
602
942
  kickoffCapability,
603
943
  childName: name,
604
944
  childColor: color,
605
- acceptsRequests: false,
945
+ acceptsRequests: input.allowRequests === true,
946
+ ...(recyclingLaunch ? { contextRecycling: recyclingLaunch } : {}),
606
947
  ...(childModel ? { model: childModel } : {}),
607
948
  };
608
949
  const launchEnvironment = launchEnvelopeEnvironment(envelope);
@@ -669,6 +1010,7 @@ export class SwarmController {
669
1010
  terminalId,
670
1011
  terminalVersion: actualTerminalVersion,
671
1012
  kickoffAccepted,
1013
+ ...(recyclingLaunch ? { lineageId: recyclingLaunch.lineageId } : {}),
672
1014
  };
673
1015
  } catch (error) {
674
1016
  const partial = splitCreated || (isTerminalLaunchError(error) && error.splitCreated);
@@ -769,6 +1111,19 @@ export class SwarmController {
769
1111
  authorizeShutdown: (message) =>
770
1112
  message.fromSessionId === this.parentSessionId ||
771
1113
  (this.leadSessionId !== undefined && message.fromSessionId === this.leadSessionId),
1114
+ authorizeHandoff: () =>
1115
+ this.isCurrent(owner, ownerGeneration) && this.leadSessionId === ctx.sessionManager.getSessionId(),
1116
+ rejectRequest: () => {
1117
+ const state = this.recycling?.state;
1118
+ if (!state || !["handoff_pending", "handoff_ready", "replacing", "failed", "retired"].includes(state))
1119
+ return undefined;
1120
+ return {
1121
+ kind: "ack",
1122
+ status: "rejected",
1123
+ code: "context_handoff",
1124
+ error: `Target worker is ${state}; only the context handoff protocol may continue`,
1125
+ };
1126
+ },
772
1127
  onMessage: async (message, deliverySignal) => {
773
1128
  if (deliverySignal?.aborted || !this.isCurrent(owner, ownerGeneration)) return;
774
1129
  const activeContext = this.activeContext;
@@ -782,6 +1137,19 @@ export class SwarmController {
782
1137
  // without a provider request and the settle boundary performs the
783
1138
  // shutdown. A busy session settles on its own and needs no trigger.
784
1139
  const idle = activeContext?.isIdle() ?? false;
1140
+ if (this.recycling) {
1141
+ const recycling = this.recycling;
1142
+ recycling.state = "retired";
1143
+ const lineage = await readWorkerLineage(recycling.projectRoot, recycling.launch.lineageId);
1144
+ await updateWorkerLineage(
1145
+ recycling.projectRoot,
1146
+ recycling.launch.lineageId,
1147
+ lineage.currentGeneration === recycling.launch.generation
1148
+ ? { state: "retired" }
1149
+ : { retiredThroughGeneration: recycling.launch.generation },
1150
+ { generation: lineage.currentGeneration },
1151
+ );
1152
+ }
785
1153
  activeContext?.shutdown();
786
1154
  if (idle && activeContext) {
787
1155
  const details: SwarmMessageDetails = { message };
@@ -796,7 +1164,10 @@ export class SwarmController {
796
1164
  if (message.kind === "lead") {
797
1165
  // Lead broadcasts only update the role badge; they never enter the model
798
1166
  // context. refreshLead below reconciles the same information.
1167
+ } else if (message.kind === "handoff") {
1168
+ if (activeContext) await this.acceptWorkerHandoff(activeContext, message);
799
1169
  } else {
1170
+ await this.noteIncomingWork(message);
800
1171
  this.receiveMessage(message);
801
1172
  }
802
1173
  void this.refreshLead().then((changed) => {
@@ -841,6 +1212,207 @@ export class SwarmController {
841
1212
  }
842
1213
  }
843
1214
 
1215
+ private acceptWorkerHandoff(ctx: ExtensionContext, message: SwarmMessage): void {
1216
+ const key = `${message.fromSessionId}:${message.text}`;
1217
+ if (this.successorLaunches.has(key)) return;
1218
+ const owner = ctx.sessionManager;
1219
+ const ownerGeneration = this.generation;
1220
+ const task = this.spawnSuccessor(ctx, message).catch((error) => {
1221
+ this.successorLaunches.delete(key);
1222
+ if (this.isCurrent(owner, ownerGeneration)) {
1223
+ this.notify(
1224
+ ctx,
1225
+ `Pi Agent Swarm could not replace worker ${safeTerminalLine(message.fromName ?? message.fromSessionId)}: ${safeError(error)}`,
1226
+ "error",
1227
+ );
1228
+ }
1229
+ });
1230
+ this.successorLaunches.set(key, task);
1231
+ }
1232
+
1233
+ private async recoverProjectHandoffs(ctx: ExtensionContext): Promise<void> {
1234
+ const directory = resolve(ctx.cwd, ".pi", "agent-swarm", "lineages");
1235
+ const entries = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
1236
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
1237
+ throw error;
1238
+ });
1239
+ for (const entry of entries) {
1240
+ if (!entry.isDirectory()) continue;
1241
+ let lineage = await readWorkerLineage(ctx.cwd, entry.name).catch(() => undefined);
1242
+ if (!lineage || lineage.leaderSessionId !== ctx.sessionManager.getSessionId()) continue;
1243
+ if (!lineage.workerSessionId || !lineage.currentHandoffPath) continue;
1244
+ const workerSessionId = lineage.workerSessionId;
1245
+ const handoffPath = lineage.currentHandoffPath;
1246
+ const key = `${workerSessionId}:${handoffPath}`;
1247
+ if (this.successorLaunches.has(key)) continue;
1248
+ if (lineage.state === "replacing") {
1249
+ try {
1250
+ await this.restoreHandoffReady(ctx.cwd, entry.name, lineage.currentGeneration);
1251
+ } catch {
1252
+ // A live successor advanced this lineage, so there is nothing to recover.
1253
+ continue;
1254
+ }
1255
+ lineage = await readWorkerLineage(ctx.cwd, entry.name).catch(() => undefined);
1256
+ if (!lineage) continue;
1257
+ }
1258
+ if (
1259
+ lineage.state !== "handoff_ready" ||
1260
+ lineage.workerSessionId !== workerSessionId ||
1261
+ lineage.currentHandoffPath !== handoffPath
1262
+ ) {
1263
+ continue;
1264
+ }
1265
+ const issuedAt = this.deps.now();
1266
+ this.acceptWorkerHandoff(ctx, {
1267
+ id: this.deps.randomId("msg"),
1268
+ fromSessionId: workerSessionId,
1269
+ fromCwd: ctx.cwd,
1270
+ toSessionId: ctx.sessionManager.getSessionId(),
1271
+ mode: "notify",
1272
+ kind: "handoff",
1273
+ text: handoffPath,
1274
+ issuedAt,
1275
+ expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
1276
+ });
1277
+ }
1278
+ }
1279
+
1280
+ private async spawnSuccessor(ctx: ExtensionContext, message: SwarmMessage): Promise<void> {
1281
+ const projectRoot = message.fromCwd;
1282
+ if (!projectRoot) throw new Error("Handoff sender did not provide its project cwd");
1283
+ const handoffPath = resolve(message.text);
1284
+ const storagePrefix = `${resolve(projectRoot, ".pi", "agent-swarm", "lineages")}${sep}`;
1285
+ if (!handoffPath.startsWith(storagePrefix) || basename(dirname(handoffPath)) !== "generations") {
1286
+ throw new Error("Handoff path is outside the sender's project lineage storage");
1287
+ }
1288
+ const lineageId = basename(dirname(dirname(handoffPath)));
1289
+ const lineage = await readWorkerLineage(projectRoot, lineageId);
1290
+ if (!this.isCurrent(ctx)) throw staleError();
1291
+ if (
1292
+ lineage.leaderSessionId !== ctx.sessionManager.getSessionId() ||
1293
+ resolve(lineage.currentHandoffPath ?? "") !== handoffPath ||
1294
+ lineage.state !== "handoff_ready" ||
1295
+ !lineage.nextAction
1296
+ ) {
1297
+ throw new Error("Handoff lineage is not ready for this leader");
1298
+ }
1299
+ if (lineage.replacementCount >= lineage.policy.maxReplacements) {
1300
+ throw new Error("Handoff replacement budget is exhausted");
1301
+ }
1302
+ // Reading the exact artifact before launch proves that this leader can access
1303
+ // the durable handoff; its contents are not injected into the leader context.
1304
+ await readFile(handoffPath, "utf8");
1305
+ const nextGeneration = lineage.currentGeneration + 1;
1306
+ const replacementCount = lineage.replacementCount + 1;
1307
+ await updateWorkerLineage(
1308
+ projectRoot,
1309
+ lineageId,
1310
+ { state: "replacing" },
1311
+ { generation: lineage.currentGeneration, state: "handoff_ready" },
1312
+ );
1313
+ const baseName = lineage.launch.name ?? `Worker ${lineageId.slice(-6)}`;
1314
+ const continuation = [
1315
+ `Continue Swarm lineage ${lineageId}, generation ${nextGeneration}.`,
1316
+ `Read the exact handoff at ${handoffPath}.`,
1317
+ `Original objective: ${lineage.originalObjective}`,
1318
+ `Remaining objective: ${lineage.remainingWork ?? "See the handoff."}`,
1319
+ `Exact next action: ${lineage.nextAction}`,
1320
+ "Do not repeat completed work. Read artifact paths only when needed. Report through session_bus with taskStatus.",
1321
+ ].join("\n");
1322
+ let result: SpawnSessionResult | undefined;
1323
+ try {
1324
+ result = await this.spawn(ctx, {
1325
+ cwd: lineage.launch.cwd,
1326
+ model: lineage.launch.model,
1327
+ name: `${baseName} · G${nextGeneration}`.slice(0, 200),
1328
+ ...(lineage.launch.color ? { color: lineage.launch.color } : {}),
1329
+ allowRequests: lineage.launch.allowRequests,
1330
+ recyclingLaunch: {
1331
+ lineageId,
1332
+ generation: nextGeneration,
1333
+ replacementCount,
1334
+ policy: lineage.policy,
1335
+ handoffPath,
1336
+ },
1337
+ task: continuation,
1338
+ });
1339
+ if (!result.kickoffAccepted) throw new Error("Successor did not accept its continuation");
1340
+ if (!this.isCurrent(ctx)) throw staleError();
1341
+ } catch (error) {
1342
+ if (result && (!result.kickoffAccepted || !this.isCurrent(ctx))) {
1343
+ await this.shutdownPeer(ctx, result.sessionId).catch(() => undefined);
1344
+ }
1345
+ await this.restoreHandoffReady(projectRoot, lineageId, lineage.currentGeneration);
1346
+ throw error;
1347
+ }
1348
+ await updateWorkerLineage(
1349
+ projectRoot,
1350
+ lineageId,
1351
+ {
1352
+ state: "working",
1353
+ currentGeneration: nextGeneration,
1354
+ replacementCount,
1355
+ successorSessionId: result.sessionId,
1356
+ },
1357
+ { generation: nextGeneration },
1358
+ );
1359
+ let predecessorRetired = false;
1360
+ let shutdownError = "unknown reason";
1361
+ for (let attempt = 0; attempt < 2 && this.isCurrent(ctx); attempt += 1) {
1362
+ try {
1363
+ const shutdown = await this.shutdownPeer(ctx, message.fromSessionId);
1364
+ predecessorRetired = shutdown.acknowledgement.accepted;
1365
+ shutdownError = shutdown.acknowledgement.error ?? "shutdown rejected";
1366
+ } catch (error) {
1367
+ shutdownError = safeError(error);
1368
+ }
1369
+ if (predecessorRetired) break;
1370
+ if (attempt === 0) await this.deps.sleep(25, this.controller.signal).catch(() => undefined);
1371
+ }
1372
+ if (predecessorRetired && this.isCurrent(ctx)) {
1373
+ await updateWorkerLineage(
1374
+ projectRoot,
1375
+ lineageId,
1376
+ { retiredThroughGeneration: lineage.currentGeneration },
1377
+ { generation: nextGeneration, state: "working" },
1378
+ );
1379
+ } else if (this.isCurrent(ctx)) {
1380
+ this.notify(
1381
+ ctx,
1382
+ `Successor is ready, but the predecessor remains frozen: ${safeTerminalLine(shutdownError)}`,
1383
+ "warning",
1384
+ );
1385
+ }
1386
+ if (this.isCurrent(ctx)) {
1387
+ this.notify(
1388
+ ctx,
1389
+ `Pi Agent Swarm replaced ${safeTerminalLine(baseName)} with generation ${nextGeneration}.`,
1390
+ "info",
1391
+ );
1392
+ }
1393
+ }
1394
+
1395
+ private async restoreHandoffReady(projectRoot: string, lineageId: string, generation: number): Promise<void> {
1396
+ const latest = await readWorkerLineage(projectRoot, lineageId);
1397
+ if (latest.currentGeneration === generation && latest.state === "replacing") {
1398
+ await updateWorkerLineage(projectRoot, lineageId, { state: "handoff_ready" }, { generation, state: "replacing" });
1399
+ }
1400
+ }
1401
+
1402
+ private async noteIncomingWork(message: SwarmMessage): Promise<void> {
1403
+ const recycling = this.recycling;
1404
+ if (!recycling || (message.mode !== "kickoff" && message.mode !== "request")) return;
1405
+ recycling.taskStatus = "working";
1406
+ recycling.handoff = undefined;
1407
+ recycling.state = "working";
1408
+ recycling.handoffAttempts = 0;
1409
+ const patch: Record<string, unknown> = { state: "working" };
1410
+ if (message.mode === "kickoff" && recycling.launch.generation === 1) patch.originalObjective = message.text;
1411
+ await updateWorkerLineage(recycling.projectRoot, recycling.launch.lineageId, patch, {
1412
+ generation: recycling.launch.generation,
1413
+ });
1414
+ }
1415
+
844
1416
  private receiveMessage(message: SwarmMessage): void {
845
1417
  const sender = message.fromName ?? message.fromSessionId;
846
1418
  const heading =
@@ -1162,6 +1734,83 @@ export class SwarmController {
1162
1734
  await this.renderFooterStatus(ctx);
1163
1735
  }
1164
1736
 
1737
+ /**
1738
+ * Count completed turns and start the one-shot auto-name attempt for a
1739
+ * human-started session. The attempt runs in the background as an owned task
1740
+ * so shutdown waits for it; it never blocks the turn_end event path. The
1741
+ * returned promise resolves when the attempt settles (tests await it).
1742
+ */
1743
+ noteTurnEnd(ctx: ExtensionContext): Promise<void> {
1744
+ if (!this.isCurrent(ctx)) return Promise.resolve();
1745
+ if (!this.autoNameEligible) return Promise.resolve();
1746
+ if (this.autoNameInFlight) return Promise.resolve();
1747
+ if (!this.autoNamer.noteTurn(this.pi.getSessionName(), this.settings.get().settings.autoName)) {
1748
+ return Promise.resolve();
1749
+ }
1750
+ this.autoNameInFlight = true;
1751
+ const task = this.runAutoName(ctx, ctx.sessionManager, this.generation).finally(() => {
1752
+ this.autoNameInFlight = false;
1753
+ });
1754
+ return this.track(task);
1755
+ }
1756
+
1757
+ /**
1758
+ * Keep the roster peer name and the footer badge in sync when the session
1759
+ * name changes outside the extension (for example `/name`), and treat a
1760
+ * custom name as the user taking over so auto-naming steps aside.
1761
+ */
1762
+ async noteSessionInfoChanged(name: string | undefined, ctx: ExtensionContext): Promise<void> {
1763
+ if (!this.isCurrent(ctx)) return;
1764
+ if (name === undefined || name !== this.applyingAutoName) this.autoNamer.noteExternalName(name);
1765
+ if (name) this.membership?.transport.setName(name);
1766
+ await this.renderFooterStatus(ctx);
1767
+ }
1768
+
1769
+ /**
1770
+ * Best-effort naming: summarize the first turns into `MAN-<title>` with the
1771
+ * current (or configured) model. Any failure keeps the default MANAGER-<id>
1772
+ * name, is recorded as a session entry for diagnosis, and is retried on a
1773
+ * later turn until the attempt budget runs out. The session name is
1774
+ * re-checked right before applying so a rename that happened during the
1775
+ * completion always wins.
1776
+ */
1777
+ private async runAutoName(ctx: ExtensionContext, owner: object, ownerGeneration: number): Promise<void> {
1778
+ try {
1779
+ const configured = this.settings.get().settings.autoNameModel;
1780
+ const model = resolveAutoNameModel(ctx, configured);
1781
+ if (!model) {
1782
+ if (configured) {
1783
+ this.notify(
1784
+ ctx,
1785
+ `Pi Agent Swarm could not resolve autoNameModel "${configured}"; keeping the default session name.`,
1786
+ "warning",
1787
+ );
1788
+ }
1789
+ return;
1790
+ }
1791
+ const messages = collectAutoNameMessages(ctx);
1792
+ if (messages.length === 0) return;
1793
+ const signal = AbortSignal.any([this.controller.signal, AbortSignal.timeout(AUTO_NAME_TIMEOUT_MS)]);
1794
+ const complete = this.deps.completeSessionTitle ?? defaultCompleteSessionTitle;
1795
+ const raw = await complete(ctx, model, buildAutoNamePrompt(messages), signal);
1796
+ if (!this.isCurrent(owner, ownerGeneration)) return;
1797
+ const name = toAutoName(raw);
1798
+ if (!name) return;
1799
+ const currentName = this.pi.getSessionName();
1800
+ if (currentName !== undefined && !isDefaultManagerName(currentName)) return;
1801
+ this.applyingAutoName = name;
1802
+ try {
1803
+ await this.setOwnName(ctx, name, signal);
1804
+ } finally {
1805
+ this.applyingAutoName = undefined;
1806
+ }
1807
+ } catch (error) {
1808
+ // Best-effort: any failure keeps the default MANAGER-<id> name and is
1809
+ // retried on a later turn; record it for offline diagnosis only.
1810
+ this.pi.appendEntry("pi-swarm-auto-name", { ok: false, error: safeTerminalLine(safeError(error)) });
1811
+ }
1812
+ }
1813
+
1165
1814
  /**
1166
1815
  * Best-effort, ordered relay of a direct user steer to the parent session so it
1167
1816
  * stays aligned. This returns immediately: sends are chained so ordering is