pi-agent-swarm 0.3.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,6 +1,6 @@
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
4
  import type { Api, Model } from "@earendil-works/pi-ai";
5
5
  import type {
6
6
  ExtensionAPI,
@@ -26,6 +26,22 @@ import {
26
26
  swarmColorName,
27
27
  swarmColorPalette,
28
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";
29
45
  import { parseExternalCommand } from "./external.js";
30
46
  import { buildRosterBadge, DEFAULT_TERMINAL_COLUMNS } from "./footer.js";
31
47
  import { consumeLaunchEnvelope, launchEnvelopeEnvironment, type SwarmLaunchEnvelope } from "./launch-envelope.js";
@@ -137,6 +153,10 @@ export interface SwarmSnapshot {
137
153
 
138
154
  export interface SpawnSessionInput {
139
155
  direction?: TerminalSplitDirection;
156
+ allowRequests?: boolean;
157
+ contextRecycling?: ContextRecyclingPolicyInput;
158
+ /** Internal continuation identity; public tools use contextRecycling instead. */
159
+ recyclingLaunch?: ContextRecyclingLaunch;
140
160
  task?: string;
141
161
  name?: string;
142
162
  color?: string;
@@ -152,6 +172,18 @@ export interface SpawnSessionResult {
152
172
  terminalId: string;
153
173
  terminalVersion: string;
154
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;
155
187
  }
156
188
 
157
189
  interface Membership {
@@ -208,6 +240,9 @@ export class SwarmController {
208
240
  private resizeWatching = false;
209
241
  private readonly pendingKickoffIds = new Set<string>();
210
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>>();
211
246
 
212
247
  constructor(
213
248
  private readonly pi: ExtensionAPI,
@@ -233,6 +268,9 @@ export class SwarmController {
233
268
  this.autoNameInFlight = false;
234
269
  this.pendingKickoffIds.clear();
235
270
  this.relayChain = Promise.resolve();
271
+ this.recycling = undefined;
272
+ this.recyclingChain = Promise.resolve();
273
+ this.successorLaunches.clear();
236
274
  this.startLeadWatcher();
237
275
  this.startResizeWatcher();
238
276
  const owner = ctx.sessionManager;
@@ -298,6 +336,10 @@ export class SwarmController {
298
336
  handoff?.kickoffConsumed ?? false,
299
337
  ),
300
338
  );
339
+ const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
340
+ if (recyclingLaunch && this.parentSessionId) {
341
+ await this.initializeContextRecycling(ctx, recyclingLaunch, this.parentSessionId);
342
+ }
301
343
  } catch (error) {
302
344
  if (this.isCurrent(owner, ownerGeneration)) {
303
345
  this.notify(ctx, `Pi Agent Swarm could not join the launch group: ${safeError(error)}`, "error");
@@ -338,6 +380,7 @@ export class SwarmController {
338
380
  ...(peerName ? { name: peerName } : {}),
339
381
  ...(peerColor ? { color: peerColor } : {}),
340
382
  ...(this.parentSessionId ? { parentSessionId: this.parentSessionId } : {}),
383
+ ...(this.recycling ? { contextRecycling: this.recycling.launch } : {}),
341
384
  expiresAt: this.deps.now() + RELOAD_HANDOFF_TTL_MS,
342
385
  });
343
386
  }
@@ -378,6 +421,10 @@ export class SwarmController {
378
421
  // Best-effort: a manager can still run a group without an explicit lead record.
379
422
  }
380
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
+ });
381
428
  return this.snapshot(signal);
382
429
  });
383
430
  }
@@ -418,9 +465,249 @@ export class SwarmController {
418
465
  setAcceptsRequests(ctx: ExtensionContext, value: boolean): void {
419
466
  this.assertCurrentContext(ctx);
420
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
+ }
421
471
  this.membership.rollbackLaunch = undefined;
422
472
  this.membership.acceptsRequests = value;
423
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);
424
711
  }
425
712
 
426
713
  async snapshot(signal?: AbortSignal): Promise<SwarmSnapshot> {
@@ -466,6 +753,8 @@ export class SwarmController {
466
753
  text: string;
467
754
  mode: Exclude<SwarmMessageMode, "kickoff">;
468
755
  replyTo?: string;
756
+ taskStatus?: WorkerTaskStatus;
757
+ handoff?: WorkerHandoffContent;
469
758
  },
470
759
  signal?: AbortSignal,
471
760
  ): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }> {
@@ -473,7 +762,12 @@ export class SwarmController {
473
762
  const membership = this.membership;
474
763
  if (!membership) throw new Error("Pi Agent Swarm is not connected");
475
764
  membership.rollbackLaunch = undefined;
476
- 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) {
477
771
  throw new Error("Pi Agent Swarm message is too large");
478
772
  }
479
773
  const self = membership.transport.peerDescription;
@@ -485,7 +779,7 @@ export class SwarmController {
485
779
  fromCwd: self.cwd,
486
780
  toSessionId: options.targetSessionId,
487
781
  mode: options.mode,
488
- text: options.text,
782
+ text: `${metricPrefix}${options.text}`,
489
783
  issuedAt,
490
784
  expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
491
785
  ...(options.replyTo ? { replyTo: options.replyTo } : {}),
@@ -497,6 +791,10 @@ export class SwarmController {
497
791
  if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
498
792
  throw staleError();
499
793
  }
794
+ if (acknowledgement.accepted && this.recycling && options.mode === "reply") {
795
+ this.recycling.taskStatus = options.taskStatus ?? "working";
796
+ this.recycling.handoff = options.handoff;
797
+ }
500
798
  return { message, acknowledgement };
501
799
  }
502
800
 
@@ -553,6 +851,16 @@ export class SwarmController {
553
851
  await this.settings.flush();
554
852
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
555
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);
556
864
  const direction = input.direction ?? "right";
557
865
  const windowLabel = "window";
558
866
  const launchLayoutLine = "External terminal window (the window manager places it)";
@@ -596,7 +904,7 @@ export class SwarmController {
596
904
  );
597
905
  const terminalVersion = await terminalAdapter.assertAvailable(operationSignal);
598
906
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
599
- if (launchSettings.confirmSessionLaunch) {
907
+ if (launchSettings.confirmSessionLaunch && !input.recyclingLaunch) {
600
908
  const confirmed = await ctx.ui.confirm(
601
909
  "Create a new Pi session?",
602
910
  [
@@ -605,6 +913,8 @@ export class SwarmController {
605
913
  `Color: ${safeTerminalLine(color)}`,
606
914
  `Cwd: ${safeTerminalLine(cwd)}`,
607
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"}.`,
608
918
  "The child may spend model tokens and edit the same workspace concurrently.",
609
919
  ].join("\n"),
610
920
  { signal: operationSignal },
@@ -632,7 +942,8 @@ export class SwarmController {
632
942
  kickoffCapability,
633
943
  childName: name,
634
944
  childColor: color,
635
- acceptsRequests: false,
945
+ acceptsRequests: input.allowRequests === true,
946
+ ...(recyclingLaunch ? { contextRecycling: recyclingLaunch } : {}),
636
947
  ...(childModel ? { model: childModel } : {}),
637
948
  };
638
949
  const launchEnvironment = launchEnvelopeEnvironment(envelope);
@@ -699,6 +1010,7 @@ export class SwarmController {
699
1010
  terminalId,
700
1011
  terminalVersion: actualTerminalVersion,
701
1012
  kickoffAccepted,
1013
+ ...(recyclingLaunch ? { lineageId: recyclingLaunch.lineageId } : {}),
702
1014
  };
703
1015
  } catch (error) {
704
1016
  const partial = splitCreated || (isTerminalLaunchError(error) && error.splitCreated);
@@ -799,6 +1111,19 @@ export class SwarmController {
799
1111
  authorizeShutdown: (message) =>
800
1112
  message.fromSessionId === this.parentSessionId ||
801
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
+ },
802
1127
  onMessage: async (message, deliverySignal) => {
803
1128
  if (deliverySignal?.aborted || !this.isCurrent(owner, ownerGeneration)) return;
804
1129
  const activeContext = this.activeContext;
@@ -812,6 +1137,19 @@ export class SwarmController {
812
1137
  // without a provider request and the settle boundary performs the
813
1138
  // shutdown. A busy session settles on its own and needs no trigger.
814
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
+ }
815
1153
  activeContext?.shutdown();
816
1154
  if (idle && activeContext) {
817
1155
  const details: SwarmMessageDetails = { message };
@@ -826,7 +1164,10 @@ export class SwarmController {
826
1164
  if (message.kind === "lead") {
827
1165
  // Lead broadcasts only update the role badge; they never enter the model
828
1166
  // context. refreshLead below reconciles the same information.
1167
+ } else if (message.kind === "handoff") {
1168
+ if (activeContext) await this.acceptWorkerHandoff(activeContext, message);
829
1169
  } else {
1170
+ await this.noteIncomingWork(message);
830
1171
  this.receiveMessage(message);
831
1172
  }
832
1173
  void this.refreshLead().then((changed) => {
@@ -871,6 +1212,207 @@ export class SwarmController {
871
1212
  }
872
1213
  }
873
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
+
874
1416
  private receiveMessage(message: SwarmMessage): void {
875
1417
  const sender = message.fromName ?? message.fromSessionId;
876
1418
  const heading =