pi-agent-swarm 0.5.0 → 0.7.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.
@@ -34,6 +34,7 @@ import {
34
34
  verifyLeaderHandoffReadable,
35
35
  } from "./leader-recycling.js";
36
36
  import {
37
+ getLeaderExternalRestorer,
37
38
  getLeaderRestoreGate,
38
39
  getLeaderSessionActions,
39
40
  getLeaderSessionRestoreError,
@@ -44,6 +45,17 @@ import {
44
45
  import type { SwarmMessage } from "./protocol.js";
45
46
  import type { LeaderRecyclingSettings, SwarmSettingsRuntime } from "./settings.js";
46
47
 
48
+ export interface ExternalLeaderContextSnapshot {
49
+ runtimeId: string;
50
+ tokens: number | null;
51
+ contextWindow: number;
52
+ completedTurns: number;
53
+ compactionCount: number;
54
+ model?: string;
55
+ thoughtLevel?: string;
56
+ mode?: string;
57
+ }
58
+
47
59
  export interface LeaderControlSnapshot {
48
60
  isLead: boolean;
49
61
  pendingKickoffIds: string[];
@@ -51,11 +63,32 @@ export interface LeaderControlSnapshot {
51
63
  groupDirectory?: string;
52
64
  acceptsRequests: boolean;
53
65
  color?: string;
66
+ externalRuntime?: {
67
+ runtimeId: string;
68
+ model?: string;
69
+ thoughtLevel?: string;
70
+ mode?: string;
71
+ };
54
72
  }
55
73
 
56
74
  export interface LeaderRuntimeHost {
57
75
  isCurrent(ctx: ExtensionContext): boolean;
58
76
  leaderSnapshot(ctx: ExtensionContext): LeaderControlSnapshot;
77
+ externalLeaderContext?(ctx: ExtensionContext): ExternalLeaderContextSnapshot | undefined;
78
+ externalPendingCount?(ctx: ExtensionContext): number;
79
+ isPostTimeoutHandoffPending?(ctx: ExtensionContext): boolean;
80
+ clearExternalLeaderQueue?(ctx: ExtensionContext, replaceTag?: string): void;
81
+ deliverExternalLeaderPrompt?(
82
+ ctx: ExtensionContext,
83
+ prompt: string,
84
+ source: "leader_advisory" | "leader_kickoff",
85
+ replaceTag?: string,
86
+ ): boolean;
87
+ restoreExternalLeader?(
88
+ ctx: ExtensionContext,
89
+ externalRuntime: NonNullable<LeaderHandoffBridgeEntry["externalRuntime"]>,
90
+ handoffPrompt: string,
91
+ ): Promise<void>;
59
92
  restoreLeaderControl(ctx: ExtensionContext, entry: LeaderHandoffBridgeEntry): Promise<void>;
60
93
  commitLeaderControl(ctx: ExtensionContext, entry: LeaderHandoffBridgeEntry): Promise<void>;
61
94
  announceCommittedLeader?(ctx: ExtensionContext): Promise<void>;
@@ -123,6 +156,7 @@ export class LeaderRuntime {
123
156
  private replacingSession = false;
124
157
  private autoDispatch?: ReturnType<typeof setTimeout>;
125
158
  private autoResponsePending = false;
159
+ private postTimeoutAdvisoryDispatched = false;
126
160
  /** Set once the user was told that automatic handoffs are circuit-broken. */
127
161
  private autoCircuitWarningShown = false;
128
162
 
@@ -158,6 +192,7 @@ export class LeaderRuntime {
158
192
  this.turnDeferred = [];
159
193
  this.autoDispatch = undefined;
160
194
  this.autoResponsePending = false;
195
+ this.postTimeoutAdvisoryDispatched = false;
161
196
  this.autoCircuitWarningShown = false;
162
197
  this.advisoryMilestones.clear();
163
198
  this.handoffBatch = undefined;
@@ -299,26 +334,52 @@ export class LeaderRuntime {
299
334
  this.scheduleApplyDispatch(staged, ctx);
300
335
  return;
301
336
  }
337
+ const externalPending = this.host.externalPendingCount?.(ctx) ?? 0;
338
+ if (externalPending > 0) {
339
+ // Wait until the external runtime drains its queued messages before evaluating auto-handoff
340
+ // or judging whether a previous automatic advisory went unanswered.
341
+ return;
342
+ }
302
343
  if (this.autoResponsePending && !this.staged && !this.applying) {
303
344
  this.autoResponsePending = false;
304
345
  if (!aborted) {
305
346
  await this.noteAutoFailure(ctx, "The model did not publish a leader handoff before the automatic turn ended.");
306
347
  // A failed automatic response is a new attempt, not a duplicate milestone advisory.
307
348
  this.advisoryMilestones.clear();
349
+ this.postTimeoutAdvisoryDispatched = false;
308
350
  }
309
351
  }
310
352
  if (aborted || this.staged || this.applying) return;
311
353
  const config = this.settings.get().settings.leaderRecycling;
312
- if (config.mode !== "auto") return;
354
+ if (!config.enabled || config.mode !== "auto") return;
313
355
  const sessionId = ctx.sessionManager.getSessionId();
314
- const advisory = await this.createAdvisory(ctx);
356
+ const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
357
+ const handoffToolName = activeExternal ? "swarm_leader_handoff" : "leader_handoff";
358
+ let advisory = await this.createAdvisory(ctx);
359
+ if (!advisory && this.host.isPostTimeoutHandoffPending?.(ctx) && !this.postTimeoutAdvisoryDispatched) {
360
+ const canRecycle = await this.canRecycleLeader(ctx);
361
+ if (canRecycle && this.isCurrent(ctx, sessionId) && !this.staged && !this.applying) {
362
+ this.postTimeoutAdvisoryDispatched = true;
363
+ advisory = {
364
+ priority: "high",
365
+ content: [
366
+ "[Pi Agent Swarm post-timeout leader handoff]",
367
+ "The previous mission countdown expired and closed in convergence mode.",
368
+ "End this leader generation cleanly and hand off to a fresh successor session before starting a new mission countdown.",
369
+ ].join("\n"),
370
+ };
371
+ }
372
+ }
315
373
  if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
316
- const automatic = `${advisory.content}\n\nAutomatic leader recycling is enabled. Call leader_handoff now with all ten sections; do not answer the user first.`;
374
+ const automatic = `${advisory.content}\n\nAutomatic leader recycling is enabled. Call ${handoffToolName} now with all ten sections; do not answer the user first.`;
317
375
  const dispatch = setTimeout(() => {
318
376
  if (this.autoDispatch === dispatch) this.autoDispatch = undefined;
319
377
  if (!this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
320
378
  try {
321
379
  this.autoResponsePending = true;
380
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory", "leader-advisory")) {
381
+ return;
382
+ }
322
383
  this.pi.sendMessage(
323
384
  { customType: LEADER_ADVISORY_CUSTOM_TYPE, content: automatic, display: false },
324
385
  { deliverAs: "followUp", triggerTurn: true },
@@ -333,6 +394,21 @@ export class LeaderRuntime {
333
394
  this.autoDispatch = dispatch;
334
395
  }
335
396
 
397
+ /** True when leader recycling is enabled, persisted, within replacement budget, and not circuit-broken. */
398
+ async canRecycleLeader(ctx: ExtensionContext): Promise<boolean> {
399
+ const config = this.settings.get().settings.leaderRecycling;
400
+ if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead) return false;
401
+ if (!ctx.sessionManager.getSessionFile()) return false;
402
+ const sessionId = ctx.sessionManager.getSessionId();
403
+ const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
404
+ if (!this.isCurrent(ctx, sessionId)) return false;
405
+ if (lineage) {
406
+ if (lineage.replacementCount >= config.maxReplacements) return false;
407
+ if (config.mode === "auto" && (lineage.autoCircuitOpen || (lineage.autoFailures ?? 0) >= 3)) return false;
408
+ }
409
+ return true;
410
+ }
411
+
336
412
  isLeaderReplacementShutdown(): boolean {
337
413
  return this.replacingSession;
338
414
  }
@@ -455,8 +531,26 @@ export class LeaderRuntime {
455
531
  }).catch(() => undefined);
456
532
  throw error;
457
533
  }
458
- const usage = ctx.getContextUsage();
459
- const analysis = usage ? analyzeSessionBranch(ctx.sessionManager.getBranch(), usage) : undefined;
534
+ const externalCtx = this.host.externalLeaderContext?.(ctx);
535
+ const analysis = externalCtx
536
+ ? {
537
+ status:
538
+ externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? ("known" as const) : ("unknown" as const),
539
+ completedTurns: externalCtx.completedTurns,
540
+ contextTokens: externalCtx.tokens,
541
+ contextWindow: externalCtx.contextWindow,
542
+ percent:
543
+ externalCtx.tokens !== null && externalCtx.contextWindow > 0
544
+ ? (externalCtx.tokens / externalCtx.contextWindow) * 100
545
+ : null,
546
+ oldToolOutputTokens: 0,
547
+ toolResultCountOver2KB: 0,
548
+ compactionCount: externalCtx.compactionCount,
549
+ }
550
+ : (() => {
551
+ const usage = ctx.getContextUsage();
552
+ return usage ? analyzeSessionBranch(ctx.sessionManager.getBranch(), usage) : undefined;
553
+ })();
460
554
  await transitionLeaderLineage(ctx.cwd, lineage.lineageId, "replacing", {
461
555
  expectedGeneration: lineage.currentGeneration,
462
556
  patch: {
@@ -478,6 +572,7 @@ export class LeaderRuntime {
478
572
  color: control.color,
479
573
  model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
480
574
  thinkingLevel: this.pi.getThinkingLevel(),
575
+ ...(control.externalRuntime ? { externalRuntime: control.externalRuntime } : {}),
481
576
  invite: control.invite,
482
577
  groupDirectory: control.groupDirectory,
483
578
  acceptsRequests: control.acceptsRequests,
@@ -486,6 +581,9 @@ export class LeaderRuntime {
486
581
  editorDraft: ctx.hasUI ? ctx.ui.getEditorText() : undefined,
487
582
  });
488
583
  this.staged = { entry, applySent: false, applyAttempts: 0, automatic };
584
+ // Clear any stale queued prompts (e.g. duplicate advisories or expired mission notices)
585
+ // in the external runtime before the doomed predecessor session is replaced.
586
+ this.host.clearExternalLeaderQueue?.(ctx);
489
587
  // Adopt every message this turn already accepted: it belongs to the successor, not the predecessor.
490
588
  if (this.turnDeferred.length > 0) {
491
589
  entry.deferredFollowUps = [...(entry.deferredFollowUps ?? []), ...this.turnDeferred];
@@ -513,11 +611,17 @@ export class LeaderRuntime {
513
611
  if (trimmed.length > 0) throw new Error("Usage: /swarm handoff [--apply <token>]");
514
612
  if (!this.settings.get().settings.leaderRecycling.enabled) throw new Error("Leader recycling is disabled.");
515
613
  if (!this.host.leaderSnapshot(ctx).isLead) throw new Error("Only the lead session can hand off.");
614
+ const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
615
+ const handoffPrompt = activeExternal
616
+ ? "The user requested a leader context handoff. Call swarm_leader_handoff now with all ten required sections, then stop. Do not answer the user first."
617
+ : "The user requested a leader context handoff. Call leader_handoff now with all ten required sections, then stop. Do not answer the user first.";
618
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory", "leader-advisory")) {
619
+ return;
620
+ }
516
621
  await this.pi.sendMessage(
517
622
  {
518
623
  customType: LEADER_ADVISORY_CUSTOM_TYPE,
519
- content:
520
- "The user requested a leader context handoff. Call leader_handoff now with all ten required sections, then stop. Do not answer the user first.",
624
+ content: handoffPrompt,
521
625
  display: false,
522
626
  },
523
627
  // Streaming uses AgentSession.followUp; false only appends a dormant custom message.
@@ -661,6 +765,7 @@ export class LeaderRuntime {
661
765
  generation,
662
766
  model,
663
767
  thinkingLevel,
768
+ externalRuntime,
664
769
  editorDraft,
665
770
  nextAction,
666
771
  previousSessionId: previousLeaderSessionId,
@@ -759,6 +864,39 @@ export class LeaderRuntime {
759
864
  await this.openSuccessorGate(replacedCtx);
760
865
  return;
761
866
  }
867
+ if (externalRuntime) {
868
+ const successorRestorer = getLeaderExternalRestorer(replacedCtx.sessionManager);
869
+ const hostRestorer = this.host.restoreExternalLeader;
870
+ const restoreFn = successorRestorer
871
+ ? (ext: NonNullable<LeaderHandoffBridgeEntry["externalRuntime"]>, prompt: string) =>
872
+ successorRestorer(ext, prompt)
873
+ : hostRestorer
874
+ ? (ext: NonNullable<LeaderHandoffBridgeEntry["externalRuntime"]>, prompt: string) =>
875
+ hostRestorer(replacedCtx, ext, prompt)
876
+ : undefined;
877
+ if (restoreFn) {
878
+ try {
879
+ const externalKickoff = [
880
+ "You are the successor leader in a fresh session. Read the leader handoff below and continue immediately.",
881
+ "",
882
+ handoff,
883
+ "",
884
+ `Continue with this exact next action: ${nextAction}`,
885
+ ].join("\n");
886
+ kickoffQueued = true;
887
+ await restoreFn(externalRuntime, externalKickoff);
888
+ await this.openSuccessorGate(replacedCtx);
889
+ } catch (error) {
890
+ this.notify(
891
+ replacedCtx,
892
+ `Could not restore external leader runtime (${externalRuntime.runtimeId}): ${errorMessage(error)}`,
893
+ "error",
894
+ );
895
+ await this.openSuccessorGate(replacedCtx);
896
+ }
897
+ return;
898
+ }
899
+ }
762
900
  try {
763
901
  const kickoff = replacedCtx.sendUserMessage(
764
902
  `You are the successor leader. Read the injected leader handoff. Continue with this exact next action: ${nextAction}`,
@@ -856,12 +994,40 @@ export class LeaderRuntime {
856
994
  if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead || this.staged || this.applying) return undefined;
857
995
  if (!ctx.sessionManager.getSessionFile()) return undefined;
858
996
  const sessionId = ctx.sessionManager.getSessionId();
859
- const usage = ctx.getContextUsage();
860
- if (!usage) return undefined;
861
- const branch = ctx.sessionManager.getBranch();
862
997
  const policy = leaderPolicy(config);
863
- if (!shouldAnalyzeLeaderBranch(branch, usage, policy)) return undefined;
864
- const analysis = analyzeSessionBranch(branch, usage);
998
+ const externalCtx = this.host.externalLeaderContext?.(ctx);
999
+ let analysis: ReturnType<typeof analyzeSessionBranch>;
1000
+ if (externalCtx) {
1001
+ const extUsage = {
1002
+ tokens: externalCtx.tokens,
1003
+ contextWindow: externalCtx.contextWindow,
1004
+ percent:
1005
+ externalCtx.tokens !== null && externalCtx.contextWindow > 0
1006
+ ? (externalCtx.tokens / externalCtx.contextWindow) * 100
1007
+ : null,
1008
+ };
1009
+ const hasPressure =
1010
+ shouldAnalyzeLeaderBranch([], extUsage, policy) ||
1011
+ externalCtx.compactionCount >= 1 ||
1012
+ (externalCtx.tokens !== null && externalCtx.completedTurns >= 25 && externalCtx.tokens >= 35_000);
1013
+ if (!hasPressure) return undefined;
1014
+ analysis = {
1015
+ status: extUsage.tokens !== null && extUsage.contextWindow > 0 ? "known" : "unknown",
1016
+ completedTurns: externalCtx.completedTurns,
1017
+ contextTokens: extUsage.tokens,
1018
+ contextWindow: extUsage.contextWindow,
1019
+ percent: extUsage.percent,
1020
+ oldToolOutputTokens: 0,
1021
+ toolResultCountOver2KB: 0,
1022
+ compactionCount: externalCtx.compactionCount,
1023
+ };
1024
+ } else {
1025
+ const usage = ctx.getContextUsage();
1026
+ if (!usage) return undefined;
1027
+ const branch = ctx.sessionManager.getBranch();
1028
+ if (!shouldAnalyzeLeaderBranch(branch, usage, policy)) return undefined;
1029
+ analysis = analyzeSessionBranch(branch, usage);
1030
+ }
865
1031
  const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
866
1032
  if (!this.isCurrent(ctx, sessionId)) return undefined;
867
1033
  if (config.mode === "auto" && (lineage?.autoCircuitOpen || (lineage?.autoFailures ?? 0) >= 3)) {
@@ -1089,6 +1255,7 @@ function leaderPolicy(config: LeaderRecyclingSettings): LeaderRecyclingPolicy {
1089
1255
  softContextPercent: config.softContextPercent,
1090
1256
  softContextTokens: config.softContextTokens,
1091
1257
  highWaterPercent: config.highWaterPercent,
1258
+ ...(config.highWaterTokens !== undefined ? { highWaterTokens: config.highWaterTokens } : {}),
1092
1259
  maxReplacements: config.maxReplacements,
1093
1260
  };
1094
1261
  }
@@ -2,9 +2,20 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  export type LeaderSessionActions = Pick<ExtensionAPI, "setModel" | "setThinkingLevel" | "setSessionName">;
4
4
 
5
+ export type LeaderExternalRestorer = (
6
+ externalRuntime: {
7
+ runtimeId: string;
8
+ model?: string;
9
+ thoughtLevel?: string;
10
+ mode?: string;
11
+ },
12
+ handoffPrompt: string,
13
+ ) => Promise<void>;
14
+
5
15
  type LeaderSessionRuntime = {
6
16
  actions: WeakMap<object, LeaderSessionActions>;
7
17
  restoreGates: WeakMap<object, () => Promise<void>>;
18
+ externalRestorers: WeakMap<object, LeaderExternalRestorer>;
8
19
  restoreStates: WeakMap<object, boolean>;
9
20
  restoreErrors: WeakMap<object, string>;
10
21
  };
@@ -20,10 +31,13 @@ const runtimeGlobal = globalThis as LeaderSessionRuntimeGlobal;
20
31
  runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL] ??= {
21
32
  actions: new WeakMap<object, LeaderSessionActions>(),
22
33
  restoreGates: new WeakMap<object, () => Promise<void>>(),
34
+ externalRestorers: new WeakMap<object, LeaderExternalRestorer>(),
23
35
  restoreStates: new WeakMap<object, boolean>(),
24
36
  restoreErrors: new WeakMap<object, string>(),
25
37
  };
26
38
  const runtime = runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL];
39
+ // Ensure hot-reloaded processes that initialized an older global object still have the WeakMap.
40
+ runtime.externalRestorers ??= new WeakMap<object, LeaderExternalRestorer>();
27
41
 
28
42
  export function registerLeaderSessionActions(sessionManager: object, actions: LeaderSessionActions): void {
29
43
  runtime.actions.set(sessionManager, actions);
@@ -48,6 +62,14 @@ export function getLeaderRestoreGate(sessionManager: object): (() => Promise<voi
48
62
  return runtime.restoreGates.get(sessionManager);
49
63
  }
50
64
 
65
+ export function registerLeaderExternalRestorer(sessionManager: object, restorer: LeaderExternalRestorer): void {
66
+ runtime.externalRestorers.set(sessionManager, restorer);
67
+ }
68
+
69
+ export function getLeaderExternalRestorer(sessionManager: object): LeaderExternalRestorer | undefined {
70
+ return runtime.externalRestorers.get(sessionManager);
71
+ }
72
+
51
73
  export function markLeaderSessionRestore(sessionManager: object, restored: boolean, error?: string): void {
52
74
  runtime.restoreStates.set(sessionManager, restored);
53
75
  if (error) runtime.restoreErrors.set(sessionManager, error);
@@ -66,6 +88,7 @@ export function unregisterLeaderSessionActions(sessionManager: object, actions:
66
88
  if (runtime.actions.get(sessionManager) !== actions) return;
67
89
  runtime.actions.delete(sessionManager);
68
90
  runtime.restoreGates.delete(sessionManager);
91
+ runtime.externalRestorers.delete(sessionManager);
69
92
  runtime.restoreStates.delete(sessionManager);
70
93
  runtime.restoreErrors.delete(sessionManager);
71
94
  }
package/src/ledger.ts CHANGED
@@ -48,6 +48,9 @@ export type SwarmLedgerRole = "lead" | "implementer" | "researcher" | "reviewer"
48
48
  export interface SwarmLedgerUsage {
49
49
  inputTokens?: number;
50
50
  outputTokens?: number;
51
+ cachedReadTokens?: number;
52
+ cachedWriteTokens?: number;
53
+ thoughtTokens?: number;
51
54
  totalTokens?: number;
52
55
  costUsd?: number;
53
56
  }
@@ -75,7 +78,10 @@ export type SwarmLedgerEventName =
75
78
  | "approval_received"
76
79
  | "run_completed"
77
80
  | "run_failed"
78
- | "run_escalated";
81
+ | "run_escalated"
82
+ | "mission_started"
83
+ | "mission_timeout"
84
+ | "mission_completed";
79
85
 
80
86
  export interface SwarmLedgerBaseEvent {
81
87
  ts?: string;
@@ -151,6 +157,7 @@ export type SwarmLedgerEventInput =
151
157
  wallclock_ms: number;
152
158
  cost_usd: number | null;
153
159
  stop_reason: string;
160
+ idle_ms?: number;
154
161
  })
155
162
  | (SwarmLedgerBaseEvent & {
156
163
  event: "run_failed";
@@ -161,6 +168,26 @@ export type SwarmLedgerEventInput =
161
168
  event: "run_escalated";
162
169
  reason: string;
163
170
  budget_left: Record<string, number | null>;
171
+ })
172
+ | (SwarmLedgerBaseEvent & {
173
+ event: "mission_started";
174
+ estimated_minutes: number;
175
+ requested_minutes: number;
176
+ clamped: boolean;
177
+ goal_chars: number;
178
+ })
179
+ | (SwarmLedgerBaseEvent & {
180
+ event: "mission_timeout";
181
+ stage: "converging" | "final_wrap_up";
182
+ elapsed_ms: number;
183
+ in_flight_workers: number;
184
+ })
185
+ | (SwarmLedgerBaseEvent & {
186
+ event: "mission_completed";
187
+ outcome: "achieved" | "with_residuals" | "handoff";
188
+ final_state: "completed" | "auto_completed" | "closed_by_handoff";
189
+ elapsed_ms: number;
190
+ residual_count: number;
164
191
  });
165
192
 
166
193
  export function ledgerDirectoryForProject(projectRoot: string): string {