pi-agent-swarm 0.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agent-swarm",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Window-manager-native agent swarm for the Pi Coding Agent — every agent runs as a real terminal window under a tiling window manager.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -88,6 +88,7 @@ export type ExternalRuntimeEventPayload =
88
88
  thoughtLevel?: string;
89
89
  mode?: string;
90
90
  busy?: boolean;
91
+ pendingCount?: number;
91
92
  }
92
93
  | {
93
94
  type: "direct_deliver";
@@ -97,6 +98,13 @@ export type ExternalRuntimeEventPayload =
97
98
  source: "swarm_message" | "leader_advisory" | "leader_kickoff";
98
99
  messageId?: string;
99
100
  fromSessionId?: string;
101
+ replaceTag?: string;
102
+ }
103
+ | {
104
+ type: "direct_clear_queue";
105
+ runtimeId: string;
106
+ sessionId: string;
107
+ replaceTag?: string;
100
108
  }
101
109
  | {
102
110
  type: "direct_restore";
@@ -125,6 +133,7 @@ export type ExternalRuntimeEventPayload =
125
133
  };
126
134
  settled?: boolean;
127
135
  aborted?: boolean;
136
+ pendingCount?: number;
128
137
  };
129
138
 
130
139
  export interface ExternalDirectState {
@@ -135,6 +144,7 @@ export interface ExternalDirectState {
135
144
  thoughtLevel?: string;
136
145
  mode?: string;
137
146
  busy?: boolean;
147
+ pendingCount?: number;
138
148
  updatedAt: number;
139
149
  }
140
150
 
@@ -154,6 +164,7 @@ export interface ExternalContextUsageReport {
154
164
  };
155
165
  settled: boolean;
156
166
  aborted: boolean;
167
+ pendingCount?: number;
157
168
  updatedAt: number;
158
169
  }
159
170
 
@@ -357,6 +368,7 @@ export class ExternalRuntimeHost {
357
368
  source: "swarm_message" | "leader_advisory" | "leader_kickoff";
358
369
  messageId?: string;
359
370
  fromSessionId?: string;
371
+ replaceTag?: string;
360
372
  }): void {
361
373
  this.emit({
362
374
  type: "direct_deliver",
@@ -366,6 +378,16 @@ export class ExternalRuntimeHost {
366
378
  source: params.source,
367
379
  ...(params.messageId ? { messageId: params.messageId } : {}),
368
380
  ...(params.fromSessionId ? { fromSessionId: params.fromSessionId } : {}),
381
+ ...(params.replaceTag ? { replaceTag: params.replaceTag } : {}),
382
+ });
383
+ }
384
+
385
+ clearDirectQueue(params: { runtimeId: string; sessionId: string; replaceTag?: string }): void {
386
+ this.emit({
387
+ type: "direct_clear_queue",
388
+ runtimeId: params.runtimeId,
389
+ sessionId: params.sessionId,
390
+ ...(params.replaceTag ? { replaceTag: params.replaceTag } : {}),
369
391
  });
370
392
  }
371
393
 
@@ -468,6 +490,9 @@ export class ExternalRuntimeHost {
468
490
  : {}),
469
491
  ...(typeof msg.mode === "string" && msg.mode.length > 0 ? { mode: msg.mode } : {}),
470
492
  ...(typeof msg.busy === "boolean" ? { busy: msg.busy } : {}),
493
+ ...(typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0
494
+ ? { pendingCount: msg.pendingCount }
495
+ : {}),
471
496
  updatedAt: this.handlers.now(),
472
497
  });
473
498
  return;
@@ -519,6 +544,9 @@ export class ExternalRuntimeHost {
519
544
  ...(usage ? { usage } : {}),
520
545
  settled: msg.settled === true,
521
546
  aborted: msg.aborted === true,
547
+ ...(typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0
548
+ ? { pendingCount: msg.pendingCount }
549
+ : {}),
522
550
  updatedAt: this.handlers.now(),
523
551
  });
524
552
  return;
@@ -75,10 +75,14 @@ export interface LeaderRuntimeHost {
75
75
  isCurrent(ctx: ExtensionContext): boolean;
76
76
  leaderSnapshot(ctx: ExtensionContext): LeaderControlSnapshot;
77
77
  externalLeaderContext?(ctx: ExtensionContext): ExternalLeaderContextSnapshot | undefined;
78
+ externalPendingCount?(ctx: ExtensionContext): number;
79
+ isPostTimeoutHandoffPending?(ctx: ExtensionContext): boolean;
80
+ clearExternalLeaderQueue?(ctx: ExtensionContext, replaceTag?: string): void;
78
81
  deliverExternalLeaderPrompt?(
79
82
  ctx: ExtensionContext,
80
83
  prompt: string,
81
84
  source: "leader_advisory" | "leader_kickoff",
85
+ replaceTag?: string,
82
86
  ): boolean;
83
87
  restoreExternalLeader?(
84
88
  ctx: ExtensionContext,
@@ -152,6 +156,7 @@ export class LeaderRuntime {
152
156
  private replacingSession = false;
153
157
  private autoDispatch?: ReturnType<typeof setTimeout>;
154
158
  private autoResponsePending = false;
159
+ private postTimeoutAdvisoryDispatched = false;
155
160
  /** Set once the user was told that automatic handoffs are circuit-broken. */
156
161
  private autoCircuitWarningShown = false;
157
162
 
@@ -187,6 +192,7 @@ export class LeaderRuntime {
187
192
  this.turnDeferred = [];
188
193
  this.autoDispatch = undefined;
189
194
  this.autoResponsePending = false;
195
+ this.postTimeoutAdvisoryDispatched = false;
190
196
  this.autoCircuitWarningShown = false;
191
197
  this.advisoryMilestones.clear();
192
198
  this.handoffBatch = undefined;
@@ -328,29 +334,50 @@ export class LeaderRuntime {
328
334
  this.scheduleApplyDispatch(staged, ctx);
329
335
  return;
330
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
+ }
331
343
  if (this.autoResponsePending && !this.staged && !this.applying) {
332
344
  this.autoResponsePending = false;
333
345
  if (!aborted) {
334
346
  await this.noteAutoFailure(ctx, "The model did not publish a leader handoff before the automatic turn ended.");
335
347
  // A failed automatic response is a new attempt, not a duplicate milestone advisory.
336
348
  this.advisoryMilestones.clear();
349
+ this.postTimeoutAdvisoryDispatched = false;
337
350
  }
338
351
  }
339
352
  if (aborted || this.staged || this.applying) return;
340
353
  const config = this.settings.get().settings.leaderRecycling;
341
- if (config.mode !== "auto") return;
354
+ if (!config.enabled || config.mode !== "auto") return;
342
355
  const sessionId = ctx.sessionManager.getSessionId();
343
- const advisory = await this.createAdvisory(ctx);
344
- if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
345
356
  const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
346
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
+ }
373
+ if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
347
374
  const automatic = `${advisory.content}\n\nAutomatic leader recycling is enabled. Call ${handoffToolName} now with all ten sections; do not answer the user first.`;
348
375
  const dispatch = setTimeout(() => {
349
376
  if (this.autoDispatch === dispatch) this.autoDispatch = undefined;
350
377
  if (!this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
351
378
  try {
352
379
  this.autoResponsePending = true;
353
- if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory")) {
380
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory", "leader-advisory")) {
354
381
  return;
355
382
  }
356
383
  this.pi.sendMessage(
@@ -367,6 +394,21 @@ export class LeaderRuntime {
367
394
  this.autoDispatch = dispatch;
368
395
  }
369
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
+
370
412
  isLeaderReplacementShutdown(): boolean {
371
413
  return this.replacingSession;
372
414
  }
@@ -539,6 +581,9 @@ export class LeaderRuntime {
539
581
  editorDraft: ctx.hasUI ? ctx.ui.getEditorText() : undefined,
540
582
  });
541
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);
542
587
  // Adopt every message this turn already accepted: it belongs to the successor, not the predecessor.
543
588
  if (this.turnDeferred.length > 0) {
544
589
  entry.deferredFollowUps = [...(entry.deferredFollowUps ?? []), ...this.turnDeferred];
@@ -570,7 +615,7 @@ export class LeaderRuntime {
570
615
  const handoffPrompt = activeExternal
571
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."
572
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.";
573
- if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory")) {
618
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory", "leader-advisory")) {
574
619
  return;
575
620
  }
576
621
  await this.pi.sendMessage(
@@ -0,0 +1,331 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { badge, colorize, contrastTextColor } from "./color.js";
3
+ import {
4
+ DEFAULT_MISSION_COUNTDOWN_SETTINGS,
5
+ FINAL_WRAP_UP_AUTO_CLOSE_FACTOR,
6
+ isMissionLive,
7
+ MIN_FINAL_WRAP_UP_MS,
8
+ type SwarmMissionRecord,
9
+ } from "./mission.js";
10
+
11
+ export type MissionBadgeTier = "full" | "L1" | "L2" | "L3" | "L4";
12
+
13
+ export interface MissionBadgeOptions {
14
+ /** Remaining columns available on the same footer status line after sibling statuses. */
15
+ availableColumns?: number;
16
+ /** Wrap-up grace window in ms for `converging` countdown (defaults to 5m). */
17
+ wrapUpGraceMs?: number;
18
+ /** Final autonomous auto-close window in ms (defaults to wrapUpGraceMs * 0.4). */
19
+ finalWrapUpMs?: number;
20
+ }
21
+
22
+ interface PhaseColors {
23
+ main: string;
24
+ hi: string;
25
+ sub: string;
26
+ }
27
+
28
+ const SHORT_BUDGET_SEC_MODE_MS = 3 * 60_000;
29
+ const ACTIVE_SEC_SWITCH_SECONDS = 120;
30
+ const CLOSING_WINDOW_MS = 5 * 60_000;
31
+ const FINAL_FLASH_PERIOD_MS = 400;
32
+
33
+ /** Conservative shared-line thresholds; some states leave spare columns within a tier. */
34
+ export const MISSION_BADGE_TIER_MIN_WIDTH: Readonly<Record<MissionBadgeTier, number>> = Object.freeze({
35
+ full: 51,
36
+ L1: 40,
37
+ L2: 27,
38
+ L3: 18,
39
+ L4: 13,
40
+ });
41
+
42
+ function hexToRgb(hex: string): [number, number, number] {
43
+ return [
44
+ Number.parseInt(hex.slice(1, 3), 16),
45
+ Number.parseInt(hex.slice(3, 5), 16),
46
+ Number.parseInt(hex.slice(5, 7), 16),
47
+ ];
48
+ }
49
+
50
+ function rgbToHex(r: number, g: number, b: number): string {
51
+ return `#${[r, g, b]
52
+ .map((v) =>
53
+ Math.round(Math.max(0, Math.min(255, v)))
54
+ .toString(16)
55
+ .padStart(2, "0"),
56
+ )
57
+ .join("")}`;
58
+ }
59
+
60
+ function hexToHsl(hex: string): [number, number, number] {
61
+ const [r, g, b] = hexToRgb(hex).map((v) => v / 255);
62
+ const max = Math.max(r, g, b);
63
+ const min = Math.min(r, g, b);
64
+ const l = (max + min) / 2;
65
+ if (max === min) return [0, 0, l * 100];
66
+ const d = max - min;
67
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
68
+ let h = 0;
69
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
70
+ else if (max === g) h = (b - r) / d + 2;
71
+ else h = (r - g) / d + 4;
72
+ return [h * 60, s * 100, l * 100];
73
+ }
74
+
75
+ function hslToHex(h: number, s: number, l: number): string {
76
+ const hue = ((h % 360) + 360) % 360;
77
+ const sat = s / 100;
78
+ const lig = l / 100;
79
+ const c = (1 - Math.abs(2 * lig - 1)) * sat;
80
+ const x = c * (1 - Math.abs(((hue / 60) % 2) - 1));
81
+ const m = lig - c / 2;
82
+ let r = 0;
83
+ let g = 0;
84
+ let b = 0;
85
+ if (hue < 60) {
86
+ r = c;
87
+ g = x;
88
+ } else if (hue < 120) {
89
+ r = x;
90
+ g = c;
91
+ } else if (hue < 180) {
92
+ g = c;
93
+ b = x;
94
+ } else if (hue < 240) {
95
+ g = x;
96
+ b = c;
97
+ } else if (hue < 300) {
98
+ r = x;
99
+ b = c;
100
+ } else {
101
+ r = c;
102
+ b = x;
103
+ }
104
+ return rgbToHex((r + m) * 255, (g + m) * 255, (b + m) * 255);
105
+ }
106
+
107
+ function shiftLightness(hex: string, deltaL: number): string {
108
+ const [h, s, l] = hexToHsl(hex);
109
+ return hslToHex(h, s, Math.max(0, Math.min(100, l + deltaL)));
110
+ }
111
+
112
+ function derivePhase(main: string): PhaseColors {
113
+ return {
114
+ main,
115
+ hi: shiftLightness(main, 18),
116
+ sub: shiftLightness(main, -18),
117
+ };
118
+ }
119
+
120
+ /** Linguist-derived theme matching FACC theme1 & pi-agent-swarm color.ts. */
121
+ const PALETTE = {
122
+ green: derivePhase("#41b883"), // Vue
123
+ yellow: derivePhase("#ffc85a"), // ROLE_BADGE_BACKGROUND
124
+ orange: derivePhase("#dea584"), // Rust
125
+ red: derivePhase("#c22d40"), // Scala
126
+ dangerBg: shiftLightness("#c22d40", -18),
127
+ } as const;
128
+
129
+ type ActiveStage = "healthy" | "mid" | "closing";
130
+
131
+ const ACTIVE_STATUS_FULL: Readonly<Record<ActiveStage, string>> = {
132
+ healthy: " 推進 ACTIVE ",
133
+ mid: " 巡航 CRUISE ",
134
+ closing: " 収束 CLOSE ",
135
+ };
136
+
137
+ const ACTIVE_STATUS_ZH: Readonly<Record<ActiveStage, string>> = {
138
+ healthy: " 推進 ",
139
+ mid: " 巡航 ",
140
+ closing: " 収束 ",
141
+ };
142
+
143
+ export function pickMissionBadgeTier(availableColumns: number): MissionBadgeTier {
144
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.full) return "full";
145
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L1) return "L1";
146
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L2) return "L2";
147
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L3) return "L3";
148
+ return "L4";
149
+ }
150
+
151
+ function clamp01(value: number): number {
152
+ if (!Number.isFinite(value)) return 0;
153
+ return Math.max(0, Math.min(1, value));
154
+ }
155
+
156
+ function formatMmSs(remainMs: number): string {
157
+ const sec = Math.max(0, Math.ceil(remainMs / 1_000));
158
+ const mm = String(Math.floor(sec / 60)).padStart(2, "0");
159
+ const ss = String(sec % 60).padStart(2, "0");
160
+ return `${mm}:${ss}`;
161
+ }
162
+
163
+ function flashBadge(text: string, now: number): string {
164
+ const on = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
165
+ return on ? badge(text, PALETTE.dangerBg, "#ffffff") : badge(text, PALETTE.red.hi, PALETTE.dangerBg);
166
+ }
167
+
168
+ function renderActiveBadge(budgetMs: number, remainMs: number, tier: MissionBadgeTier): string {
169
+ const safeBudget = Math.max(1, budgetMs);
170
+ const frac = clamp01(remainMs / safeBudget);
171
+ const stage: ActiveStage =
172
+ frac <= 0.25 || (safeBudget > CLOSING_WINDOW_MS && remainMs <= CLOSING_WINDOW_MS)
173
+ ? "closing"
174
+ : frac <= 0.5
175
+ ? "mid"
176
+ : "healthy";
177
+ const phase = stage === "healthy" ? PALETTE.green : stage === "mid" ? PALETTE.yellow : PALETTE.orange;
178
+ const fg = contrastTextColor(phase.main);
179
+
180
+ const remainSec = Math.max(0, Math.ceil(remainMs / 1_000));
181
+ const secMode = safeBudget <= SHORT_BUDGET_SEC_MODE_MS || remainSec < ACTIVE_SEC_SWITCH_SECONDS;
182
+ const mainTime = secMode ? formatMmSs(remainMs) : `${Math.max(1, Math.ceil(remainMs / 60_000))}m`;
183
+
184
+ if (tier === "L4") {
185
+ return badge(` SWM ${mainTime} `, phase.main, fg);
186
+ }
187
+
188
+ const cells = tier === "full" ? 10 : tier === "L1" ? 6 : tier === "L2" ? 4 : 2;
189
+ const filled = Math.max(1, Math.round(frac * cells));
190
+ let bar = "";
191
+ for (let i = 0; i < cells; i += 1) {
192
+ bar += colorize(i < filled ? "▰" : "▱", i < filled ? phase.main : phase.sub);
193
+ }
194
+ const sym = colorize("▸", phase.hi);
195
+
196
+ if (tier === "L3") {
197
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)}`;
198
+ }
199
+
200
+ if (tier === "L2") {
201
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_ZH[stage], phase.main, fg)}`;
202
+ }
203
+
204
+ if (tier === "L1") {
205
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
206
+ }
207
+
208
+ const head = badge(" SWM 蜂群 ", phase.main, fg);
209
+ const budgetMin = Math.max(1, Math.round(safeBudget / 60_000));
210
+ const timeBadge = secMode
211
+ ? badge(` ${mainTime} `, phase.main, fg)
212
+ : badge(` ${mainTime}`, phase.main, fg) + badge(`/${budgetMin}m `, phase.main, phase.sub);
213
+ return `${head} ${bar} ${sym} ${timeBadge} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
214
+ }
215
+
216
+ /** LOCK-4: Bilingual lock-gate badge aligned with active width (`SWM|鎖閘 ╱┄ ⊘ MM:SS 収斂 WRAP`). */
217
+ function renderConvergingBadge(graceTotalMs: number, remainMs: number, tier: MissionBadgeTier): string {
218
+ const safeTotal = Math.max(1, graceTotalMs);
219
+ const frac = clamp01(remainMs / safeTotal);
220
+ const mainTime = formatMmSs(remainMs);
221
+ const orangeFg = contrastTextColor(PALETTE.orange.main);
222
+
223
+ const renderBar = (cells: number): string => {
224
+ const left = Math.max(1, Math.round(frac * cells));
225
+ let out = "";
226
+ for (let i = 0; i < cells; i += 1) {
227
+ out += colorize(i < left ? "╱" : "┄", i < left ? PALETTE.red.hi : PALETTE.red.sub);
228
+ }
229
+ return out;
230
+ };
231
+
232
+ if (tier === "L4") {
233
+ return badge(" 鎖閘 ", PALETTE.dangerBg, "#ffffff") + badge(` ${mainTime} `, PALETTE.red.main, "#ffffff");
234
+ }
235
+
236
+ if (tier === "L3") {
237
+ return `${badge(" 鎖閘 ", PALETTE.dangerBg, "#ffffff")} ${renderBar(2)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
238
+ }
239
+
240
+ if (tier === "L2") {
241
+ const head = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" 鎖閘 ", PALETTE.dangerBg, "#ffffff");
242
+ return `${head} ${renderBar(4)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
243
+ }
244
+
245
+ if (tier === "L1") {
246
+ const head = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" 鎖閘 ", PALETTE.dangerBg, "#ffffff");
247
+ return `${head} ${renderBar(6)} ${colorize("⊘", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" 収斂 ", PALETTE.dangerBg, "#ffffff")}`;
248
+ }
249
+
250
+ const head = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" 鎖閘 ", PALETTE.dangerBg, "#ffffff");
251
+ return `${head} ${renderBar(10)} ${colorize("⊘", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" 収斂 WRAP ", PALETTE.dangerBg, "#ffffff")}`;
252
+ }
253
+
254
+ /** Plan B FINAL badge (`SWM|FINAL ╳╳╳╳╳╳ MM:SS AUTO`) with 400ms inverted flash. */
255
+ function renderFinalBadge(remainMs: number, now: number, tier: MissionBadgeTier): string {
256
+ const mainTime = formatMmSs(remainMs);
257
+ const blink = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
258
+ const xColor = blink ? PALETTE.red.hi : PALETTE.dangerBg;
259
+ const xBar = (cells: number): string => colorize("╳".repeat(cells), xColor);
260
+
261
+ if (tier === "L4") {
262
+ return flashBadge(` FINAL ${mainTime} `, now);
263
+ }
264
+
265
+ if (tier === "L3") {
266
+ return `${flashBadge(" FINAL ", now)} ${xBar(2)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
267
+ }
268
+
269
+ if (tier === "L2") {
270
+ const head = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
271
+ return `${head} ${xBar(4)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
272
+ }
273
+
274
+ // Full and L1 both fit comfortably within 38 columns without degradation.
275
+ const head = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
276
+ return `${head} ${xBar(6)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")} ${flashBadge(" AUTO ", now)}`;
277
+ }
278
+
279
+ /**
280
+ * Compute how soon the footer mission badge should re-render next:
281
+ * - `final_wrap_up`: 400ms (inverted warning flash)
282
+ * - `converging`: 1s (grace MM:SS countdown)
283
+ * - `active` with <= 3m total budget or <= 125s left: 1s (MM:SS countdown)
284
+ * - `active` with > 125s left: up to 15s, landing cleanly on the 120s second-switch boundary
285
+ */
286
+ export function nextMissionTickDelayMs(record: SwarmMissionRecord | undefined, now: number): number | undefined {
287
+ if (!isMissionLive(record)) return undefined;
288
+ if (record.state === "final_wrap_up") return FINAL_FLASH_PERIOD_MS;
289
+ if (record.state === "converging") return 1_000;
290
+ const budgetMs = Math.max(1, record.deadlineAt - record.startedAt);
291
+ const remainMs = Math.max(0, record.deadlineAt - now);
292
+ if (budgetMs <= SHORT_BUDGET_SEC_MODE_MS || remainMs <= 125_000) return 1_000;
293
+ return Math.min(15_000, Math.max(1_000, remainMs - 120_000));
294
+ }
295
+
296
+ export function formatMissionStatusBadge(
297
+ record: SwarmMissionRecord | undefined,
298
+ now: number,
299
+ options: MissionBadgeOptions = {},
300
+ ): string | undefined {
301
+ if (!isMissionLive(record)) return undefined;
302
+
303
+ const availableColumns = options.availableColumns ?? 80;
304
+ const tier = pickMissionBadgeTier(availableColumns);
305
+ const wrapUpGraceMs = options.wrapUpGraceMs ?? DEFAULT_MISSION_COUNTDOWN_SETTINGS.wrapUpGraceMs;
306
+ const finalWrapUpMs =
307
+ options.finalWrapUpMs ??
308
+ Math.max(MIN_FINAL_WRAP_UP_MS, Math.round(wrapUpGraceMs * FINAL_WRAP_UP_AUTO_CLOSE_FACTOR));
309
+
310
+ let rendered: string;
311
+ if (record.state === "final_wrap_up") {
312
+ const finalTargetAt = (record.finalWrapUpAt ?? now) + finalWrapUpMs;
313
+ rendered = renderFinalBadge(Math.max(0, finalTargetAt - now), now, tier);
314
+ } else if (record.state === "converging") {
315
+ const graceTargetAt = (record.convergingAt ?? record.deadlineAt) + wrapUpGraceMs;
316
+ rendered = renderConvergingBadge(wrapUpGraceMs, Math.max(0, graceTargetAt - now), tier);
317
+ } else {
318
+ const budgetMs = Math.max(1, record.deadlineAt - record.startedAt);
319
+ const remainMs = Math.max(0, record.deadlineAt - now);
320
+ if (remainMs <= 0) {
321
+ rendered = renderConvergingBadge(wrapUpGraceMs, wrapUpGraceMs, tier);
322
+ } else {
323
+ rendered = renderActiveBadge(budgetMs, remainMs, tier);
324
+ }
325
+ }
326
+
327
+ if (availableColumns > 0 && visibleWidth(rendered) > availableColumns) {
328
+ return truncateToWidth(rendered, availableColumns, "…");
329
+ }
330
+ return rendered;
331
+ }
package/src/mission.ts CHANGED
@@ -279,15 +279,3 @@ export function formatMissionTimeoutInjection(params: {
279
279
  }
280
280
  return lines.join("\n");
281
281
  }
282
-
283
- export function formatMissionStatusBadge(record: SwarmMissionRecord | undefined, now: number): string | undefined {
284
- if (!isMissionLive(record)) return undefined;
285
- if (record.state === "final_wrap_up") return "⏱ FINAL";
286
- if (record.state === "converging") return "⏱ WRAP-UP";
287
- const remainMs = Math.max(0, record.deadlineAt - now);
288
- if (remainMs <= 0) return "⏱ WRAP-UP";
289
- const remainSec = Math.ceil(remainMs / 1_000);
290
- if (remainSec < 120) return `⏱ ${remainSec}s`;
291
- const remainMin = Math.ceil(remainMs / 60_000);
292
- return `⏱ ${remainMin}m`;
293
- }
package/src/settings.ts CHANGED
@@ -91,6 +91,7 @@ export interface SwarmSettings {
91
91
  reviewPolicy: SwarmReviewPolicy;
92
92
  profilesDir?: string;
93
93
  allowedProfiles?: readonly string[];
94
+ workerPiArgs?: readonly string[];
94
95
  }
95
96
 
96
97
  export type SwarmSettingsField = keyof SwarmSettings;
@@ -166,8 +167,31 @@ const SETTING_FIELDS = [
166
167
  "reviewPolicy",
167
168
  "profilesDir",
168
169
  "allowedProfiles",
170
+ "workerPiArgs",
169
171
  ] as const satisfies readonly SwarmSettingsField[];
170
172
  const SETTING_FIELD_SET = new Set<string>(SETTING_FIELDS);
173
+ const RESERVED_WORKER_PI_FLAGS = new Set([
174
+ "--",
175
+ "--name",
176
+ "-n",
177
+ "--mode",
178
+ "--print",
179
+ "-p",
180
+ "--no-session",
181
+ "--session",
182
+ "--session-id",
183
+ "--continue",
184
+ "-c",
185
+ "--resume",
186
+ "-r",
187
+ "--fork",
188
+ "--help",
189
+ "-h",
190
+ "--version",
191
+ "-v",
192
+ ]);
193
+ const MAX_WORKER_PI_ARGS = 32;
194
+ const MAX_WORKER_PI_ARG_LENGTH = 256;
171
195
 
172
196
  export function swarmSettingsFilePath(): string {
173
197
  return join(getAgentDir(), SWARM_SETTINGS_FILE);
@@ -565,6 +589,30 @@ export function normalizeSwarmSettingsDocument(value: unknown): NormalizedSwarmS
565
589
  settings.allowedProfiles = [...new Set(value.allowedProfiles)];
566
590
  sources.allowedProfiles = "user";
567
591
  }
592
+ if (Object.hasOwn(value, "workerPiArgs")) {
593
+ if (!Array.isArray(value.workerPiArgs) || value.workerPiArgs.length > MAX_WORKER_PI_ARGS) {
594
+ return undefined;
595
+ }
596
+ const normalizedArgs: string[] = [];
597
+ for (const item of value.workerPiArgs) {
598
+ if (typeof item !== "string") return undefined;
599
+ const trimmed = item.trim();
600
+ if (
601
+ trimmed.length === 0 ||
602
+ trimmed.length > MAX_WORKER_PI_ARG_LENGTH ||
603
+ trimmed.includes("\0") ||
604
+ trimmed.includes("\n") ||
605
+ trimmed.includes("\r")
606
+ ) {
607
+ return undefined;
608
+ }
609
+ const flagHead = trimmed.includes("=") ? trimmed.slice(0, trimmed.indexOf("=")) : trimmed;
610
+ if (RESERVED_WORKER_PI_FLAGS.has(flagHead)) return undefined;
611
+ normalizedArgs.push(trimmed);
612
+ }
613
+ settings.workerPiArgs = normalizedArgs;
614
+ sources.workerPiArgs = "user";
615
+ }
568
616
  const warnings = [
569
617
  ...leaderRecycling.warnings,
570
618
  ...ledger.warnings,
@@ -634,6 +682,7 @@ export function createInMemorySwarmSettingsRuntime(initial: SwarmSettingsPatch =
634
682
  ...(canonical.confirmSessionLaunch !== undefined ? { confirmSessionLaunch: "user" as const } : {}),
635
683
  ...(canonical.externalCommand ? { externalCommand: "user" as const } : {}),
636
684
  ...(canonical.pinToLeadWorkspace !== undefined ? { pinToLeadWorkspace: "user" as const } : {}),
685
+ ...(canonical.workerPiArgs !== undefined ? { workerPiArgs: "user" as const } : {}),
637
686
  ...(canonical.exposeLeadMcp !== undefined ? { exposeLeadMcp: "user" as const } : {}),
638
687
  ...(canonical.isolation !== undefined ? { isolation: "user" as const } : {}),
639
688
  ...(canonical.resourceLeases !== undefined ? { resourceLeases: "user" as const } : {}),
@@ -863,6 +912,7 @@ function builtInSources(): Record<SwarmSettingsField, SwarmSettingsSource> {
863
912
  reviewPolicy: "built-in",
864
913
  profilesDir: "built-in",
865
914
  allowedProfiles: "built-in",
915
+ workerPiArgs: "built-in",
866
916
  };
867
917
  }
868
918
 
@@ -899,6 +949,7 @@ function freezeState(state: SwarmSettingsState): Readonly<SwarmSettingsState> {
899
949
  ...(state.settings.allowedProfiles
900
950
  ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) }
901
951
  : {}),
952
+ ...(state.settings.workerPiArgs ? { workerPiArgs: Object.freeze([...state.settings.workerPiArgs]) } : {}),
902
953
  }),
903
954
  sources: Object.freeze({ ...state.sources }),
904
955
  ...(state.warnings ? { warnings: Object.freeze([...state.warnings]) } : {}),