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.
package/dist/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  badge,
5
+ colorize,
5
6
  contrastTextColor,
6
7
  normalizeOptionalText,
7
8
  normalizeSwarmColor,
@@ -11,7 +12,7 @@ import {
11
12
  safeTerminalText,
12
13
  swarmColorName,
13
14
  swarmColorPalette
14
- } from "./chunks/chunk-77JHO3GV.ts";
15
+ } from "./chunks/chunk-CV4VP4UE.ts";
15
16
 
16
17
  // src/protocol.ts
17
18
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -644,8 +645,8 @@ var renderSwarmMessage = (message, options, theme) => {
644
645
  // src/settings.ts
645
646
  import { randomUUID } from "node:crypto";
646
647
  import { constants } from "node:fs";
647
- import { lstat as lstat2, mkdir as mkdir3, open as open2, rename as rename3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
648
- import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
648
+ import { lstat as lstat2, mkdir as mkdir3, open as open2, rename as rename3, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
649
+ import { basename as basename2, dirname as dirname2, join as join4 } from "node:path";
649
650
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
650
651
 
651
652
  // src/auto-name.ts
@@ -1477,8 +1478,8 @@ async function atomicText(path2, content) {
1477
1478
  try {
1478
1479
  await rename(temporary, path2);
1479
1480
  } catch (error) {
1480
- const { rm: rm11 } = await import("node:fs/promises");
1481
- await rm11(temporary, { force: true }).catch(() => void 0);
1481
+ const { rm: rm12 } = await import("node:fs/promises");
1482
+ await rm12(temporary, { force: true }).catch(() => void 0);
1482
1483
  throw error;
1483
1484
  }
1484
1485
  }
@@ -1681,6 +1682,158 @@ function isMissing(error) {
1681
1682
  return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
1682
1683
  }
1683
1684
 
1685
+ // src/mission.ts
1686
+ import { readFile as readFile3, rm as rm3 } from "node:fs/promises";
1687
+ import { join as join3, resolve as resolve3 } from "node:path";
1688
+ var DEFAULT_MISSION_COUNTDOWN_SETTINGS = Object.freeze({
1689
+ enabled: true,
1690
+ requireBeforeSpawn: false,
1691
+ minMinutes: 2,
1692
+ maxMinutes: 90,
1693
+ wrapUpGraceMs: 5 * 6e4
1694
+ });
1695
+ var FINAL_WRAP_UP_AUTO_CLOSE_FACTOR = 0.4;
1696
+ var MIN_FINAL_WRAP_UP_MS = 100;
1697
+ function missionPaths(projectRoot) {
1698
+ const root = resolve3(projectRoot);
1699
+ const storageRoot = resolve3(root, WORKER_RECYCLING_DIRECTORY);
1700
+ const missionsDirectory = join3(storageRoot, "missions");
1701
+ return {
1702
+ root: storageRoot,
1703
+ missionsDirectory,
1704
+ activePath: join3(missionsDirectory, "active.json"),
1705
+ historyDirectory: join3(missionsDirectory, "history")
1706
+ };
1707
+ }
1708
+ function isMissionLive(record3) {
1709
+ return record3 !== void 0 && (record3.state === "active" || record3.state === "converging" || record3.state === "final_wrap_up");
1710
+ }
1711
+ function isMissionConverging(record3) {
1712
+ return record3 !== void 0 && (record3.state === "converging" || record3.state === "final_wrap_up");
1713
+ }
1714
+ function validateMissionStartInput(input, settings) {
1715
+ const firstPrinciples = typeof input.firstPrinciples === "string" ? input.firstPrinciples.trim() : "";
1716
+ if (firstPrinciples.length === 0 || firstPrinciples.length > 4096) {
1717
+ throw new Error("Mission firstPrinciples must be a non-empty string (max 4096 chars).");
1718
+ }
1719
+ const acceptanceCriteria = typeof input.acceptanceCriteria === "string" ? input.acceptanceCriteria.trim() : "";
1720
+ if (acceptanceCriteria.length === 0 || acceptanceCriteria.length > 4096) {
1721
+ throw new Error("Mission acceptanceCriteria must be a non-empty string (max 4096 chars).");
1722
+ }
1723
+ const constraints = typeof input.constraints === "string" && input.constraints.trim().length > 0 ? input.constraints.trim().slice(0, 4096) : void 0;
1724
+ const combined = `${firstPrinciples}
1725
+ ${acceptanceCriteria}
1726
+ ${constraints ?? ""}`;
1727
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(combined))) {
1728
+ throw new Error("Mission definition must not contain swarm invite tokens or secret credentials.");
1729
+ }
1730
+ const requestedMinutes = input.estimatedMinutes;
1731
+ if (typeof requestedMinutes !== "number" || !Number.isFinite(requestedMinutes) || requestedMinutes <= 0) {
1732
+ throw new Error("Mission estimatedMinutes must be a positive finite number.");
1733
+ }
1734
+ const min = Math.max(1e-3, settings.minMinutes);
1735
+ const max = Math.max(min, settings.maxMinutes);
1736
+ const estimatedMinutes = Math.min(max, Math.max(min, requestedMinutes));
1737
+ return {
1738
+ firstPrinciples,
1739
+ acceptanceCriteria,
1740
+ ...constraints ? { constraints } : {},
1741
+ requestedMinutes,
1742
+ estimatedMinutes,
1743
+ clamped: estimatedMinutes !== requestedMinutes
1744
+ };
1745
+ }
1746
+ function validateMissionCompleteInput(input) {
1747
+ const summary = typeof input.summary === "string" ? input.summary.trim() : "";
1748
+ if (summary.length === 0 || summary.length > 8192) {
1749
+ throw new Error("Mission complete requires a non-empty summary (max 8192 chars).");
1750
+ }
1751
+ const residuals = Array.isArray(input.residuals) ? input.residuals.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim().slice(0, 1024)).slice(0, 32) : [];
1752
+ const outcome = input.outcome === "with_residuals" || residuals.length > 0 ? "with_residuals" : "achieved";
1753
+ return { summary, outcome, residuals };
1754
+ }
1755
+ async function readActiveMission(projectRoot) {
1756
+ const paths = missionPaths(projectRoot);
1757
+ try {
1758
+ const raw = await readFile3(paths.activePath, "utf8");
1759
+ const parsed = JSON.parse(raw);
1760
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
1761
+ const rec = parsed;
1762
+ if (rec.schemaVersion !== 1 || typeof rec.missionId !== "string" || typeof rec.leaderSessionId !== "string" || typeof rec.firstPrinciples !== "string" || typeof rec.acceptanceCriteria !== "string" || typeof rec.deadlineAt !== "number" || typeof rec.startedAt !== "number" || typeof rec.state !== "string") {
1763
+ return void 0;
1764
+ }
1765
+ return parsed;
1766
+ } catch {
1767
+ return void 0;
1768
+ }
1769
+ }
1770
+ async function writeActiveMission(projectRoot, record3) {
1771
+ const paths = missionPaths(projectRoot);
1772
+ await ensureStorageRoot(paths);
1773
+ await atomicJson(paths.activePath, record3);
1774
+ }
1775
+ async function archiveMission(projectRoot, record3) {
1776
+ const paths = missionPaths(projectRoot);
1777
+ await ensureStorageRoot(paths);
1778
+ const safeId2 = record3.missionId.replace(/[^A-Za-z0-9_-]/gu, "_");
1779
+ const historyPath = join3(paths.historyDirectory, `${safeId2}.json`);
1780
+ await atomicJson(historyPath, record3);
1781
+ await rm3(paths.activePath, { force: true }).catch(() => void 0);
1782
+ return historyPath;
1783
+ }
1784
+ function checkMissionSpawnGate(params) {
1785
+ if (!params.settings.enabled) return { allowed: true };
1786
+ const live = isMissionLive(params.mission) ? params.mission : void 0;
1787
+ if (!live) {
1788
+ if (!params.settings.requireBeforeSpawn) return { allowed: true };
1789
+ return {
1790
+ allowed: false,
1791
+ reason: `Mission countdown gate: before spawning workers, you must first establish this round's first-principles goal and time estimate via ${params.busToolName}(action="mission", missionAction="start", firstPrinciples="...", acceptanceCriteria="...", estimatedMinutes=<number>).`
1792
+ };
1793
+ }
1794
+ if (live.state === "converging" || live.state === "final_wrap_up") {
1795
+ if (params.role === "reviewer") {
1796
+ return { allowed: true };
1797
+ }
1798
+ return {
1799
+ allowed: false,
1800
+ reason: `Mission "${live.missionId}" has timed out and is in wrap-up convergence mode (${live.state}). Do NOT spawn new ${params.role} workers or expand scope. Wrap up current results (residuals/open contradictions are explicitly acceptable) and call ${params.busToolName}(action="mission", missionAction="complete", summary="...", outcome="with_residuals", residuals=[...]).`
1801
+ };
1802
+ }
1803
+ return { allowed: true };
1804
+ }
1805
+ function formatMissionTimeoutInjection(params) {
1806
+ const { mission, stage, now, inFlightWorkerCount, busToolName } = params;
1807
+ const elapsedMin = Math.max(0, (now - mission.startedAt) / 6e4).toFixed(1);
1808
+ const header = stage === "final_wrap_up" ? `[MISSION FINAL WRAP-UP \u2014 COMPLETE IMMEDIATELY] Mission "${mission.missionId}" exceeded both its time estimate and wrap-up grace period.` : `[MISSION COUNTDOWN EXPIRED \u2014 CONVERGE TO COMPLETE] Mission "${mission.missionId}" reached its estimated time budget (${mission.estimatedMinutes}m; elapsed ${elapsedMin}m).`;
1809
+ const lines = [
1810
+ header,
1811
+ "",
1812
+ "### First-Principles Requirement (Re-Anchor)",
1813
+ mission.firstPrinciples,
1814
+ "",
1815
+ "### Acceptance Criteria",
1816
+ mission.acceptanceCriteria,
1817
+ ...mission.constraints ? ["", "### Hard Constraints", mission.constraints] : [],
1818
+ "",
1819
+ `### Current Runtime State`,
1820
+ `- Mission state: ${stage} (elapsed ${elapsedMin}m / budget ${mission.estimatedMinutes}m)`,
1821
+ `- In-flight workers awaiting reply: ${inFlightWorkerCount}`,
1822
+ "",
1823
+ "### Required Action (Converge \u2014 Only Two Outcomes)",
1824
+ `1. Complete now if the first-principles objective is met: call ${busToolName}(action="mission", missionAction="complete", summary="...", outcome="achieved").`,
1825
+ `2. Otherwise converge and complete ASAP with honest residuals: you do NOT need to solve every edge case or contradiction \u2014 completing cleanly with documented residuals/contradictions is strictly preferred over endless iteration. Spawning new implementers/researchers/fanout is now locked (you may still message/shutdown active workers or run a quick read-only reviewer).`,
1826
+ ` Call ${busToolName}(action="mission", missionAction="complete", summary="...", outcome="with_residuals", residuals=["..."]).`
1827
+ ];
1828
+ if (stage === "final_wrap_up") {
1829
+ lines.push(
1830
+ "",
1831
+ "This is the final autonomous convergence notice. If you do not call mission complete shortly, the host will automatically archive this mission as auto_completed (with_residuals) so the next round can start cleanly."
1832
+ );
1833
+ }
1834
+ return lines.join("\n");
1835
+ }
1836
+
1684
1837
  // src/settings.ts
1685
1838
  var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
1686
1839
  var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
@@ -1692,6 +1845,12 @@ var DEFAULT_LEADER_RECYCLING_SETTINGS = Object.freeze({
1692
1845
  highWaterPercent: 75,
1693
1846
  maxReplacements: 3
1694
1847
  });
1848
+ var DEFAULT_CACHE_WARMING_SETTINGS = Object.freeze({
1849
+ enabled: true,
1850
+ maxWaitDurationMs: 30 * 6e4,
1851
+ maxRefreshesPerWait: 8
1852
+ });
1853
+ var DEFAULT_REVIEW_POLICY = "suggest";
1695
1854
  var DEFAULT_SWARM_SETTINGS = Object.freeze({
1696
1855
  autoName: true,
1697
1856
  colorPalette: "muted",
@@ -1703,7 +1862,10 @@ var DEFAULT_SWARM_SETTINGS = Object.freeze({
1703
1862
  resourceLeases: true,
1704
1863
  leaderRecycling: DEFAULT_LEADER_RECYCLING_SETTINGS,
1705
1864
  ledger: DEFAULT_LEDGER_SETTINGS,
1706
- budget: DEFAULT_SWARM_BUDGET_SETTINGS
1865
+ budget: DEFAULT_SWARM_BUDGET_SETTINGS,
1866
+ cacheWarming: DEFAULT_CACHE_WARMING_SETTINGS,
1867
+ missionCountdown: DEFAULT_MISSION_COUNTDOWN_SETTINGS,
1868
+ reviewPolicy: DEFAULT_REVIEW_POLICY
1707
1869
  });
1708
1870
  var SETTING_FIELDS = [
1709
1871
  "autoName",
@@ -1718,12 +1880,38 @@ var SETTING_FIELDS = [
1718
1880
  "leaderRecycling",
1719
1881
  "ledger",
1720
1882
  "budget",
1883
+ "cacheWarming",
1884
+ "missionCountdown",
1885
+ "reviewPolicy",
1721
1886
  "profilesDir",
1722
- "allowedProfiles"
1887
+ "allowedProfiles",
1888
+ "workerPiArgs"
1723
1889
  ];
1724
1890
  var SETTING_FIELD_SET = new Set(SETTING_FIELDS);
1891
+ var RESERVED_WORKER_PI_FLAGS = /* @__PURE__ */ new Set([
1892
+ "--",
1893
+ "--name",
1894
+ "-n",
1895
+ "--mode",
1896
+ "--print",
1897
+ "-p",
1898
+ "--no-session",
1899
+ "--session",
1900
+ "--session-id",
1901
+ "--continue",
1902
+ "-c",
1903
+ "--resume",
1904
+ "-r",
1905
+ "--fork",
1906
+ "--help",
1907
+ "-h",
1908
+ "--version",
1909
+ "-v"
1910
+ ]);
1911
+ var MAX_WORKER_PI_ARGS = 32;
1912
+ var MAX_WORKER_PI_ARG_LENGTH = 256;
1725
1913
  function swarmSettingsFilePath() {
1726
- return join3(getAgentDir(), SWARM_SETTINGS_FILE);
1914
+ return join4(getAgentDir(), SWARM_SETTINGS_FILE);
1727
1915
  }
1728
1916
  function normalizeLeaderRecycling(value) {
1729
1917
  if (value === void 0) return { settings: { ...DEFAULT_LEADER_RECYCLING_SETTINGS }, warnings: [] };
@@ -1744,6 +1932,14 @@ function normalizeLeaderRecycling(value) {
1744
1932
  return DEFAULT_LEADER_RECYCLING_SETTINGS[field];
1745
1933
  };
1746
1934
  const integer = (minimum, maximum) => (candidate) => typeof candidate === "number" && Number.isInteger(candidate) && candidate >= minimum && candidate <= maximum;
1935
+ let highWaterTokens;
1936
+ if (value.highWaterTokens !== void 0) {
1937
+ if (integer(1, 1e7)(value.highWaterTokens)) {
1938
+ highWaterTokens = value.highWaterTokens;
1939
+ } else {
1940
+ warnings.push("leaderRecycling.highWaterTokens must be an integer from 1 to 10000000; ignoring invalid value.");
1941
+ }
1942
+ }
1747
1943
  return {
1748
1944
  settings: {
1749
1945
  enabled: read(
@@ -1759,11 +1955,103 @@ function normalizeLeaderRecycling(value) {
1759
1955
  softContextPercent: read("softContextPercent", integer(1, 100), "must be an integer from 1 to 100"),
1760
1956
  softContextTokens: read("softContextTokens", integer(1, 1e7), "must be an integer from 1 to 10000000"),
1761
1957
  highWaterPercent: read("highWaterPercent", integer(1, 100), "must be an integer from 1 to 100"),
1958
+ ...highWaterTokens !== void 0 ? { highWaterTokens } : {},
1762
1959
  maxReplacements: read("maxReplacements", integer(0, 10), "must be an integer from 0 to 10")
1763
1960
  },
1764
1961
  warnings
1765
1962
  };
1766
1963
  }
1964
+ function normalizeCacheWarmingSettings(value) {
1965
+ if (value === void 0) return { settings: { ...DEFAULT_CACHE_WARMING_SETTINGS }, warnings: [] };
1966
+ if (!isRecord3(value)) {
1967
+ return {
1968
+ settings: { ...DEFAULT_CACHE_WARMING_SETTINGS },
1969
+ warnings: ["cacheWarming must be an object; using all cacheWarming defaults."]
1970
+ };
1971
+ }
1972
+ const warnings = [];
1973
+ let enabled = DEFAULT_CACHE_WARMING_SETTINGS.enabled;
1974
+ if (value.enabled !== void 0) {
1975
+ if (typeof value.enabled === "boolean") enabled = value.enabled;
1976
+ else warnings.push(`cacheWarming.enabled must be a boolean; using ${String(enabled)}.`);
1977
+ }
1978
+ let maxWaitDurationMs = DEFAULT_CACHE_WARMING_SETTINGS.maxWaitDurationMs;
1979
+ if (value.maxWaitDurationMs !== void 0) {
1980
+ if (typeof value.maxWaitDurationMs === "number" && Number.isInteger(value.maxWaitDurationMs) && value.maxWaitDurationMs >= 6e4 && value.maxWaitDurationMs <= 36e5) {
1981
+ maxWaitDurationMs = value.maxWaitDurationMs;
1982
+ } else {
1983
+ warnings.push(
1984
+ `cacheWarming.maxWaitDurationMs must be an integer from 60000 to 3600000; using ${String(maxWaitDurationMs)}.`
1985
+ );
1986
+ }
1987
+ }
1988
+ let maxRefreshesPerWait = DEFAULT_CACHE_WARMING_SETTINGS.maxRefreshesPerWait;
1989
+ if (value.maxRefreshesPerWait !== void 0) {
1990
+ if (typeof value.maxRefreshesPerWait === "number" && Number.isInteger(value.maxRefreshesPerWait) && value.maxRefreshesPerWait >= 1 && value.maxRefreshesPerWait <= 30) {
1991
+ maxRefreshesPerWait = value.maxRefreshesPerWait;
1992
+ } else {
1993
+ warnings.push(
1994
+ `cacheWarming.maxRefreshesPerWait must be an integer from 1 to 30; using ${String(maxRefreshesPerWait)}.`
1995
+ );
1996
+ }
1997
+ }
1998
+ return { settings: { enabled, maxWaitDurationMs, maxRefreshesPerWait }, warnings };
1999
+ }
2000
+ function normalizeMissionCountdownSettings(value) {
2001
+ if (value === void 0) return { settings: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS }, warnings: [] };
2002
+ if (!isRecord3(value)) {
2003
+ return {
2004
+ settings: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS },
2005
+ warnings: ["missionCountdown must be an object; using all missionCountdown defaults."]
2006
+ };
2007
+ }
2008
+ const warnings = [];
2009
+ let enabled = DEFAULT_MISSION_COUNTDOWN_SETTINGS.enabled;
2010
+ if (value.enabled !== void 0) {
2011
+ if (typeof value.enabled === "boolean") enabled = value.enabled;
2012
+ else warnings.push(`missionCountdown.enabled must be a boolean; using ${String(enabled)}.`);
2013
+ }
2014
+ let requireBeforeSpawn = DEFAULT_MISSION_COUNTDOWN_SETTINGS.requireBeforeSpawn;
2015
+ if (value.requireBeforeSpawn !== void 0) {
2016
+ if (typeof value.requireBeforeSpawn === "boolean") requireBeforeSpawn = value.requireBeforeSpawn;
2017
+ else {
2018
+ warnings.push(`missionCountdown.requireBeforeSpawn must be a boolean; using ${String(requireBeforeSpawn)}.`);
2019
+ }
2020
+ }
2021
+ let minMinutes = DEFAULT_MISSION_COUNTDOWN_SETTINGS.minMinutes;
2022
+ if (value.minMinutes !== void 0) {
2023
+ if (typeof value.minMinutes === "number" && Number.isFinite(value.minMinutes) && value.minMinutes > 0 && value.minMinutes <= 60) {
2024
+ minMinutes = value.minMinutes;
2025
+ } else {
2026
+ warnings.push(`missionCountdown.minMinutes must be a positive number <= 60; using ${String(minMinutes)}.`);
2027
+ }
2028
+ }
2029
+ let maxMinutes = DEFAULT_MISSION_COUNTDOWN_SETTINGS.maxMinutes;
2030
+ if (value.maxMinutes !== void 0) {
2031
+ if (typeof value.maxMinutes === "number" && Number.isFinite(value.maxMinutes) && value.maxMinutes >= minMinutes && value.maxMinutes <= 480) {
2032
+ maxMinutes = value.maxMinutes;
2033
+ } else {
2034
+ warnings.push(
2035
+ `missionCountdown.maxMinutes must be a number from ${String(minMinutes)} to 480; using ${String(maxMinutes)}.`
2036
+ );
2037
+ }
2038
+ }
2039
+ if (maxMinutes < minMinutes) maxMinutes = minMinutes;
2040
+ let wrapUpGraceMs = DEFAULT_MISSION_COUNTDOWN_SETTINGS.wrapUpGraceMs;
2041
+ if (value.wrapUpGraceMs !== void 0) {
2042
+ if (typeof value.wrapUpGraceMs === "number" && Number.isInteger(value.wrapUpGraceMs) && value.wrapUpGraceMs >= 100 && value.wrapUpGraceMs <= 36e5) {
2043
+ wrapUpGraceMs = value.wrapUpGraceMs;
2044
+ } else {
2045
+ warnings.push(
2046
+ `missionCountdown.wrapUpGraceMs must be an integer from 100 to 3600000; using ${String(wrapUpGraceMs)}.`
2047
+ );
2048
+ }
2049
+ }
2050
+ return {
2051
+ settings: { enabled, requireBeforeSpawn, minMinutes, maxMinutes, wrapUpGraceMs },
2052
+ warnings
2053
+ };
2054
+ }
1767
2055
  function normalizeLedgerSettings(value) {
1768
2056
  if (value === void 0) return { settings: { ...DEFAULT_LEDGER_SETTINGS }, warnings: [] };
1769
2057
  if (!isRecord3(value)) {
@@ -1927,6 +2215,19 @@ function normalizeSwarmSettingsDocument(value) {
1927
2215
  const budget = normalizeBudgetSettings(value.budget);
1928
2216
  settings.budget = budget.settings;
1929
2217
  if (Object.hasOwn(value, "budget")) sources.budget = "user";
2218
+ const cacheWarming = normalizeCacheWarmingSettings(value.cacheWarming);
2219
+ settings.cacheWarming = cacheWarming.settings;
2220
+ if (Object.hasOwn(value, "cacheWarming")) sources.cacheWarming = "user";
2221
+ const missionCountdown = normalizeMissionCountdownSettings(value.missionCountdown);
2222
+ settings.missionCountdown = missionCountdown.settings;
2223
+ if (Object.hasOwn(value, "missionCountdown")) sources.missionCountdown = "user";
2224
+ if (Object.hasOwn(value, "reviewPolicy")) {
2225
+ if (value.reviewPolicy !== "off" && value.reviewPolicy !== "suggest" && value.reviewPolicy !== "required") {
2226
+ return void 0;
2227
+ }
2228
+ settings.reviewPolicy = value.reviewPolicy;
2229
+ sources.reviewPolicy = "user";
2230
+ }
1930
2231
  if (Object.hasOwn(value, "profilesDir")) {
1931
2232
  if (typeof value.profilesDir !== "string" || value.profilesDir.trim().length === 0 || value.profilesDir.includes("\0")) {
1932
2233
  return void 0;
@@ -1941,7 +2242,31 @@ function normalizeSwarmSettingsDocument(value) {
1941
2242
  settings.allowedProfiles = [...new Set(value.allowedProfiles)];
1942
2243
  sources.allowedProfiles = "user";
1943
2244
  }
1944
- const warnings = [...leaderRecycling.warnings, ...ledger.warnings, ...budget.warnings];
2245
+ if (Object.hasOwn(value, "workerPiArgs")) {
2246
+ if (!Array.isArray(value.workerPiArgs) || value.workerPiArgs.length > MAX_WORKER_PI_ARGS) {
2247
+ return void 0;
2248
+ }
2249
+ const normalizedArgs = [];
2250
+ for (const item of value.workerPiArgs) {
2251
+ if (typeof item !== "string") return void 0;
2252
+ const trimmed = item.trim();
2253
+ if (trimmed.length === 0 || trimmed.length > MAX_WORKER_PI_ARG_LENGTH || trimmed.includes("\0") || trimmed.includes("\n") || trimmed.includes("\r")) {
2254
+ return void 0;
2255
+ }
2256
+ const flagHead = trimmed.includes("=") ? trimmed.slice(0, trimmed.indexOf("=")) : trimmed;
2257
+ if (RESERVED_WORKER_PI_FLAGS.has(flagHead)) return void 0;
2258
+ normalizedArgs.push(trimmed);
2259
+ }
2260
+ settings.workerPiArgs = normalizedArgs;
2261
+ sources.workerPiArgs = "user";
2262
+ }
2263
+ const warnings = [
2264
+ ...leaderRecycling.warnings,
2265
+ ...ledger.warnings,
2266
+ ...budget.warnings,
2267
+ ...cacheWarming.warnings,
2268
+ ...missionCountdown.warnings
2269
+ ];
1945
2270
  return { settings, sources, ...warnings.length > 0 ? { warnings } : {} };
1946
2271
  }
1947
2272
  async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
@@ -1998,12 +2323,16 @@ function createInMemorySwarmSettingsRuntime(initial = {}) {
1998
2323
  ...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
1999
2324
  ...canonical.externalCommand ? { externalCommand: "user" } : {},
2000
2325
  ...canonical.pinToLeadWorkspace !== void 0 ? { pinToLeadWorkspace: "user" } : {},
2326
+ ...canonical.workerPiArgs !== void 0 ? { workerPiArgs: "user" } : {},
2001
2327
  ...canonical.exposeLeadMcp !== void 0 ? { exposeLeadMcp: "user" } : {},
2002
2328
  ...canonical.isolation !== void 0 ? { isolation: "user" } : {},
2003
2329
  ...canonical.resourceLeases !== void 0 ? { resourceLeases: "user" } : {},
2004
2330
  ...canonical.leaderRecycling !== void 0 ? { leaderRecycling: "user" } : {},
2005
2331
  ...canonical.ledger !== void 0 ? { ledger: "user" } : {},
2006
2332
  ...canonical.budget !== void 0 ? { budget: "user" } : {},
2333
+ ...canonical.cacheWarming !== void 0 ? { cacheWarming: "user" } : {},
2334
+ ...canonical.missionCountdown !== void 0 ? { missionCountdown: "user" } : {},
2335
+ ...canonical.reviewPolicy !== void 0 ? { reviewPolicy: "user" } : {},
2007
2336
  ...canonical.profilesDir !== void 0 ? { profilesDir: "user" } : {},
2008
2337
  ...canonical.allowedProfiles !== void 0 ? { allowedProfiles: "user" } : {}
2009
2338
  },
@@ -2080,6 +2409,18 @@ function createSwarmSettingsRuntime(options = {}) {
2080
2409
  ...canonicalPatch.budget
2081
2410
  };
2082
2411
  }
2412
+ if (canonicalPatch.cacheWarming && isRecord3(latest.document.cacheWarming)) {
2413
+ document.cacheWarming = {
2414
+ ...latest.document.cacheWarming,
2415
+ ...canonicalPatch.cacheWarming
2416
+ };
2417
+ }
2418
+ if (canonicalPatch.missionCountdown && isRecord3(latest.document.missionCountdown)) {
2419
+ document.missionCountdown = {
2420
+ ...latest.document.missionCountdown,
2421
+ ...canonicalPatch.missionCountdown
2422
+ };
2423
+ }
2083
2424
  const normalized = normalizeSwarmSettingsDocument(document);
2084
2425
  if (!normalized) throw new Error("Refusing to publish invalid Pi Agent Swarm settings.");
2085
2426
  await publishSettingsDocument(document, getPath(), operations);
@@ -2114,7 +2455,7 @@ async function publishSettingsDocument(document, path2, operations) {
2114
2455
  throw new Error(`settings document exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
2115
2456
  }
2116
2457
  await mkdir3(dirname2(path2), { recursive: true });
2117
- const temporaryPath = join3(dirname2(path2), `.${basename2(path2)}.${process.pid}.${randomUUID()}.tmp`);
2458
+ const temporaryPath = join4(dirname2(path2), `.${basename2(path2)}.${process.pid}.${randomUUID()}.tmp`);
2118
2459
  try {
2119
2460
  await operations.writeFile(temporaryPath, contents, {
2120
2461
  encoding: "utf8",
@@ -2123,7 +2464,7 @@ async function publishSettingsDocument(document, path2, operations) {
2123
2464
  });
2124
2465
  await operations.rename(temporaryPath, path2);
2125
2466
  } finally {
2126
- await rm3(temporaryPath, { force: true }).catch(() => void 0);
2467
+ await rm4(temporaryPath, { force: true }).catch(() => void 0);
2127
2468
  }
2128
2469
  }
2129
2470
  async function readSettingsDocument(path2, signal) {
@@ -2190,8 +2531,12 @@ function builtInSources() {
2190
2531
  leaderRecycling: "built-in",
2191
2532
  ledger: "built-in",
2192
2533
  budget: "built-in",
2534
+ cacheWarming: "built-in",
2535
+ missionCountdown: "built-in",
2536
+ reviewPolicy: "built-in",
2193
2537
  profilesDir: "built-in",
2194
- allowedProfiles: "built-in"
2538
+ allowedProfiles: "built-in",
2539
+ workerPiArgs: "built-in"
2195
2540
  };
2196
2541
  }
2197
2542
  function defaultSettings() {
@@ -2203,7 +2548,10 @@ function defaultSettings() {
2203
2548
  maxChildren: DEFAULT_SWARM_BUDGET_SETTINGS.maxChildren,
2204
2549
  standard: { ...DEFAULT_STANDARD_BUDGET },
2205
2550
  heavy: { ...DEFAULT_HEAVY_BUDGET }
2206
- }
2551
+ },
2552
+ cacheWarming: { ...DEFAULT_CACHE_WARMING_SETTINGS },
2553
+ missionCountdown: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS },
2554
+ reviewPolicy: DEFAULT_REVIEW_POLICY
2207
2555
  };
2208
2556
  }
2209
2557
  function freezeState(state) {
@@ -2218,7 +2566,10 @@ function freezeState(state) {
2218
2566
  standard: Object.freeze({ ...state.settings.budget.standard }),
2219
2567
  heavy: Object.freeze({ ...state.settings.budget.heavy })
2220
2568
  }),
2221
- ...state.settings.allowedProfiles ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) } : {}
2569
+ cacheWarming: Object.freeze({ ...state.settings.cacheWarming }),
2570
+ missionCountdown: Object.freeze({ ...state.settings.missionCountdown }),
2571
+ ...state.settings.allowedProfiles ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) } : {},
2572
+ ...state.settings.workerPiArgs ? { workerPiArgs: Object.freeze([...state.settings.workerPiArgs]) } : {}
2222
2573
  }),
2223
2574
  sources: Object.freeze({ ...state.sources }),
2224
2575
  ...state.warnings ? { warnings: Object.freeze([...state.warnings]) } : {}
@@ -2236,13 +2587,94 @@ function formatError(error) {
2236
2587
 
2237
2588
  // src/swarm-controller.ts
2238
2589
  import { randomBytes as randomBytes9 } from "node:crypto";
2239
- import { readdir as readdir4, readFile as readFile6, realpath as realpath3, rename as rename5, rm as rm10, stat as stat4, writeFile as writeFile5 } from "node:fs/promises";
2240
- import { basename as basename7, dirname as dirname7, join as join15, resolve as resolve12, sep as sep3 } from "node:path";
2590
+ import { readdir as readdir4, readFile as readFile7, realpath as realpath3, rename as rename5, rm as rm11, stat as stat4, writeFile as writeFile5 } from "node:fs/promises";
2591
+ import { basename as basename7, dirname as dirname7, join as join16, resolve as resolve13, sep as sep3 } from "node:path";
2592
+ import { visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
2593
+
2594
+ // src/cache-warming.ts
2595
+ function classifyModelCacheTier(model) {
2596
+ if (!model) return "unknown";
2597
+ if (isLocalHostedModel(model)) return "local_infinite";
2598
+ if (isDeepSeekModel(model)) return "deepseek_long";
2599
+ const shortSec = model.promptCache?.short;
2600
+ if (typeof shortSec === "number" && shortSec > 0) {
2601
+ return shortSec <= 3600 ? "cloud_short" : "deepseek_long";
2602
+ }
2603
+ const provider = (model.provider ?? "").toLowerCase();
2604
+ const id = (model.id ?? "").toLowerCase();
2605
+ if (provider.includes("anthropic") || provider.includes("kimi") || provider.includes("moonshot") || id.includes("claude") || id.startsWith("k3") || id.includes("kimi")) {
2606
+ return "cloud_short";
2607
+ }
2608
+ return "unknown";
2609
+ }
2610
+ function isDeepSeekModel(model) {
2611
+ const provider = (model?.provider ?? "").toLowerCase();
2612
+ const id = (model?.id ?? "").toLowerCase();
2613
+ return provider === "deepseek" || provider.includes("deepseek") || id.startsWith("deepseek");
2614
+ }
2615
+ function isLocalHostedModel(model) {
2616
+ if (!model?.baseUrl) return false;
2617
+ let host;
2618
+ try {
2619
+ host = new URL(model.baseUrl).hostname.toLowerCase();
2620
+ } catch {
2621
+ return false;
2622
+ }
2623
+ if (host === "localhost" || host.endsWith(".localhost") || host === "::1" || host === "[::1]" || host === "0.0.0.0") {
2624
+ return true;
2625
+ }
2626
+ const ipv4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/u.exec(host);
2627
+ if (!ipv4) return false;
2628
+ const a = Number(ipv4[1]);
2629
+ const b = Number(ipv4[2]);
2630
+ return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
2631
+ }
2632
+ var SwarmCacheWarmingPolicy = class {
2633
+ waitStartedAt;
2634
+ refreshesInWait = 0;
2635
+ /** Reset wait window counters when a real native turn starts or session resets. */
2636
+ resetWaitWindow() {
2637
+ this.waitStartedAt = void 0;
2638
+ this.refreshesInWait = 0;
2639
+ }
2640
+ evaluate(input) {
2641
+ const tier = classifyModelCacheTier(input.model);
2642
+ if (input.externalDirectActive) {
2643
+ this.resetWaitWindow();
2644
+ return { action: "stop", tier, reason: "external_direct_runtime_active" };
2645
+ }
2646
+ if (tier === "local_infinite") {
2647
+ this.resetWaitWindow();
2648
+ return { action: "stop", tier, reason: "local_model_infinite_kv" };
2649
+ }
2650
+ if (tier === "deepseek_long") {
2651
+ this.resetWaitWindow();
2652
+ return { action: "stop", tier, reason: "deepseek_long_retention" };
2653
+ }
2654
+ if (!input.settings.enabled) {
2655
+ return { action: input.defaultAction, tier, reason: "swarm_cache_warming_disabled" };
2656
+ }
2657
+ if (!input.isLead || input.inFlightWorkerCount <= 0) {
2658
+ this.resetWaitWindow();
2659
+ return { action: input.defaultAction, tier, reason: "no_inflight_workers" };
2660
+ }
2661
+ this.waitStartedAt ??= input.now;
2662
+ const elapsedMs = Math.max(0, input.now - this.waitStartedAt);
2663
+ if (elapsedMs >= input.settings.maxWaitDurationMs) {
2664
+ return { action: "stop", tier, reason: "wait_duration_cap_reached" };
2665
+ }
2666
+ if (this.refreshesInWait >= input.settings.maxRefreshesPerWait) {
2667
+ return { action: "stop", tier, reason: "refresh_count_cap_reached" };
2668
+ }
2669
+ this.refreshesInWait += 1;
2670
+ return { action: "warm", tier, reason: "lead_waiting_for_active_workers" };
2671
+ }
2672
+ };
2241
2673
 
2242
2674
  // src/external.ts
2243
2675
  import { spawn } from "node:child_process";
2244
2676
  import { existsSync } from "node:fs";
2245
- import { join as join4 } from "node:path";
2677
+ import { join as join5 } from "node:path";
2246
2678
  var ExternalLaunchError = class extends Error {
2247
2679
  constructor(message, splitCreated = false, terminalId) {
2248
2680
  super(message);
@@ -2345,7 +2777,7 @@ function isOnPath(binary) {
2345
2777
  if (binary.includes("/")) return existsSync(binary);
2346
2778
  const path2 = process.env.PATH ?? "";
2347
2779
  for (const dir of path2.split(":")) {
2348
- if (dir && existsSync(join4(dir, binary))) return true;
2780
+ if (dir && existsSync(join5(dir, binary))) return true;
2349
2781
  }
2350
2782
  return false;
2351
2783
  }
@@ -2498,6 +2930,65 @@ var ExternalRuntimeHost = class {
2498
2930
  sessionId
2499
2931
  });
2500
2932
  }
2933
+ deliverToDirect(params) {
2934
+ this.emit({
2935
+ type: "direct_deliver",
2936
+ runtimeId: params.runtimeId,
2937
+ sessionId: params.sessionId,
2938
+ prompt: params.prompt,
2939
+ source: params.source,
2940
+ ...params.messageId ? { messageId: params.messageId } : {},
2941
+ ...params.fromSessionId ? { fromSessionId: params.fromSessionId } : {},
2942
+ ...params.replaceTag ? { replaceTag: params.replaceTag } : {}
2943
+ });
2944
+ }
2945
+ clearDirectQueue(params) {
2946
+ this.emit({
2947
+ type: "direct_clear_queue",
2948
+ runtimeId: params.runtimeId,
2949
+ sessionId: params.sessionId,
2950
+ ...params.replaceTag ? { replaceTag: params.replaceTag } : {}
2951
+ });
2952
+ }
2953
+ restoreDirect(params, signal) {
2954
+ const requestId = this.handlers.randomId("extrestore");
2955
+ const timeoutMs = params.timeoutMs ?? 6e4;
2956
+ return new Promise((resolvePromise, rejectPromise) => {
2957
+ if (signal?.aborted) {
2958
+ rejectPromise(new Error("External runtime direct restore aborted"));
2959
+ return;
2960
+ }
2961
+ const waiter = {
2962
+ resolve: resolvePromise,
2963
+ reject: rejectPromise
2964
+ };
2965
+ waiter.timer = setTimeout(() => {
2966
+ if (!this.readyWaiters.delete(requestId)) return;
2967
+ this.clearWaiter(waiter);
2968
+ rejectPromise(new Error(`External runtime "${params.runtimeId}" did not restore within ${timeoutMs}ms`));
2969
+ }, timeoutMs);
2970
+ if (signal) {
2971
+ const onAbort = () => {
2972
+ if (!this.readyWaiters.delete(requestId)) return;
2973
+ this.clearWaiter(waiter);
2974
+ rejectPromise(new Error("External runtime direct restore aborted"));
2975
+ };
2976
+ signal.addEventListener("abort", onAbort, { once: true });
2977
+ waiter.cleanupAbort = () => signal.removeEventListener("abort", onAbort);
2978
+ }
2979
+ this.readyWaiters.set(requestId, waiter);
2980
+ this.emit({
2981
+ type: "direct_restore",
2982
+ requestId,
2983
+ runtimeId: params.runtimeId,
2984
+ sessionId: params.sessionId,
2985
+ ...params.model ? { model: params.model } : {},
2986
+ ...params.thoughtLevel ? { thoughtLevel: params.thoughtLevel } : {},
2987
+ ...params.mode ? { mode: params.mode } : {},
2988
+ handoffPrompt: params.handoffPrompt
2989
+ });
2990
+ });
2991
+ }
2501
2992
  emit(payload) {
2502
2993
  if (typeof this.pi.events?.emit === "function") {
2503
2994
  this.pi.events.emit(EXTERNAL_RUNTIME_EVENT, payload);
@@ -2526,6 +3017,52 @@ var ExternalRuntimeHost = class {
2526
3017
  });
2527
3018
  return;
2528
3019
  }
3020
+ if (type === "direct_state" && typeof msg.runtimeId === "string" && typeof msg.active === "boolean") {
3021
+ this.handlers.onDirectState?.({
3022
+ runtimeId: msg.runtimeId,
3023
+ ...typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {},
3024
+ active: msg.active,
3025
+ ...typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {},
3026
+ ...typeof msg.thoughtLevel === "string" && msg.thoughtLevel.length > 0 ? { thoughtLevel: msg.thoughtLevel } : {},
3027
+ ...typeof msg.mode === "string" && msg.mode.length > 0 ? { mode: msg.mode } : {},
3028
+ ...typeof msg.busy === "boolean" ? { busy: msg.busy } : {},
3029
+ ...typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0 ? { pendingCount: msg.pendingCount } : {},
3030
+ updatedAt: this.handlers.now()
3031
+ });
3032
+ return;
3033
+ }
3034
+ if (type === "context_usage" && typeof msg.runtimeId === "string") {
3035
+ const contextWindow = typeof msg.contextWindow === "number" && Number.isFinite(msg.contextWindow) && msg.contextWindow > 0 ? msg.contextWindow : 1048576;
3036
+ const tokens = typeof msg.tokens === "number" && Number.isFinite(msg.tokens) && msg.tokens >= 0 ? msg.tokens : null;
3037
+ const completedTurns = typeof msg.completedTurns === "number" && Number.isInteger(msg.completedTurns) && msg.completedTurns >= 0 ? msg.completedTurns : 0;
3038
+ const compactionCount = typeof msg.compactionCount === "number" && Number.isInteger(msg.compactionCount) && msg.compactionCount >= 0 ? msg.compactionCount : 0;
3039
+ const rawUsage = msg.usage && typeof msg.usage === "object" && !Array.isArray(msg.usage) ? msg.usage : void 0;
3040
+ const usage = rawUsage ? {
3041
+ ...typeof rawUsage.inputTokens === "number" ? { inputTokens: rawUsage.inputTokens } : {},
3042
+ ...typeof rawUsage.outputTokens === "number" ? { outputTokens: rawUsage.outputTokens } : {},
3043
+ ...typeof rawUsage.totalTokens === "number" ? { totalTokens: rawUsage.totalTokens } : {},
3044
+ ...typeof rawUsage.costUsd === "number" ? { costUsd: rawUsage.costUsd } : {},
3045
+ ...typeof rawUsage.cachedReadTokens === "number" ? { cachedReadTokens: rawUsage.cachedReadTokens } : {},
3046
+ ...typeof rawUsage.cachedWriteTokens === "number" ? { cachedWriteTokens: rawUsage.cachedWriteTokens } : {},
3047
+ ...typeof rawUsage.thoughtTokens === "number" ? { thoughtTokens: rawUsage.thoughtTokens } : {}
3048
+ } : void 0;
3049
+ this.handlers.onContextUsage?.({
3050
+ runtimeId: msg.runtimeId,
3051
+ ...typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {},
3052
+ tokens,
3053
+ contextWindow,
3054
+ completedTurns,
3055
+ compactionCount,
3056
+ ...typeof msg.idleMs === "number" && Number.isFinite(msg.idleMs) && msg.idleMs >= 0 ? { idleMs: msg.idleMs } : {},
3057
+ ...typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {},
3058
+ ...usage ? { usage } : {},
3059
+ settled: msg.settled === true,
3060
+ aborted: msg.aborted === true,
3061
+ ...typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0 ? { pendingCount: msg.pendingCount } : {},
3062
+ updatedAt: this.handlers.now()
3063
+ });
3064
+ return;
3065
+ }
2529
3066
  if (type === "ready" && typeof msg.requestId === "string") {
2530
3067
  const waiter = this.readyWaiters.get(msg.requestId);
2531
3068
  if (!waiter) return;
@@ -2581,7 +3118,7 @@ var ExternalRuntimeHost = class {
2581
3118
  };
2582
3119
 
2583
3120
  // src/fanout.ts
2584
- import { resolve as resolve3 } from "node:path";
3121
+ import { resolve as resolve4 } from "node:path";
2585
3122
  var FanoutConcurrencyError = class extends Error {
2586
3123
  constructor(code, message) {
2587
3124
  super(message);
@@ -2619,7 +3156,7 @@ function precheckFanoutBatch(branches, options) {
2619
3156
  }
2620
3157
  }
2621
3158
  if (branch.profile.writable) {
2622
- const normalizedCwd = resolve3(branch.cwd);
3159
+ const normalizedCwd = resolve4(branch.cwd);
2623
3160
  const list = writableByCwd.get(normalizedCwd) ?? [];
2624
3161
  list.push(branch.id);
2625
3162
  writableByCwd.set(normalizedCwd, list);
@@ -2947,11 +3484,11 @@ function optionalHexColor(value) {
2947
3484
 
2948
3485
  // src/launcher.ts
2949
3486
  import { randomBytes as randomBytes4 } from "node:crypto";
2950
- import { lstat as lstat3, open as open3, rm as rm4 } from "node:fs/promises";
2951
- import { join as join5, relative as relative2, resolve as resolve4 } from "node:path";
3487
+ import { lstat as lstat3, open as open3, rm as rm5 } from "node:fs/promises";
3488
+ import { join as join6, relative as relative2, resolve as resolve5 } from "node:path";
2952
3489
  async function createPiLauncher(invocation, directory, embeddedEnvironment) {
2953
3490
  await assertPrivateDirectory(directory);
2954
- const launcherPath = join5(directory, `launch-${randomBytes4(8).toString("hex")}.sh`);
3491
+ const launcherPath = join6(directory, `launch-${randomBytes4(8).toString("hex")}.sh`);
2955
3492
  assertInside(directory, launcherPath);
2956
3493
  const command = [invocation.command, ...invocation.args];
2957
3494
  for (const value of command) {
@@ -2971,7 +3508,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
2971
3508
  await handle.close();
2972
3509
  } catch (error) {
2973
3510
  await handle.close().catch(() => void 0);
2974
- await rm4(launcherPath, { force: true }).catch(() => void 0);
3511
+ await rm5(launcherPath, { force: true }).catch(() => void 0);
2975
3512
  throw error;
2976
3513
  }
2977
3514
  let cleaned = false;
@@ -2982,7 +3519,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
2982
3519
  if (cleaned) return;
2983
3520
  cleaned = true;
2984
3521
  assertInside(directory, launcherPath);
2985
- await rm4(launcherPath, { force: true });
3522
+ await rm5(launcherPath, { force: true });
2986
3523
  }
2987
3524
  };
2988
3525
  }
@@ -3014,7 +3551,7 @@ async function assertPrivateDirectory(path2) {
3014
3551
  }
3015
3552
  }
3016
3553
  function assertInside(parent, candidate) {
3017
- const rel = relative2(resolve4(parent), resolve4(candidate));
3554
+ const rel = relative2(resolve5(parent), resolve5(candidate));
3018
3555
  if (!rel || rel === ".." || rel.startsWith("../")) {
3019
3556
  throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
3020
3557
  }
@@ -3022,15 +3559,15 @@ function assertInside(parent, candidate) {
3022
3559
 
3023
3560
  // src/lead-mcp-bridge.ts
3024
3561
  import { randomBytes as randomBytes6, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
3025
- import { chmod as chmod3, lstat as lstat5, mkdir as mkdir5, readdir as readdir2, rm as rm6 } from "node:fs/promises";
3562
+ import { chmod as chmod3, lstat as lstat5, mkdir as mkdir5, readdir as readdir2, rm as rm7 } from "node:fs/promises";
3026
3563
  import { createConnection, createServer } from "node:net";
3027
- import { join as join7 } from "node:path";
3564
+ import { join as join8 } from "node:path";
3028
3565
 
3029
3566
  // src/runtime-directory.ts
3030
3567
  import { randomBytes as randomBytes5 } from "node:crypto";
3031
- import { chmod as chmod2, lstat as lstat4, mkdir as mkdir4, open as open4, opendir, realpath as realpath2, rename as rename4, rm as rm5, stat as stat3 } from "node:fs/promises";
3568
+ import { chmod as chmod2, lstat as lstat4, mkdir as mkdir4, open as open4, opendir, realpath as realpath2, rename as rename4, rm as rm6, stat as stat3 } from "node:fs/promises";
3032
3569
  import { tmpdir } from "node:os";
3033
- import { basename as basename3, dirname as dirname3, isAbsolute, join as join6, relative as relative3, resolve as resolve5 } from "node:path";
3570
+ import { basename as basename3, dirname as dirname3, isAbsolute, join as join7, relative as relative3, resolve as resolve6 } from "node:path";
3034
3571
  var MAX_UNIX_SOCKET_PATH_BYTES = 103;
3035
3572
  var MAX_MANIFEST_BYTES = 8 * 1024;
3036
3573
  var ORPHAN_GRACE_MS = 6e4;
@@ -3046,21 +3583,21 @@ function defaultRuntimeBaseDirectory() {
3046
3583
  throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
3047
3584
  }
3048
3585
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
3049
- if (process.platform === "darwin") return join6("/tmp", `pi-swarm-${uid}`);
3586
+ if (process.platform === "darwin") return join7("/tmp", `pi-swarm-${uid}`);
3050
3587
  const runtime2 = process.env.XDG_RUNTIME_DIR;
3051
- if (runtime2 && isAbsolute(runtime2) && Buffer.byteLength(join6(runtime2, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES) {
3052
- return join6(runtime2, "pi-swarm");
3588
+ if (runtime2 && isAbsolute(runtime2) && Buffer.byteLength(join7(runtime2, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES) {
3589
+ return join7(runtime2, "pi-swarm");
3053
3590
  }
3054
- const systemTmp = resolve5(tmpdir());
3055
- const candidate = join6(systemTmp, `pi-swarm-${uid}`);
3056
- const socketCandidate = join6(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
3057
- return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join6("/tmp", `pi-swarm-${uid}`);
3591
+ const systemTmp = resolve6(tmpdir());
3592
+ const candidate = join7(systemTmp, `pi-swarm-${uid}`);
3593
+ const socketCandidate = join7(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
3594
+ return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join7("/tmp", `pi-swarm-${uid}`);
3058
3595
  }
3059
3596
  async function ensureGroupRuntimeDirectory(groupId, options = {}) {
3060
3597
  if (!SAFE_GROUP_ID.test(groupId)) throw new Error("Pi Agent Swarm runtime group id is invalid");
3061
- const baseDirectory = resolve5(options.baseDirectory ?? defaultRuntimeBaseDirectory());
3062
- const directory = join6(baseDirectory, groupId);
3063
- const longestSocket = join6(directory, `${"x".repeat(24)}.sock`);
3598
+ const baseDirectory = resolve6(options.baseDirectory ?? defaultRuntimeBaseDirectory());
3599
+ const directory = join7(baseDirectory, groupId);
3600
+ const longestSocket = join7(directory, `${"x".repeat(24)}.sock`);
3064
3601
  if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
3065
3602
  throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
3066
3603
  }
@@ -3070,7 +3607,7 @@ async function ensureGroupRuntimeDirectory(groupId, options = {}) {
3070
3607
  }
3071
3608
  function createEndpointPaths(directory, endpointId) {
3072
3609
  if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
3073
- const socketPath = join6(directory, `${endpointId}.sock`);
3610
+ const socketPath = join7(directory, `${endpointId}.sock`);
3074
3611
  if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
3075
3612
  throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
3076
3613
  }
@@ -3078,7 +3615,7 @@ function createEndpointPaths(directory, endpointId) {
3078
3615
  directory,
3079
3616
  endpointId,
3080
3617
  socketPath,
3081
- manifestPath: join6(directory, `${endpointId}.json`)
3618
+ manifestPath: join7(directory, `${endpointId}.json`)
3082
3619
  };
3083
3620
  }
3084
3621
  function randomEndpointId() {
@@ -3093,7 +3630,7 @@ async function publishManifest(manifestPath, manifest) {
3093
3630
  if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
3094
3631
  throw new Error("Pi Agent Swarm endpoint manifest is too large");
3095
3632
  }
3096
- const temporaryPath = join6(parent, `.${basename3(manifestPath)}.${randomBytes5(8).toString("hex")}.tmp`);
3633
+ const temporaryPath = join7(parent, `.${basename3(manifestPath)}.${randomBytes5(8).toString("hex")}.tmp`);
3097
3634
  let handle;
3098
3635
  try {
3099
3636
  handle = await open4(temporaryPath, "wx", 384);
@@ -3105,7 +3642,7 @@ async function publishManifest(manifestPath, manifest) {
3105
3642
  await chmod2(manifestPath, 384);
3106
3643
  } finally {
3107
3644
  await handle?.close().catch(() => void 0);
3108
- await rm5(temporaryPath, { force: true }).catch(() => void 0);
3645
+ await rm6(temporaryPath, { force: true }).catch(() => void 0);
3109
3646
  }
3110
3647
  }
3111
3648
  async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
@@ -3131,7 +3668,7 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
3131
3668
  for (const name of names) {
3132
3669
  const socketMatch = SAFE_SOCKET_NAME.exec(name);
3133
3670
  if (socketMatch) {
3134
- const manifestPath = join6(directory, `${socketMatch[1]}.json`);
3671
+ const manifestPath = join7(directory, `${socketMatch[1]}.json`);
3135
3672
  if (!await pathExists(manifestPath)) {
3136
3673
  if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
3137
3674
  }
@@ -3148,15 +3685,15 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
3148
3685
  async function removeOwnedEndpoint(paths) {
3149
3686
  for (const path2 of [paths.manifestPath, paths.socketPath]) {
3150
3687
  assertOwnedPath(paths.directory, path2);
3151
- await rm5(path2, { force: true }).catch(() => void 0);
3688
+ await rm6(path2, { force: true }).catch(() => void 0);
3152
3689
  }
3153
3690
  }
3154
3691
  function endpointIdFromManifestName(name) {
3155
3692
  return SAFE_MANIFEST_NAME.exec(name)?.[1];
3156
3693
  }
3157
3694
  function assertOwnedPath(parent, candidate, suffix) {
3158
- const resolvedParent = resolve5(parent);
3159
- const resolvedCandidate = resolve5(candidate);
3695
+ const resolvedParent = resolve6(parent);
3696
+ const resolvedCandidate = resolve6(candidate);
3160
3697
  const rel = relative3(resolvedParent, resolvedCandidate);
3161
3698
  if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
3162
3699
  throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
@@ -3166,7 +3703,7 @@ function assertOwnedPath(parent, candidate, suffix) {
3166
3703
  }
3167
3704
  }
3168
3705
  async function removeStaleOwnedEntry(directory, name, kind, now) {
3169
- const path2 = join6(directory, name);
3706
+ const path2 = join7(directory, name);
3170
3707
  assertOwnedPath(directory, path2);
3171
3708
  try {
3172
3709
  const first = await lstat4(path2, { bigint: true });
@@ -3177,7 +3714,7 @@ async function removeStaleOwnedEntry(directory, name, kind, now) {
3177
3714
  if (current.dev !== first.dev || current.ino !== first.ino || current.mtimeMs !== first.mtimeMs || (kind === "file" ? !current.isFile() : !current.isSocket())) {
3178
3715
  return false;
3179
3716
  }
3180
- await rm5(path2);
3717
+ await rm6(path2);
3181
3718
  return true;
3182
3719
  } catch (error) {
3183
3720
  if (isMissing2(error)) return false;
@@ -3236,12 +3773,12 @@ async function cleanupStaleLeadMcpSockets(baseDir) {
3236
3773
  let removed = 0;
3237
3774
  for (const name of entries) {
3238
3775
  if (!LEAD_MCP_SOCKET_RE.test(name)) continue;
3239
- const candidate = join7(baseDir, name);
3776
+ const candidate = join8(baseDir, name);
3240
3777
  const info = await lstat5(candidate).catch(() => void 0);
3241
3778
  if (!info?.isSocket()) continue;
3242
3779
  const alive = await probeUnixSocketAlive(candidate);
3243
3780
  if (!alive) {
3244
- await rm6(candidate, { force: true }).catch(() => void 0);
3781
+ await rm7(candidate, { force: true }).catch(() => void 0);
3245
3782
  removed += 1;
3246
3783
  }
3247
3784
  }
@@ -3312,16 +3849,24 @@ var LEAD_MCP_TOOLS = [
3312
3849
  },
3313
3850
  {
3314
3851
  name: "swarm_bus",
3315
- description: "List live swarm sessions, send a notify/request/reply message, or request graceful peer shutdown.",
3852
+ description: 'List live swarm sessions, manage the mandatory first-principles mission countdown (action="mission"), send a notify/request/reply message, or request graceful peer shutdown.',
3316
3853
  inputSchema: {
3317
3854
  type: "object",
3318
3855
  properties: {
3319
- action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog"] },
3856
+ action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog", "mission"] },
3320
3857
  targetSessionId: { type: "string" },
3321
3858
  message: { type: "string" },
3322
3859
  mode: { type: "string", enum: ["notify", "request"] },
3323
3860
  replyTo: { type: "string" },
3324
- taskStatus: { type: "string", enum: ["working", "completed"] }
3861
+ taskStatus: { type: "string", enum: ["working", "completed"] },
3862
+ missionAction: { type: "string", enum: ["start", "complete", "status"] },
3863
+ firstPrinciples: { type: "string" },
3864
+ acceptanceCriteria: { type: "string" },
3865
+ constraints: { type: "string" },
3866
+ estimatedMinutes: { type: "number" },
3867
+ summary: { type: "string" },
3868
+ outcome: { type: "string", enum: ["achieved", "with_residuals"] },
3869
+ residuals: { type: "array", items: { type: "string" } }
3325
3870
  },
3326
3871
  required: ["action"],
3327
3872
  additionalProperties: false
@@ -3438,12 +3983,12 @@ var LeadMcpBridge = class {
3438
3983
  throw new Error("Refusing to start swarm-lead MCP bridge in a non-lead worker session");
3439
3984
  }
3440
3985
  if (this.server) return;
3441
- const baseDir = join7(this.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), "lead-mcp");
3986
+ const baseDir = join8(this.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), "lead-mcp");
3442
3987
  await mkdir5(baseDir, { recursive: true, mode: 448 });
3443
3988
  await chmod3(baseDir, 448).catch(() => void 0);
3444
3989
  await cleanupStaleLeadMcpSockets(baseDir).catch(() => void 0);
3445
3990
  const token = randomBytes6(32).toString("hex");
3446
- const socketPath = join7(baseDir, `lmcp-${randomBytes6(8).toString("hex")}.sock`);
3991
+ const socketPath = join8(baseDir, `lmcp-${randomBytes6(8).toString("hex")}.sock`);
3447
3992
  const server = createServer((socket) => {
3448
3993
  this.handleConnection(socket, token);
3449
3994
  });
@@ -3486,7 +4031,7 @@ var LeadMcpBridge = class {
3486
4031
  });
3487
4032
  }
3488
4033
  if (socketPath) {
3489
- await rm6(socketPath, { force: true }).catch(() => void 0);
4034
+ await rm7(socketPath, { force: true }).catch(() => void 0);
3490
4035
  }
3491
4036
  if (this.registered) {
3492
4037
  const unregisterMcp = this.pi.unregisterMcpServer;
@@ -3623,6 +4168,23 @@ var LeadMcpBridge = class {
3623
4168
  const action = typeof args.action === "string" ? args.action : "";
3624
4169
  if (action === "catalog") return this.actions.catalog(ctx);
3625
4170
  if (action === "list") return this.actions.snapshot();
4171
+ if (action === "mission") {
4172
+ if (!this.actions.mission) throw new Error("swarm_bus mission is unavailable");
4173
+ const missionAction = args.missionAction;
4174
+ if (missionAction !== "start" && missionAction !== "complete" && missionAction !== "status") {
4175
+ throw new Error('swarm_bus mission requires missionAction ("start" | "complete" | "status")');
4176
+ }
4177
+ return this.actions.mission(ctx, {
4178
+ missionAction,
4179
+ ...typeof args.firstPrinciples === "string" ? { firstPrinciples: args.firstPrinciples } : {},
4180
+ ...typeof args.acceptanceCriteria === "string" ? { acceptanceCriteria: args.acceptanceCriteria } : {},
4181
+ ...typeof args.constraints === "string" ? { constraints: args.constraints } : {},
4182
+ ...typeof args.estimatedMinutes === "number" ? { estimatedMinutes: args.estimatedMinutes } : {},
4183
+ ...typeof args.summary === "string" ? { summary: args.summary } : {},
4184
+ ...args.outcome === "achieved" || args.outcome === "with_residuals" ? { outcome: args.outcome } : {},
4185
+ ...Array.isArray(args.residuals) ? { residuals: args.residuals.filter((r) => typeof r === "string") } : {}
4186
+ });
4187
+ }
3626
4188
  if (action === "shutdown") {
3627
4189
  if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
3628
4190
  throw new Error("swarm_bus shutdown requires targetSessionId");
@@ -3656,9 +4218,9 @@ var LeadMcpBridge = class {
3656
4218
  };
3657
4219
 
3658
4220
  // src/leader-recycling.ts
3659
- import { readdir as readdir3, readFile as readFile3 } from "node:fs/promises";
3660
- import { join as join8, resolve as resolve6 } from "node:path";
3661
- var LEADER_LINEAGES_DIRECTORY = join8(WORKER_RECYCLING_DIRECTORY, "leader-lineages");
4221
+ import { readdir as readdir3, readFile as readFile4 } from "node:fs/promises";
4222
+ import { join as join9, resolve as resolve7 } from "node:path";
4223
+ var LEADER_LINEAGES_DIRECTORY = join9(WORKER_RECYCLING_DIRECTORY, "leader-lineages");
3662
4224
  var DEFAULT_LEADER_SOFT_CONTEXT_PERCENT = 50;
3663
4225
  var DEFAULT_LEADER_SOFT_CONTEXT_TOKENS = 1e5;
3664
4226
  var DEFAULT_LEADER_HIGH_WATER_PERCENT = 75;
@@ -3696,12 +4258,13 @@ var LEADER_LINEAGE_TRANSITIONS = {
3696
4258
  };
3697
4259
  function normalizeLeaderRecyclingPolicy(input = {}) {
3698
4260
  const value = record2(input, "leader recycling policy");
3699
- const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "maxReplacements"];
4261
+ const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "highWaterTokens", "maxReplacements"];
3700
4262
  const unknown = Object.keys(value).find((key) => !allowed.includes(key));
3701
4263
  if (unknown) throw new Error(`Pi Agent Swarm leader recycling policy has unknown field ${unknown}`);
3702
4264
  const softContextPercent = value.softContextPercent ?? DEFAULT_LEADER_SOFT_CONTEXT_PERCENT;
3703
4265
  const softContextTokens = value.softContextTokens ?? DEFAULT_LEADER_SOFT_CONTEXT_TOKENS;
3704
4266
  const highWaterPercent = value.highWaterPercent ?? DEFAULT_LEADER_HIGH_WATER_PERCENT;
4267
+ const highWaterTokens = value.highWaterTokens;
3705
4268
  const maxReplacements = value.maxReplacements ?? DEFAULT_LEADER_RECYCLING_POLICY.maxReplacements;
3706
4269
  for (const [key, percentage] of [
3707
4270
  ["softContextPercent", softContextPercent],
@@ -3714,6 +4277,9 @@ function normalizeLeaderRecyclingPolicy(input = {}) {
3714
4277
  if (typeof softContextTokens !== "number" || !Number.isFinite(softContextTokens) || softContextTokens <= 0) {
3715
4278
  throw new Error("Pi Agent Swarm leader recycling softContextTokens must be greater than 0");
3716
4279
  }
4280
+ if (highWaterTokens !== void 0 && (typeof highWaterTokens !== "number" || !Number.isFinite(highWaterTokens) || highWaterTokens <= 0)) {
4281
+ throw new Error("Pi Agent Swarm leader recycling highWaterTokens must be greater than 0");
4282
+ }
3717
4283
  if (!Number.isInteger(maxReplacements) || maxReplacements < 0 || maxReplacements > MAX_REPLACEMENTS) {
3718
4284
  throw new Error(`Pi Agent Swarm leader recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
3719
4285
  }
@@ -3721,6 +4287,7 @@ function normalizeLeaderRecyclingPolicy(input = {}) {
3721
4287
  softContextPercent,
3722
4288
  softContextTokens,
3723
4289
  highWaterPercent,
4290
+ ...highWaterTokens !== void 0 ? { highWaterTokens } : {},
3724
4291
  maxReplacements
3725
4292
  };
3726
4293
  }
@@ -3730,7 +4297,7 @@ function shouldAnalyzeLeaderBranch(branch, usage, policyInput = {}) {
3730
4297
  const window = usage.contextWindow;
3731
4298
  const policy = normalizeLeaderRecyclingPolicy(policyInput);
3732
4299
  const percent = tokens / window * 100;
3733
- if (percent >= policy.softContextPercent || percent >= policy.highWaterPercent || tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP)) {
4300
+ if (percent >= policy.softContextPercent || percent >= policy.highWaterPercent || tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP) || policy.highWaterTokens !== void 0 && tokens >= Math.min(policy.highWaterTokens, window * 0.85)) {
3734
4301
  return true;
3735
4302
  }
3736
4303
  let completedTurns = 0;
@@ -3830,7 +4397,7 @@ function evaluateLeaderRecyclingGate(snapshot, policyInput = {}, cooldown = {
3830
4397
  }
3831
4398
  }
3832
4399
  if (snapshot.compactionCount >= 1) signals.push("compaction_detected");
3833
- const highWater = known !== void 0 && known.percent >= policy.highWaterPercent;
4400
+ const highWater = known !== void 0 && (known.percent >= policy.highWaterPercent || policy.highWaterTokens !== void 0 && known.tokens >= Math.min(policy.highWaterTokens, known.window * 0.85));
3834
4401
  const reason = [...signals];
3835
4402
  if (highWater) reason.push("high_water_context");
3836
4403
  if (known === void 0) reason.push("context_tokens_unknown");
@@ -3874,15 +4441,15 @@ function leaderLineagePaths(projectRoot, lineageId, generation) {
3874
4441
  if (!Number.isInteger(generation) || generation < 1) {
3875
4442
  throw new Error("Pi Agent Swarm leader lineage generation is invalid");
3876
4443
  }
3877
- const root = resolve6(projectRoot);
3878
- const storageRoot = resolve6(root, WORKER_RECYCLING_DIRECTORY);
4444
+ const root = resolve7(projectRoot);
4445
+ const storageRoot = resolve7(root, WORKER_RECYCLING_DIRECTORY);
3879
4446
  if (!isWithin(root, storageRoot)) throw new Error("Pi Agent Swarm leader lineage storage escapes the project root");
3880
- const lineageDirectory = join8(storageRoot, "leader-lineages", lineageId);
4447
+ const lineageDirectory = join9(storageRoot, "leader-lineages", lineageId);
3881
4448
  return {
3882
4449
  root: storageRoot,
3883
4450
  lineageDirectory,
3884
- lineagePath: join8(lineageDirectory, "lineage.json"),
3885
- handoffPath: join8(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`)
4451
+ lineagePath: join9(lineageDirectory, "lineage.json"),
4452
+ handoffPath: join9(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`)
3886
4453
  };
3887
4454
  }
3888
4455
  function canTransitionLeaderLineageState(from, to) {
@@ -3900,7 +4467,7 @@ async function initializeLeaderLineage(options) {
3900
4467
  {
3901
4468
  schemaVersion: 1,
3902
4469
  lineageId: options.lineageId,
3903
- projectRoot: resolve6(options.projectRoot),
4470
+ projectRoot: resolve7(options.projectRoot),
3904
4471
  leaderSessionId: options.leaderSessionId,
3905
4472
  originalObjective: options.originalObjective,
3906
4473
  policy: normalizeLeaderRecyclingPolicy(options.policy),
@@ -3922,7 +4489,7 @@ async function initializeLeaderLineage(options) {
3922
4489
  );
3923
4490
  }
3924
4491
  async function findLeaderLineage(projectRoot, leaderSessionId, onWarning) {
3925
- const directory = resolve6(projectRoot, LEADER_LINEAGES_DIRECTORY);
4492
+ const directory = resolve7(projectRoot, LEADER_LINEAGES_DIRECTORY);
3926
4493
  let entries;
3927
4494
  try {
3928
4495
  entries = await readdir3(directory, { withFileTypes: true });
@@ -3951,7 +4518,7 @@ async function findLeaderLineage(projectRoot, leaderSessionId, onWarning) {
3951
4518
  }
3952
4519
  async function readLeaderLineage(projectRoot, lineageId) {
3953
4520
  const paths = leaderLineagePaths(projectRoot, lineageId, 1);
3954
- const value = JSON.parse(await readFile3(paths.lineagePath, "utf8"));
4521
+ const value = JSON.parse(await readFile4(paths.lineagePath, "utf8"));
3955
4522
  return validateLeaderLineage(value, projectRoot, lineageId);
3956
4523
  }
3957
4524
  async function updateLeaderLineage(projectRoot, lineageId, patch, expected = {}) {
@@ -3970,7 +4537,7 @@ async function updateLeaderLineage(projectRoot, lineageId, patch, expected = {})
3970
4537
  ...existing,
3971
4538
  ...patch,
3972
4539
  lineageId,
3973
- projectRoot: resolve6(projectRoot),
4540
+ projectRoot: resolve7(projectRoot),
3974
4541
  state: existing.state,
3975
4542
  currentGeneration: existing.currentGeneration,
3976
4543
  replacementCount: existing.replacementCount,
@@ -4010,7 +4577,7 @@ async function transitionLeaderLineage(projectRoot, lineageId, nextState, option
4010
4577
  ...existing,
4011
4578
  ...options.patch ?? {},
4012
4579
  lineageId,
4013
- projectRoot: resolve6(projectRoot),
4580
+ projectRoot: resolve7(projectRoot),
4014
4581
  currentGeneration,
4015
4582
  replacementCount,
4016
4583
  state: nextState,
@@ -4027,9 +4594,9 @@ async function transitionLeaderLineage(projectRoot, lineageId, nextState, option
4027
4594
  }
4028
4595
  function validateLeaderHandoffContent(content, projectRoot) {
4029
4596
  validateHandoff(content, "leader");
4030
- const root = resolve6(projectRoot);
4597
+ const root = resolve7(projectRoot);
4031
4598
  for (const artifact of content.artifacts) {
4032
- if (!isWithin(root, resolve6(root, artifact))) {
4599
+ if (!isWithin(root, resolve7(root, artifact))) {
4033
4600
  throw new Error("Pi Agent Swarm leader handoff artifact is outside the project root");
4034
4601
  }
4035
4602
  }
@@ -4075,17 +4642,17 @@ function renderLeaderHandoff(content) {
4075
4642
  async function verifyLeaderHandoffReadable(projectRoot, lineageId, generation, handoffPath) {
4076
4643
  if (generation === 1) return;
4077
4644
  const expected = leaderLineagePaths(projectRoot, lineageId, generation - 1).handoffPath;
4078
- if (resolve6(handoffPath) !== expected) {
4645
+ if (resolve7(handoffPath) !== expected) {
4079
4646
  throw new Error("Pi Agent Swarm leader successor handoff path does not match its predecessor generation");
4080
4647
  }
4081
- const markdown = await readFile3(expected, "utf8");
4648
+ const markdown = await readFile4(expected, "utf8");
4082
4649
  if (!hasRequiredHandoffSections(markdown)) {
4083
4650
  throw new Error("Pi Agent Swarm leader successor handoff is incomplete");
4084
4651
  }
4085
4652
  }
4086
4653
  function validateLeaderLineage(value, projectRoot, lineageId) {
4087
4654
  const lineage = record2(value, "leader lineage");
4088
- if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve6(projectRoot)) {
4655
+ if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve7(projectRoot)) {
4089
4656
  throw new Error("Pi Agent Swarm leader lineage identity is invalid");
4090
4657
  }
4091
4658
  if (typeof lineage.leaderSessionId !== "string" || Buffer.byteLength(lineage.leaderSessionId, "utf8") > 256) {
@@ -4117,8 +4684,8 @@ function validateLeaderLineage(value, projectRoot, lineageId) {
4117
4684
  if (typeof lineage.currentHandoffPath !== "string") {
4118
4685
  throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
4119
4686
  }
4120
- const handoffPath = resolve6(lineage.currentHandoffPath);
4121
- const generations = join8(leaderLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
4687
+ const handoffPath = resolve7(lineage.currentHandoffPath);
4688
+ const generations = join9(leaderLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
4122
4689
  if (!isWithin(generations, handoffPath) || !/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))) {
4123
4690
  throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
4124
4691
  }
@@ -4170,7 +4737,7 @@ function record2(value, label) {
4170
4737
  }
4171
4738
 
4172
4739
  // src/leader-runtime.ts
4173
- import { readFile as readFile4 } from "node:fs/promises";
4740
+ import { readFile as readFile5 } from "node:fs/promises";
4174
4741
 
4175
4742
  // src/leader-handoff-bridge.ts
4176
4743
  import { randomBytes as randomBytes7 } from "node:crypto";
@@ -4255,10 +4822,12 @@ var runtimeGlobal = globalThis;
4255
4822
  runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL] ??= {
4256
4823
  actions: /* @__PURE__ */ new WeakMap(),
4257
4824
  restoreGates: /* @__PURE__ */ new WeakMap(),
4825
+ externalRestorers: /* @__PURE__ */ new WeakMap(),
4258
4826
  restoreStates: /* @__PURE__ */ new WeakMap(),
4259
4827
  restoreErrors: /* @__PURE__ */ new WeakMap()
4260
4828
  };
4261
4829
  var runtime = runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL];
4830
+ runtime.externalRestorers ??= /* @__PURE__ */ new WeakMap();
4262
4831
  function registerLeaderSessionActions(sessionManager, actions) {
4263
4832
  runtime.actions.set(sessionManager, actions);
4264
4833
  runtime.restoreStates.set(sessionManager, false);
@@ -4274,6 +4843,12 @@ function registerLeaderRestoreGate(sessionManager, release) {
4274
4843
  function getLeaderRestoreGate(sessionManager) {
4275
4844
  return runtime.restoreGates.get(sessionManager);
4276
4845
  }
4846
+ function registerLeaderExternalRestorer(sessionManager, restorer) {
4847
+ runtime.externalRestorers.set(sessionManager, restorer);
4848
+ }
4849
+ function getLeaderExternalRestorer(sessionManager) {
4850
+ return runtime.externalRestorers.get(sessionManager);
4851
+ }
4277
4852
  function markLeaderSessionRestore(sessionManager, restored, error) {
4278
4853
  runtime.restoreStates.set(sessionManager, restored);
4279
4854
  if (error) runtime.restoreErrors.set(sessionManager, error);
@@ -4288,6 +4863,7 @@ function unregisterLeaderSessionActions(sessionManager, actions) {
4288
4863
  if (runtime.actions.get(sessionManager) !== actions) return;
4289
4864
  runtime.actions.delete(sessionManager);
4290
4865
  runtime.restoreGates.delete(sessionManager);
4866
+ runtime.externalRestorers.delete(sessionManager);
4291
4867
  runtime.restoreStates.delete(sessionManager);
4292
4868
  runtime.restoreErrors.delete(sessionManager);
4293
4869
  }
@@ -4323,6 +4899,7 @@ var LeaderRuntime = class {
4323
4899
  replacingSession = false;
4324
4900
  autoDispatch;
4325
4901
  autoResponsePending = false;
4902
+ postTimeoutAdvisoryDispatched = false;
4326
4903
  /** Set once the user was told that automatic handoffs are circuit-broken. */
4327
4904
  autoCircuitWarningShown = false;
4328
4905
  reset(ctx) {
@@ -4349,6 +4926,7 @@ var LeaderRuntime = class {
4349
4926
  this.turnDeferred = [];
4350
4927
  this.autoDispatch = void 0;
4351
4928
  this.autoResponsePending = false;
4929
+ this.postTimeoutAdvisoryDispatched = false;
4352
4930
  this.autoCircuitWarningShown = false;
4353
4931
  this.advisoryMilestones.clear();
4354
4932
  this.handoffBatch = void 0;
@@ -4462,27 +5040,51 @@ var LeaderRuntime = class {
4462
5040
  this.scheduleApplyDispatch(staged, ctx);
4463
5041
  return;
4464
5042
  }
5043
+ const externalPending = this.host.externalPendingCount?.(ctx) ?? 0;
5044
+ if (externalPending > 0) {
5045
+ return;
5046
+ }
4465
5047
  if (this.autoResponsePending && !this.staged && !this.applying) {
4466
5048
  this.autoResponsePending = false;
4467
5049
  if (!aborted) {
4468
5050
  await this.noteAutoFailure(ctx, "The model did not publish a leader handoff before the automatic turn ended.");
4469
5051
  this.advisoryMilestones.clear();
5052
+ this.postTimeoutAdvisoryDispatched = false;
4470
5053
  }
4471
5054
  }
4472
5055
  if (aborted || this.staged || this.applying) return;
4473
5056
  const config = this.settings.get().settings.leaderRecycling;
4474
- if (config.mode !== "auto") return;
5057
+ if (!config.enabled || config.mode !== "auto") return;
4475
5058
  const sessionId = ctx.sessionManager.getSessionId();
4476
- const advisory = await this.createAdvisory(ctx);
5059
+ const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
5060
+ const handoffToolName = activeExternal ? "swarm_leader_handoff" : "leader_handoff";
5061
+ let advisory = await this.createAdvisory(ctx);
5062
+ if (!advisory && this.host.isPostTimeoutHandoffPending?.(ctx) && !this.postTimeoutAdvisoryDispatched) {
5063
+ const canRecycle = await this.canRecycleLeader(ctx);
5064
+ if (canRecycle && this.isCurrent(ctx, sessionId) && !this.staged && !this.applying) {
5065
+ this.postTimeoutAdvisoryDispatched = true;
5066
+ advisory = {
5067
+ priority: "high",
5068
+ content: [
5069
+ "[Pi Agent Swarm post-timeout leader handoff]",
5070
+ "The previous mission countdown expired and closed in convergence mode.",
5071
+ "End this leader generation cleanly and hand off to a fresh successor session before starting a new mission countdown."
5072
+ ].join("\n")
5073
+ };
5074
+ }
5075
+ }
4477
5076
  if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
4478
5077
  const automatic = `${advisory.content}
4479
5078
 
4480
- Automatic leader recycling is enabled. Call leader_handoff now with all ten sections; do not answer the user first.`;
5079
+ Automatic leader recycling is enabled. Call ${handoffToolName} now with all ten sections; do not answer the user first.`;
4481
5080
  const dispatch = setTimeout(() => {
4482
5081
  if (this.autoDispatch === dispatch) this.autoDispatch = void 0;
4483
5082
  if (!this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
4484
5083
  try {
4485
5084
  this.autoResponsePending = true;
5085
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory", "leader-advisory")) {
5086
+ return;
5087
+ }
4486
5088
  this.pi.sendMessage(
4487
5089
  { customType: LEADER_ADVISORY_CUSTOM_TYPE, content: automatic, display: false },
4488
5090
  { deliverAs: "followUp", triggerTurn: true }
@@ -4496,6 +5098,20 @@ Automatic leader recycling is enabled. Call leader_handoff now with all ten sect
4496
5098
  if (this.autoDispatch) clearTimeout(this.autoDispatch);
4497
5099
  this.autoDispatch = dispatch;
4498
5100
  }
5101
+ /** True when leader recycling is enabled, persisted, within replacement budget, and not circuit-broken. */
5102
+ async canRecycleLeader(ctx) {
5103
+ const config = this.settings.get().settings.leaderRecycling;
5104
+ if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead) return false;
5105
+ if (!ctx.sessionManager.getSessionFile()) return false;
5106
+ const sessionId = ctx.sessionManager.getSessionId();
5107
+ const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
5108
+ if (!this.isCurrent(ctx, sessionId)) return false;
5109
+ if (lineage) {
5110
+ if (lineage.replacementCount >= config.maxReplacements) return false;
5111
+ if (config.mode === "auto" && (lineage.autoCircuitOpen || (lineage.autoFailures ?? 0) >= 3)) return false;
5112
+ }
5113
+ return true;
5114
+ }
4499
5115
  isLeaderReplacementShutdown() {
4500
5116
  return this.replacingSession;
4501
5117
  }
@@ -4596,8 +5212,20 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4596
5212
  }).catch(() => void 0);
4597
5213
  throw error;
4598
5214
  }
4599
- const usage = ctx.getContextUsage();
4600
- const analysis = usage ? analyzeSessionBranch(ctx.sessionManager.getBranch(), usage) : void 0;
5215
+ const externalCtx = this.host.externalLeaderContext?.(ctx);
5216
+ const analysis = externalCtx ? {
5217
+ status: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? "known" : "unknown",
5218
+ completedTurns: externalCtx.completedTurns,
5219
+ contextTokens: externalCtx.tokens,
5220
+ contextWindow: externalCtx.contextWindow,
5221
+ percent: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? externalCtx.tokens / externalCtx.contextWindow * 100 : null,
5222
+ oldToolOutputTokens: 0,
5223
+ toolResultCountOver2KB: 0,
5224
+ compactionCount: externalCtx.compactionCount
5225
+ } : (() => {
5226
+ const usage = ctx.getContextUsage();
5227
+ return usage ? analyzeSessionBranch(ctx.sessionManager.getBranch(), usage) : void 0;
5228
+ })();
4601
5229
  await transitionLeaderLineage(ctx.cwd, lineage.lineageId, "replacing", {
4602
5230
  expectedGeneration: lineage.currentGeneration,
4603
5231
  patch: {
@@ -4619,6 +5247,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4619
5247
  color: control.color,
4620
5248
  model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : void 0,
4621
5249
  thinkingLevel: this.pi.getThinkingLevel(),
5250
+ ...control.externalRuntime ? { externalRuntime: control.externalRuntime } : {},
4622
5251
  invite: control.invite,
4623
5252
  groupDirectory: control.groupDirectory,
4624
5253
  acceptsRequests: control.acceptsRequests,
@@ -4627,6 +5256,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4627
5256
  editorDraft: ctx.hasUI ? ctx.ui.getEditorText() : void 0
4628
5257
  });
4629
5258
  this.staged = { entry, applySent: false, applyAttempts: 0, automatic };
5259
+ this.host.clearExternalLeaderQueue?.(ctx);
4630
5260
  if (this.turnDeferred.length > 0) {
4631
5261
  entry.deferredFollowUps = [...entry.deferredFollowUps ?? [], ...this.turnDeferred];
4632
5262
  this.turnDeferred = [];
@@ -4652,10 +5282,15 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4652
5282
  if (trimmed.length > 0) throw new Error("Usage: /swarm handoff [--apply <token>]");
4653
5283
  if (!this.settings.get().settings.leaderRecycling.enabled) throw new Error("Leader recycling is disabled.");
4654
5284
  if (!this.host.leaderSnapshot(ctx).isLead) throw new Error("Only the lead session can hand off.");
5285
+ const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
5286
+ const handoffPrompt = activeExternal ? "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." : "The user requested a leader context handoff. Call leader_handoff now with all ten required sections, then stop. Do not answer the user first.";
5287
+ if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory", "leader-advisory")) {
5288
+ return;
5289
+ }
4655
5290
  await this.pi.sendMessage(
4656
5291
  {
4657
5292
  customType: LEADER_ADVISORY_CUSTOM_TYPE,
4658
- content: "The user requested a leader context handoff. Call leader_handoff now with all ten required sections, then stop. Do not answer the user first.",
5293
+ content: handoffPrompt,
4659
5294
  display: false
4660
5295
  },
4661
5296
  // Streaming uses AgentSession.followUp; false only appends a dormant custom message.
@@ -4766,7 +5401,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4766
5401
  leaderHandoffBridge.arm(token, previousSessionFile, Date.now(), LEADER_HANDOFF_BRIDGE_APPLY_TTL_MS);
4767
5402
  let handoff;
4768
5403
  try {
4769
- handoff = await readFile4(entry.handoffPath, "utf8");
5404
+ handoff = await readFile5(entry.handoffPath, "utf8");
4770
5405
  if (!hasRequiredHandoffSections(handoff)) throw new Error("required sections are missing");
4771
5406
  } catch (error) {
4772
5407
  throw new Error(`Cannot apply leader handoff: ${errorMessage(error)}`);
@@ -4782,6 +5417,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4782
5417
  generation,
4783
5418
  model,
4784
5419
  thinkingLevel,
5420
+ externalRuntime,
4785
5421
  editorDraft,
4786
5422
  nextAction,
4787
5423
  previousSessionId: previousLeaderSessionId,
@@ -4844,8 +5480,8 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4844
5480
  () => ({ status: "restored" }),
4845
5481
  (error) => ({ status: "failed", error })
4846
5482
  ),
4847
- new Promise((resolve13) => {
4848
- modelTimer = setTimeout(() => resolve13({ status: "timeout" }), LEADER_MODEL_RESTORE_TIMEOUT_MS);
5483
+ new Promise((resolve14) => {
5484
+ modelTimer = setTimeout(() => resolve14({ status: "timeout" }), LEADER_MODEL_RESTORE_TIMEOUT_MS);
4849
5485
  })
4850
5486
  ]);
4851
5487
  if (modelTimer) clearTimeout(modelTimer);
@@ -4876,6 +5512,33 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4876
5512
  await this.openSuccessorGate(replacedCtx);
4877
5513
  return;
4878
5514
  }
5515
+ if (externalRuntime) {
5516
+ const successorRestorer = getLeaderExternalRestorer(replacedCtx.sessionManager);
5517
+ const hostRestorer = this.host.restoreExternalLeader;
5518
+ const restoreFn = successorRestorer ? (ext, prompt) => successorRestorer(ext, prompt) : hostRestorer ? (ext, prompt) => hostRestorer(replacedCtx, ext, prompt) : void 0;
5519
+ if (restoreFn) {
5520
+ try {
5521
+ const externalKickoff = [
5522
+ "You are the successor leader in a fresh session. Read the leader handoff below and continue immediately.",
5523
+ "",
5524
+ handoff,
5525
+ "",
5526
+ `Continue with this exact next action: ${nextAction}`
5527
+ ].join("\n");
5528
+ kickoffQueued = true;
5529
+ await restoreFn(externalRuntime, externalKickoff);
5530
+ await this.openSuccessorGate(replacedCtx);
5531
+ } catch (error) {
5532
+ this.notify(
5533
+ replacedCtx,
5534
+ `Could not restore external leader runtime (${externalRuntime.runtimeId}): ${errorMessage(error)}`,
5535
+ "error"
5536
+ );
5537
+ await this.openSuccessorGate(replacedCtx);
5538
+ }
5539
+ return;
5540
+ }
5541
+ }
4879
5542
  try {
4880
5543
  const kickoff = replacedCtx.sendUserMessage(
4881
5544
  `You are the successor leader. Read the injected leader handoff. Continue with this exact next action: ${nextAction}`,
@@ -4954,12 +5617,34 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
4954
5617
  if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead || this.staged || this.applying) return void 0;
4955
5618
  if (!ctx.sessionManager.getSessionFile()) return void 0;
4956
5619
  const sessionId = ctx.sessionManager.getSessionId();
4957
- const usage = ctx.getContextUsage();
4958
- if (!usage) return void 0;
4959
- const branch = ctx.sessionManager.getBranch();
4960
5620
  const policy = leaderPolicy(config);
4961
- if (!shouldAnalyzeLeaderBranch(branch, usage, policy)) return void 0;
4962
- const analysis = analyzeSessionBranch(branch, usage);
5621
+ const externalCtx = this.host.externalLeaderContext?.(ctx);
5622
+ let analysis;
5623
+ if (externalCtx) {
5624
+ const extUsage = {
5625
+ tokens: externalCtx.tokens,
5626
+ contextWindow: externalCtx.contextWindow,
5627
+ percent: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? externalCtx.tokens / externalCtx.contextWindow * 100 : null
5628
+ };
5629
+ const hasPressure = shouldAnalyzeLeaderBranch([], extUsage, policy) || externalCtx.compactionCount >= 1 || externalCtx.tokens !== null && externalCtx.completedTurns >= 25 && externalCtx.tokens >= 35e3;
5630
+ if (!hasPressure) return void 0;
5631
+ analysis = {
5632
+ status: extUsage.tokens !== null && extUsage.contextWindow > 0 ? "known" : "unknown",
5633
+ completedTurns: externalCtx.completedTurns,
5634
+ contextTokens: extUsage.tokens,
5635
+ contextWindow: extUsage.contextWindow,
5636
+ percent: extUsage.percent,
5637
+ oldToolOutputTokens: 0,
5638
+ toolResultCountOver2KB: 0,
5639
+ compactionCount: externalCtx.compactionCount
5640
+ };
5641
+ } else {
5642
+ const usage = ctx.getContextUsage();
5643
+ if (!usage) return void 0;
5644
+ const branch = ctx.sessionManager.getBranch();
5645
+ if (!shouldAnalyzeLeaderBranch(branch, usage, policy)) return void 0;
5646
+ analysis = analyzeSessionBranch(branch, usage);
5647
+ }
4963
5648
  const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
4964
5649
  if (!this.isCurrent(ctx, sessionId)) return void 0;
4965
5650
  if (config.mode === "auto" && (lineage?.autoCircuitOpen || (lineage?.autoFailures ?? 0) >= 3)) {
@@ -5160,6 +5845,7 @@ function leaderPolicy(config) {
5160
5845
  softContextPercent: config.softContextPercent,
5161
5846
  softContextTokens: config.softContextTokens,
5162
5847
  highWaterPercent: config.highWaterPercent,
5848
+ ...config.highWaterTokens !== void 0 ? { highWaterTokens: config.highWaterTokens } : {},
5163
5849
  maxReplacements: config.maxReplacements
5164
5850
  };
5165
5851
  }
@@ -5167,6 +5853,247 @@ function errorMessage(error) {
5167
5853
  return error instanceof Error ? error.message : String(error);
5168
5854
  }
5169
5855
 
5856
+ // src/mission-badge.ts
5857
+ import { truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth2 } from "@earendil-works/pi-tui";
5858
+ var SHORT_BUDGET_SEC_MODE_MS = 3 * 6e4;
5859
+ var ACTIVE_SEC_SWITCH_SECONDS = 120;
5860
+ var CLOSING_WINDOW_MS = 5 * 6e4;
5861
+ var FINAL_FLASH_PERIOD_MS = 400;
5862
+ var MISSION_BADGE_TIER_MIN_WIDTH = Object.freeze({
5863
+ full: 51,
5864
+ L1: 40,
5865
+ L2: 27,
5866
+ L3: 18,
5867
+ L4: 13
5868
+ });
5869
+ function hexToRgb(hex) {
5870
+ return [
5871
+ Number.parseInt(hex.slice(1, 3), 16),
5872
+ Number.parseInt(hex.slice(3, 5), 16),
5873
+ Number.parseInt(hex.slice(5, 7), 16)
5874
+ ];
5875
+ }
5876
+ function rgbToHex(r, g, b) {
5877
+ return `#${[r, g, b].map(
5878
+ (v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")
5879
+ ).join("")}`;
5880
+ }
5881
+ function hexToHsl(hex) {
5882
+ const [r, g, b] = hexToRgb(hex).map((v) => v / 255);
5883
+ const max = Math.max(r, g, b);
5884
+ const min = Math.min(r, g, b);
5885
+ const l = (max + min) / 2;
5886
+ if (max === min) return [0, 0, l * 100];
5887
+ const d = max - min;
5888
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
5889
+ let h = 0;
5890
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
5891
+ else if (max === g) h = (b - r) / d + 2;
5892
+ else h = (r - g) / d + 4;
5893
+ return [h * 60, s * 100, l * 100];
5894
+ }
5895
+ function hslToHex(h, s, l) {
5896
+ const hue = (h % 360 + 360) % 360;
5897
+ const sat = s / 100;
5898
+ const lig = l / 100;
5899
+ const c = (1 - Math.abs(2 * lig - 1)) * sat;
5900
+ const x = c * (1 - Math.abs(hue / 60 % 2 - 1));
5901
+ const m = lig - c / 2;
5902
+ let r = 0;
5903
+ let g = 0;
5904
+ let b = 0;
5905
+ if (hue < 60) {
5906
+ r = c;
5907
+ g = x;
5908
+ } else if (hue < 120) {
5909
+ r = x;
5910
+ g = c;
5911
+ } else if (hue < 180) {
5912
+ g = c;
5913
+ b = x;
5914
+ } else if (hue < 240) {
5915
+ g = x;
5916
+ b = c;
5917
+ } else if (hue < 300) {
5918
+ r = x;
5919
+ b = c;
5920
+ } else {
5921
+ r = c;
5922
+ b = x;
5923
+ }
5924
+ return rgbToHex((r + m) * 255, (g + m) * 255, (b + m) * 255);
5925
+ }
5926
+ function shiftLightness(hex, deltaL) {
5927
+ const [h, s, l] = hexToHsl(hex);
5928
+ return hslToHex(h, s, Math.max(0, Math.min(100, l + deltaL)));
5929
+ }
5930
+ function derivePhase(main) {
5931
+ return {
5932
+ main,
5933
+ hi: shiftLightness(main, 18),
5934
+ sub: shiftLightness(main, -18)
5935
+ };
5936
+ }
5937
+ var PALETTE = {
5938
+ green: derivePhase("#41b883"),
5939
+ // Vue
5940
+ yellow: derivePhase("#ffc85a"),
5941
+ // ROLE_BADGE_BACKGROUND
5942
+ orange: derivePhase("#dea584"),
5943
+ // Rust
5944
+ red: derivePhase("#c22d40"),
5945
+ // Scala
5946
+ dangerBg: shiftLightness("#c22d40", -18)
5947
+ };
5948
+ var ACTIVE_STATUS_FULL = {
5949
+ healthy: " \u63A8\u9032 ACTIVE ",
5950
+ mid: " \u5DE1\u822A CRUISE ",
5951
+ closing: " \u53CE\u675F CLOSE "
5952
+ };
5953
+ var ACTIVE_STATUS_ZH = {
5954
+ healthy: " \u63A8\u9032 ",
5955
+ mid: " \u5DE1\u822A ",
5956
+ closing: " \u53CE\u675F "
5957
+ };
5958
+ function pickMissionBadgeTier(availableColumns) {
5959
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.full) return "full";
5960
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L1) return "L1";
5961
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L2) return "L2";
5962
+ if (availableColumns >= MISSION_BADGE_TIER_MIN_WIDTH.L3) return "L3";
5963
+ return "L4";
5964
+ }
5965
+ function clamp01(value) {
5966
+ if (!Number.isFinite(value)) return 0;
5967
+ return Math.max(0, Math.min(1, value));
5968
+ }
5969
+ function formatMmSs(remainMs) {
5970
+ const sec = Math.max(0, Math.ceil(remainMs / 1e3));
5971
+ const mm = String(Math.floor(sec / 60)).padStart(2, "0");
5972
+ const ss = String(sec % 60).padStart(2, "0");
5973
+ return `${mm}:${ss}`;
5974
+ }
5975
+ function flashBadge(text, now) {
5976
+ const on = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
5977
+ return on ? badge(text, PALETTE.dangerBg, "#ffffff") : badge(text, PALETTE.red.hi, PALETTE.dangerBg);
5978
+ }
5979
+ function renderActiveBadge(budgetMs, remainMs, tier) {
5980
+ const safeBudget = Math.max(1, budgetMs);
5981
+ const frac = clamp01(remainMs / safeBudget);
5982
+ const stage = frac <= 0.25 || safeBudget > CLOSING_WINDOW_MS && remainMs <= CLOSING_WINDOW_MS ? "closing" : frac <= 0.5 ? "mid" : "healthy";
5983
+ const phase = stage === "healthy" ? PALETTE.green : stage === "mid" ? PALETTE.yellow : PALETTE.orange;
5984
+ const fg = contrastTextColor(phase.main);
5985
+ const remainSec = Math.max(0, Math.ceil(remainMs / 1e3));
5986
+ const secMode = safeBudget <= SHORT_BUDGET_SEC_MODE_MS || remainSec < ACTIVE_SEC_SWITCH_SECONDS;
5987
+ const mainTime = secMode ? formatMmSs(remainMs) : `${Math.max(1, Math.ceil(remainMs / 6e4))}m`;
5988
+ if (tier === "L4") {
5989
+ return badge(` SWM ${mainTime} `, phase.main, fg);
5990
+ }
5991
+ const cells = tier === "full" ? 10 : tier === "L1" ? 6 : tier === "L2" ? 4 : 2;
5992
+ const filled = Math.max(1, Math.round(frac * cells));
5993
+ let bar = "";
5994
+ for (let i = 0; i < cells; i += 1) {
5995
+ bar += colorize(i < filled ? "\u25B0" : "\u25B1", i < filled ? phase.main : phase.sub);
5996
+ }
5997
+ const sym = colorize("\u25B8", phase.hi);
5998
+ if (tier === "L3") {
5999
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)}`;
6000
+ }
6001
+ if (tier === "L2") {
6002
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_ZH[stage], phase.main, fg)}`;
6003
+ }
6004
+ if (tier === "L1") {
6005
+ return `${badge(" SWM ", phase.main, fg)} ${bar} ${sym} ${badge(` ${mainTime} `, phase.main, fg)} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
6006
+ }
6007
+ const head = badge(" SWM \u8702\u7FA4 ", phase.main, fg);
6008
+ const budgetMin = Math.max(1, Math.round(safeBudget / 6e4));
6009
+ const timeBadge = secMode ? badge(` ${mainTime} `, phase.main, fg) : badge(` ${mainTime}`, phase.main, fg) + badge(`/${budgetMin}m `, phase.main, phase.sub);
6010
+ return `${head} ${bar} ${sym} ${timeBadge} ${badge(ACTIVE_STATUS_FULL[stage], phase.main, fg)}`;
6011
+ }
6012
+ function renderConvergingBadge(graceTotalMs, remainMs, tier) {
6013
+ const safeTotal = Math.max(1, graceTotalMs);
6014
+ const frac = clamp01(remainMs / safeTotal);
6015
+ const mainTime = formatMmSs(remainMs);
6016
+ const orangeFg = contrastTextColor(PALETTE.orange.main);
6017
+ const renderBar = (cells) => {
6018
+ const left = Math.max(1, Math.round(frac * cells));
6019
+ let out = "";
6020
+ for (let i = 0; i < cells; i += 1) {
6021
+ out += colorize(i < left ? "\u2571" : "\u2504", i < left ? PALETTE.red.hi : PALETTE.red.sub);
6022
+ }
6023
+ return out;
6024
+ };
6025
+ if (tier === "L4") {
6026
+ return badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff") + badge(` ${mainTime} `, PALETTE.red.main, "#ffffff");
6027
+ }
6028
+ if (tier === "L3") {
6029
+ return `${badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff")} ${renderBar(2)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
6030
+ }
6031
+ if (tier === "L2") {
6032
+ const head2 = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6033
+ return `${head2} ${renderBar(4)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")}`;
6034
+ }
6035
+ if (tier === "L1") {
6036
+ const head2 = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6037
+ return `${head2} ${renderBar(6)} ${colorize("\u2298", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" \u53CE\u6582 ", PALETTE.dangerBg, "#ffffff")}`;
6038
+ }
6039
+ const head = badge(" SWM ", PALETTE.orange.main, orangeFg) + badge(" \u9396\u9598 ", PALETTE.dangerBg, "#ffffff");
6040
+ return `${head} ${renderBar(10)} ${colorize("\u2298", PALETTE.red.hi)} ${badge(` ${mainTime} `, PALETTE.red.main, "#ffffff")} ${badge(" \u53CE\u6582 WRAP ", PALETTE.dangerBg, "#ffffff")}`;
6041
+ }
6042
+ function renderFinalBadge(remainMs, now, tier) {
6043
+ const mainTime = formatMmSs(remainMs);
6044
+ const blink = Math.floor(now / FINAL_FLASH_PERIOD_MS) % 2 === 0;
6045
+ const xColor = blink ? PALETTE.red.hi : PALETTE.dangerBg;
6046
+ const xBar = (cells) => colorize("\u2573".repeat(cells), xColor);
6047
+ if (tier === "L4") {
6048
+ return flashBadge(` FINAL ${mainTime} `, now);
6049
+ }
6050
+ if (tier === "L3") {
6051
+ return `${flashBadge(" FINAL ", now)} ${xBar(2)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
6052
+ }
6053
+ if (tier === "L2") {
6054
+ const head2 = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
6055
+ return `${head2} ${xBar(4)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")}`;
6056
+ }
6057
+ const head = badge(" SWM ", PALETTE.red.main, "#ffffff") + flashBadge(" FINAL ", now);
6058
+ return `${head} ${xBar(6)} ${badge(` ${mainTime} `, PALETTE.dangerBg, "#ffffff")} ${flashBadge(" AUTO ", now)}`;
6059
+ }
6060
+ function nextMissionTickDelayMs(record3, now) {
6061
+ if (!isMissionLive(record3)) return void 0;
6062
+ if (record3.state === "final_wrap_up") return FINAL_FLASH_PERIOD_MS;
6063
+ if (record3.state === "converging") return 1e3;
6064
+ const budgetMs = Math.max(1, record3.deadlineAt - record3.startedAt);
6065
+ const remainMs = Math.max(0, record3.deadlineAt - now);
6066
+ if (budgetMs <= SHORT_BUDGET_SEC_MODE_MS || remainMs <= 125e3) return 1e3;
6067
+ return Math.min(15e3, Math.max(1e3, remainMs - 12e4));
6068
+ }
6069
+ function formatMissionStatusBadge(record3, now, options = {}) {
6070
+ if (!isMissionLive(record3)) return void 0;
6071
+ const availableColumns = options.availableColumns ?? 80;
6072
+ const tier = pickMissionBadgeTier(availableColumns);
6073
+ const wrapUpGraceMs = options.wrapUpGraceMs ?? DEFAULT_MISSION_COUNTDOWN_SETTINGS.wrapUpGraceMs;
6074
+ const finalWrapUpMs = options.finalWrapUpMs ?? Math.max(MIN_FINAL_WRAP_UP_MS, Math.round(wrapUpGraceMs * FINAL_WRAP_UP_AUTO_CLOSE_FACTOR));
6075
+ let rendered;
6076
+ if (record3.state === "final_wrap_up") {
6077
+ const finalTargetAt = (record3.finalWrapUpAt ?? now) + finalWrapUpMs;
6078
+ rendered = renderFinalBadge(Math.max(0, finalTargetAt - now), now, tier);
6079
+ } else if (record3.state === "converging") {
6080
+ const graceTargetAt = (record3.convergingAt ?? record3.deadlineAt) + wrapUpGraceMs;
6081
+ rendered = renderConvergingBadge(wrapUpGraceMs, Math.max(0, graceTargetAt - now), tier);
6082
+ } else {
6083
+ const budgetMs = Math.max(1, record3.deadlineAt - record3.startedAt);
6084
+ const remainMs = Math.max(0, record3.deadlineAt - now);
6085
+ if (remainMs <= 0) {
6086
+ rendered = renderConvergingBadge(wrapUpGraceMs, wrapUpGraceMs, tier);
6087
+ } else {
6088
+ rendered = renderActiveBadge(budgetMs, remainMs, tier);
6089
+ }
6090
+ }
6091
+ if (availableColumns > 0 && visibleWidth2(rendered) > availableColumns) {
6092
+ return truncateToWidth2(rendered, availableColumns, "\u2026");
6093
+ }
6094
+ return rendered;
6095
+ }
6096
+
5170
6097
  // src/model-catalog.ts
5171
6098
  var AGY_MODEL_ID_RE = /^[A-Za-z0-9._:-]{1,160}$/u;
5172
6099
  function parseModelRef(raw) {
@@ -5309,7 +6236,7 @@ function isLikelyLocalProvider(provider) {
5309
6236
 
5310
6237
  // src/org.ts
5311
6238
  import { existsSync as existsSync2, readFileSync } from "node:fs";
5312
- import { join as join9, resolve as resolve7 } from "node:path";
6239
+ import { join as join10, resolve as resolve8 } from "node:path";
5313
6240
  var VALID_ROLES2 = /* @__PURE__ */ new Set(["lead", "implementer", "researcher", "reviewer"]);
5314
6241
  var VALID_INTENTS = /* @__PURE__ */ new Set(["assign", "evidence", "verdict", "handoff", "escalate"]);
5315
6242
  var FORBIDDEN_ROLE_KEYS = /* @__PURE__ */ new Set(["cwd", "defaultCwd", "workingDirectory", "workdir"]);
@@ -5328,7 +6255,7 @@ var DEFAULT_STAR_ORG = Object.freeze({
5328
6255
  edges: []
5329
6256
  });
5330
6257
  function orgConfigPathForProject(projectRoot) {
5331
- return join9(resolve7(projectRoot), WORKER_RECYCLING_DIRECTORY, "org.json");
6258
+ return join10(resolve8(projectRoot), WORKER_RECYCLING_DIRECTORY, "org.json");
5332
6259
  }
5333
6260
  function validateOrgDocument(raw) {
5334
6261
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
@@ -5340,6 +6267,13 @@ function validateOrgDocument(raw) {
5340
6267
  }
5341
6268
  const version = typeof obj.version === "string" && obj.version.trim().length > 0 ? obj.version.trim() : "v1-custom";
5342
6269
  const strictTaskId = obj.strictTaskId === true;
6270
+ let reviewPolicy;
6271
+ if (obj.reviewPolicy !== void 0) {
6272
+ if (obj.reviewPolicy !== "off" && obj.reviewPolicy !== "suggest" && obj.reviewPolicy !== "required") {
6273
+ throw new Error(`org.json has invalid reviewPolicy "${String(obj.reviewPolicy)}"`);
6274
+ }
6275
+ reviewPolicy = obj.reviewPolicy;
6276
+ }
5343
6277
  if (!obj.roles || typeof obj.roles !== "object" || Array.isArray(obj.roles)) {
5344
6278
  throw new Error("org.json requires a roles object");
5345
6279
  }
@@ -5423,6 +6357,7 @@ function validateOrgDocument(raw) {
5423
6357
  schemaVersion: 1,
5424
6358
  version,
5425
6359
  strictTaskId,
6360
+ ...reviewPolicy ? { reviewPolicy } : {},
5426
6361
  roles,
5427
6362
  edges
5428
6363
  };
@@ -5672,7 +6607,7 @@ function probeCommand(resourceId, argv, timeoutMs, startedAt, signal) {
5672
6607
  // src/profiles.ts
5673
6608
  import { existsSync as existsSync3, lstatSync, readdirSync, readFileSync as readFileSync3, realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
5674
6609
  import { homedir } from "node:os";
5675
- import { basename as basename5, dirname as dirname5, join as join11, relative as relative5, resolve as resolve9 } from "node:path";
6610
+ import { basename as basename5, dirname as dirname5, join as join12, relative as relative5, resolve as resolve10 } from "node:path";
5676
6611
  import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
5677
6612
  var READONLY_EXCLUDED_TOOLS = ["edit", "write", "bash"];
5678
6613
  var ALLOWED_TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
@@ -5718,15 +6653,15 @@ var BUILTIN_DEFAULT_PROFILE = Object.freeze({
5718
6653
  });
5719
6654
  function defaultProfilesDirectory(configuredDir) {
5720
6655
  if (configuredDir?.trim()) {
5721
- return resolve9(expandHome(configuredDir.trim()));
6656
+ return resolve10(expandHome(configuredDir.trim()));
5722
6657
  }
5723
- return join11(getAgentDir2(), "profiles");
6658
+ return join12(getAgentDir2(), "profiles");
5724
6659
  }
5725
6660
  function defaultMcpProfilesDirectory(env = process.env) {
5726
6661
  if (env.PI_MCP_PROFILES_DIR?.trim()) {
5727
- return resolve9(expandHome(env.PI_MCP_PROFILES_DIR.trim()));
6662
+ return resolve10(expandHome(env.PI_MCP_PROFILES_DIR.trim()));
5728
6663
  }
5729
- return join11(dirname5(getAgentDir2()), "mcp-profiles");
6664
+ return join12(dirname5(getAgentDir2()), "mcp-profiles");
5730
6665
  }
5731
6666
  function isReadOnlyRole(role) {
5732
6667
  return role === "reviewer" || role === "researcher";
@@ -5840,7 +6775,7 @@ function loadProfileCatalog(options = {}) {
5840
6775
  continue;
5841
6776
  }
5842
6777
  if (allowedSet && !allowedSet.has(expectedId)) continue;
5843
- const candidatePath = join11(realProfilesDir, filename);
6778
+ const candidatePath = join12(realProfilesDir, filename);
5844
6779
  try {
5845
6780
  const realFile = realpathSync2(candidatePath);
5846
6781
  const rel = relative5(realProfilesDir, realFile);
@@ -5886,7 +6821,7 @@ function resolveWorkerProfile(profileIdInput, role, options = {}) {
5886
6821
  const resources = readOnly ? [] : doc.resources.map((r) => ({ ...r }));
5887
6822
  const mcpExtensionPaths = [];
5888
6823
  for (const mcpName of mcpProfiles) {
5889
- const candidate = join11(mcpProfilesDir, `${mcpName}.ts`);
6824
+ const candidate = join12(mcpProfilesDir, `${mcpName}.ts`);
5890
6825
  if (existsSync3(candidate)) {
5891
6826
  mcpExtensionPaths.push(candidate);
5892
6827
  }
@@ -5992,7 +6927,7 @@ function detectProjectProfileHints(cwd, catalog) {
5992
6927
  }
5993
6928
  function expandHome(rawPath, home = homedir()) {
5994
6929
  if (rawPath === "~") return home;
5995
- if (rawPath.startsWith("~/")) return join11(home, rawPath.slice(2));
6930
+ if (rawPath.startsWith("~/")) return join12(home, rawPath.slice(2));
5996
6931
  return rawPath;
5997
6932
  }
5998
6933
  function expandSkillEntry(entry, home) {
@@ -6008,7 +6943,7 @@ function expandSkillEntry(entry, home) {
6008
6943
  }
6009
6944
  const dirs = [];
6010
6945
  for (const entryItem of entries) {
6011
- const candidate = join11(parent, entryItem.name);
6946
+ const candidate = join12(parent, entryItem.name);
6012
6947
  let isDir = entryItem.isDirectory();
6013
6948
  if (!isDir && entryItem.isSymbolicLink()) {
6014
6949
  try {
@@ -6017,14 +6952,14 @@ function expandSkillEntry(entry, home) {
6017
6952
  isDir = false;
6018
6953
  }
6019
6954
  }
6020
- if (isDir && existsSync3(join11(candidate, "SKILL.md"))) {
6955
+ if (isDir && existsSync3(join12(candidate, "SKILL.md"))) {
6021
6956
  dirs.push(candidate);
6022
6957
  }
6023
6958
  }
6024
6959
  dirs.sort((a, b) => basename5(a).localeCompare(basename5(b)));
6025
6960
  return dirs;
6026
6961
  }
6027
- if (existsSync3(join11(expanded, "SKILL.md"))) {
6962
+ if (existsSync3(join12(expanded, "SKILL.md"))) {
6028
6963
  return [expanded];
6029
6964
  }
6030
6965
  return [];
@@ -6160,8 +7095,8 @@ function reloadHandoffs() {
6160
7095
 
6161
7096
  // src/resource-lease.ts
6162
7097
  import { createHash as createHash3 } from "node:crypto";
6163
- import { chmod as chmod4, mkdir as mkdir6, open as open5, readFile as readFile5, rm as rm7, writeFile as writeFile4 } from "node:fs/promises";
6164
- import { join as join12 } from "node:path";
7098
+ import { chmod as chmod4, mkdir as mkdir6, open as open5, readFile as readFile6, rm as rm8, writeFile as writeFile4 } from "node:fs/promises";
7099
+ import { join as join13 } from "node:path";
6165
7100
  function defaultIsProcessAlive(pid) {
6166
7101
  if (!Number.isInteger(pid) || pid <= 0) return false;
6167
7102
  try {
@@ -6187,7 +7122,7 @@ var ResourceLeaseManager = class {
6187
7122
  now;
6188
7123
  heldByLeaseId = /* @__PURE__ */ new Map();
6189
7124
  constructor(options = {}) {
6190
- this.baseDirectory = join12(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "resource-leases");
7125
+ this.baseDirectory = join13(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "resource-leases");
6191
7126
  this.isProcessAlive = options.isProcessAlive ?? defaultIsProcessAlive;
6192
7127
  this.pid = options.pid ?? process.pid;
6193
7128
  this.now = options.now ?? Date.now;
@@ -6226,7 +7161,7 @@ var ResourceLeaseManager = class {
6226
7161
  const keyHash = createHash3("sha256").update(spec.id).digest("hex").slice(0, 24);
6227
7162
  let lastHolderDesc = "another active worker";
6228
7163
  for (let slot = 0; slot < spec.concurrency; slot += 1) {
6229
- const lockPath = join12(this.baseDirectory, `res-${keyHash}-s${slot}.lock`);
7164
+ const lockPath = join13(this.baseDirectory, `res-${keyHash}-s${slot}.lock`);
6230
7165
  const record3 = {
6231
7166
  resourceId: spec.id,
6232
7167
  slot,
@@ -6250,7 +7185,7 @@ var ResourceLeaseManager = class {
6250
7185
  }
6251
7186
  const existing = await this.readLock(lockPath);
6252
7187
  if (!existing) {
6253
- await rm7(lockPath, { force: true }).catch(() => void 0);
7188
+ await rm8(lockPath, { force: true }).catch(() => void 0);
6254
7189
  if (await this.tryCreateExclusive(lockPath, record3)) {
6255
7190
  const lease = {
6256
7191
  resourceId: spec.id,
@@ -6279,7 +7214,7 @@ var ResourceLeaseManager = class {
6279
7214
  return lease;
6280
7215
  }
6281
7216
  if (!this.isProcessAlive(existing.ownerPid)) {
6282
- await rm7(lockPath, { force: true }).catch(() => void 0);
7217
+ await rm8(lockPath, { force: true }).catch(() => void 0);
6283
7218
  if (await this.tryCreateExclusive(lockPath, record3)) {
6284
7219
  const lease = {
6285
7220
  resourceId: spec.id,
@@ -6305,7 +7240,7 @@ var ResourceLeaseManager = class {
6305
7240
  if (existing && existing.leaseId !== lease.leaseId) {
6306
7241
  return;
6307
7242
  }
6308
- await rm7(lease.lockPath, { force: true }).catch(() => void 0);
7243
+ await rm8(lease.lockPath, { force: true }).catch(() => void 0);
6309
7244
  }
6310
7245
  async tryCreateExclusive(lockPath, record3) {
6311
7246
  let handle;
@@ -6326,7 +7261,7 @@ var ResourceLeaseManager = class {
6326
7261
  }
6327
7262
  async readLock(lockPath) {
6328
7263
  try {
6329
- const parsed = JSON.parse(await readFile5(lockPath, "utf8"));
7264
+ const parsed = JSON.parse(await readFile6(lockPath, "utf8"));
6330
7265
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
6331
7266
  const rec = parsed;
6332
7267
  if (typeof rec.resourceId !== "string" || typeof rec.slot !== "number" || typeof rec.ownerPid !== "number" || typeof rec.leaseId !== "string") {
@@ -6477,11 +7412,72 @@ var ReviewerVerdictStore = class {
6477
7412
  }
6478
7413
  return void 0;
6479
7414
  }
7415
+ hasPassingVerdict(taskId) {
7416
+ return this.records.some((rec) => rec.taskId === taskId && rec.verdict.verdict === "pass");
7417
+ }
7418
+ consecutiveFailsForTask(taskId) {
7419
+ let count = 0;
7420
+ for (let i = this.records.length - 1; i >= 0; i -= 1) {
7421
+ const rec = this.records[i];
7422
+ if (rec?.taskId !== taskId) continue;
7423
+ if (rec.verdict.verdict === "fail") {
7424
+ count += 1;
7425
+ } else {
7426
+ break;
7427
+ }
7428
+ }
7429
+ return count;
7430
+ }
6480
7431
  clear() {
6481
7432
  this.records.length = 0;
6482
7433
  this.byMessageId.clear();
6483
7434
  }
6484
7435
  };
7436
+ var MAX_CONSECUTIVE_REVIEWER_FAILS = 2;
7437
+ function inferModelFamily(modelRef) {
7438
+ const lower = modelRef.toLowerCase();
7439
+ if (lower.includes("claude")) return "claude";
7440
+ if (lower.includes("gemini")) return "gemini";
7441
+ if (lower.includes("deepseek")) return "deepseek";
7442
+ if (lower.includes("kimi") || lower.includes("moonshot") || /\/k3(\b|[-_.])/u.test(lower)) return "kimi";
7443
+ if (lower.includes("qwen")) return "qwen";
7444
+ if (lower.includes("glm")) return "glm";
7445
+ if (lower.includes("gpt") || lower.includes("o1") || lower.includes("o3") || lower.includes("o4")) return "openai";
7446
+ const stripped = lower.replace(/^(?:pi|agy):/u, "");
7447
+ return stripped.split(/[/:]/u)[0] || "unknown";
7448
+ }
7449
+ function suggestCrossFamilyReviewerModels(implementerModelRef, candidates) {
7450
+ const implFamily = implementerModelRef ? inferModelFamily(implementerModelRef) : "";
7451
+ const seenFamilies = /* @__PURE__ */ new Set();
7452
+ const picked = [];
7453
+ for (const candidate of candidates) {
7454
+ if (candidate.sawQuota) continue;
7455
+ const family = inferModelFamily(candidate.ref);
7456
+ if (implFamily && family === implFamily) continue;
7457
+ if (seenFamilies.has(family)) continue;
7458
+ seenFamilies.add(family);
7459
+ picked.push(candidate.ref);
7460
+ if (picked.length >= 2) break;
7461
+ }
7462
+ return picked;
7463
+ }
7464
+ function formatReviewGovernanceReminder(params) {
7465
+ const modelHint = params.suggestedReviewerModels.length > 0 ? ` Recommended cross-family reviewer model(s): ${params.suggestedReviewerModels.join(" or ")}.` : "";
7466
+ if (params.policy === "required") {
7467
+ return `
7468
+
7469
+ [Swarm Governance \u2014 Review Required] Implementer ${params.implementerName} reported results for task "${params.taskId}", and no independent reviewer "pass" verdict is recorded yet. Before closing out this task, spawn an independent read-only reviewer (role="reviewer") to verify real files/diffs.${modelHint}`;
7470
+ }
7471
+ return `
7472
+
7473
+ [Swarm Governance \u2014 Review Suggested] Implementer ${params.implementerName} reported results for task "${params.taskId}" with no independent reviewer verdict yet. For substantive code/doc/hardware changes, consider spawning role="reviewer" in a fresh read-only context.${modelHint}`;
7474
+ }
7475
+ function formatReviewerEscalationNotice(params) {
7476
+ const issueText = params.blockingIssues.length > 0 ? ` Blocking issues: ${params.blockingIssues.slice(0, 5).join("; ")}.` : "";
7477
+ return `
7478
+
7479
+ [Swarm Escalation \u2014 Reviewer Circuit Open] Task "${params.taskId}" has received ${params.consecutiveFails} consecutive reviewer "fail" verdicts.${issueText} Stop the implementer/reviewer retry loop and escalate to the human user for a decision.`;
7480
+ }
6485
7481
  function stringList(value, field) {
6486
7482
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
6487
7483
  throw new Error(`Reviewer verdict ${field} must be an array of strings`);
@@ -6672,12 +7668,12 @@ function quoteI3Value(value) {
6672
7668
  }
6673
7669
  async function abortableSleep(milliseconds, signal) {
6674
7670
  throwIfAborted3(signal, "Pi Agent Swarm i3 workspace wait was aborted");
6675
- await new Promise((resolve13, reject) => {
7671
+ await new Promise((resolve14, reject) => {
6676
7672
  const finish = (error) => {
6677
7673
  clearTimeout(timer);
6678
7674
  signal?.removeEventListener("abort", abort);
6679
7675
  if (error) reject(error);
6680
- else resolve13();
7676
+ else resolve14();
6681
7677
  };
6682
7678
  const timer = setTimeout(() => finish(), milliseconds);
6683
7679
  const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
@@ -6717,9 +7713,9 @@ function createTerminalLaunchError(message, splitCreated, terminalId) {
6717
7713
  // src/transport.ts
6718
7714
  import { randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
6719
7715
  import { constants as constants3 } from "node:fs";
6720
- import { chmod as chmod5, lstat as lstat6, open as open7, opendir as opendir2, rm as rm8 } from "node:fs/promises";
7716
+ import { chmod as chmod5, lstat as lstat6, open as open7, opendir as opendir2, rm as rm9 } from "node:fs/promises";
6721
7717
  import { createServer as createServer2 } from "node:net";
6722
- import { basename as basename6, dirname as dirname6, join as join13, resolve as resolve10 } from "node:path";
7718
+ import { basename as basename6, dirname as dirname6, join as join14, resolve as resolve11 } from "node:path";
6723
7719
 
6724
7720
  // src/transport-io.ts
6725
7721
  import { constants as constants2 } from "node:fs";
@@ -7363,7 +8359,7 @@ var SwarmTransport = class {
7363
8359
  }
7364
8360
  try {
7365
8361
  records.push(
7366
- await readManifest2(paths.directory, resolve10(paths.directory, entry.name), endpointId, this.options.group)
8362
+ await readManifest2(paths.directory, resolve11(paths.directory, entry.name), endpointId, this.options.group)
7367
8363
  );
7368
8364
  } catch {
7369
8365
  addIssue(issues, { code: "invalid_manifest", endpointId });
@@ -7436,11 +8432,11 @@ var SwarmTransport = class {
7436
8432
  try {
7437
8433
  const current = await readBoundedUtf8(record3.manifestPath, MAX_MANIFEST_BYTES);
7438
8434
  if (current !== record3.raw) return;
7439
- await rm8(record3.manifestPath, { force: true });
8435
+ await rm9(record3.manifestPath, { force: true });
7440
8436
  if (record3.socketIdentity) {
7441
8437
  const info = await lstat6(record3.socketPath, { bigint: true }).catch(() => void 0);
7442
8438
  if (info?.isSocket() && info.dev === record3.socketIdentity.dev && info.ino === record3.socketIdentity.ino) {
7443
- await rm8(record3.socketPath, { force: true });
8439
+ await rm9(record3.socketPath, { force: true });
7444
8440
  }
7445
8441
  }
7446
8442
  } catch {
@@ -7500,8 +8496,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
7500
8496
  expectedGroupId: group.id,
7501
8497
  expectedEndpointId: endpointId
7502
8498
  });
7503
- const socketPath = join13(directory, manifest.socketName);
7504
- if (dirname6(resolve10(socketPath)) !== resolve10(directory)) {
8499
+ const socketPath = join14(directory, manifest.socketName);
8500
+ if (dirname6(resolve11(socketPath)) !== resolve11(directory)) {
7505
8501
  throw new Error("Pi Agent Swarm endpoint socket path is invalid");
7506
8502
  }
7507
8503
  const socketInfo = await lstat6(socketPath, { bigint: true }).catch(() => void 0);
@@ -7603,8 +8599,8 @@ function assertPositiveDuration2(value, label) {
7603
8599
  // src/worktree.ts
7604
8600
  import { execFile as execFile2 } from "node:child_process";
7605
8601
  import { createHash as createHash4 } from "node:crypto";
7606
- import { chmod as chmod6, mkdir as mkdir7, rm as rm9 } from "node:fs/promises";
7607
- import { join as join14, resolve as resolve11 } from "node:path";
8602
+ import { chmod as chmod6, mkdir as mkdir7, rm as rm10 } from "node:fs/promises";
8603
+ import { join as join15, resolve as resolve12 } from "node:path";
7608
8604
  import { promisify as promisify2 } from "node:util";
7609
8605
  var execFileAsync = promisify2(execFile2);
7610
8606
  var SAFE_TASK_ID_RE = /^[A-Za-z0-9._-]{1,128}$/u;
@@ -7614,7 +8610,7 @@ async function resolveGitTopLevel(cwd) {
7614
8610
  timeout: 5e3
7615
8611
  });
7616
8612
  const root = stdout.trim();
7617
- return root ? resolve11(root) : void 0;
8613
+ return root ? resolve12(root) : void 0;
7618
8614
  } catch {
7619
8615
  return void 0;
7620
8616
  }
@@ -7627,11 +8623,11 @@ async function provisionTaskWorktree(options) {
7627
8623
  if (!repoRoot) {
7628
8624
  throw new Error(`Worktree isolation requires "${options.cwd}" to be inside a git repository`);
7629
8625
  }
7630
- const worktreesBase = join14(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "worktrees");
8626
+ const worktreesBase = join15(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "worktrees");
7631
8627
  await mkdir7(worktreesBase, { recursive: true, mode: 448 });
7632
8628
  await chmod6(worktreesBase, 448).catch(() => void 0);
7633
8629
  const repoHash = createHash4("sha256").update(repoRoot).digest("hex").slice(0, 12);
7634
- const worktreePath = join14(worktreesBase, `${repoHash}-${options.taskId}`);
8630
+ const worktreePath = join15(worktreesBase, `${repoHash}-${options.taskId}`);
7635
8631
  await execFileAsync("git", ["-C", repoRoot, "worktree", "add", "--detach", worktreePath, "HEAD"], {
7636
8632
  timeout: 15e3
7637
8633
  });
@@ -7654,7 +8650,7 @@ async function cleanupTaskWorktree(repoRoot, worktreePath) {
7654
8650
  timeout: 1e4
7655
8651
  });
7656
8652
  } catch {
7657
- await rm9(worktreePath, { recursive: true, force: true }).catch(() => void 0);
8653
+ await rm10(worktreePath, { recursive: true, force: true }).catch(() => void 0);
7658
8654
  await execFileAsync("git", ["-C", repoRoot, "worktree", "prune"], { timeout: 1e4 }).catch(() => void 0);
7659
8655
  }
7660
8656
  }
@@ -7662,6 +8658,9 @@ async function cleanupTaskWorktree(repoRoot, worktreePath) {
7662
8658
  // src/swarm-controller.ts
7663
8659
  var STATUS_KEY = "swarm";
7664
8660
  var ROSTER_STATUS_KEY = "swarm-roster";
8661
+ var LEADER_GEN_STATUS_KEY = "swarm-leader-gen";
8662
+ var MISSION_STATUS_KEY = "swarm-mission";
8663
+ var MISSION_CUSTOM_TYPE = "pi-agent-swarm:mission-timeout";
7665
8664
  var DEFAULT_LAUNCH_TIMEOUT_MS = 15e3;
7666
8665
  var DEFAULT_POLL_INTERVAL_MS2 = 100;
7667
8666
  var RELOAD_HANDOFF_TTL_MS = 3e4;
@@ -7702,6 +8701,51 @@ var SwarmController = class {
7702
8701
  }
7703
8702
  }
7704
8703
  },
8704
+ onDirectState: (state) => {
8705
+ const activeSid = this.activeContext?.sessionManager.getSessionId();
8706
+ if (state.sessionId && activeSid && state.sessionId !== activeSid) return;
8707
+ if (state.active) {
8708
+ this.activeDirectRuntime = state;
8709
+ this.cacheWarmingPolicy.resetWaitWindow();
8710
+ } else if (!this.activeDirectRuntime || this.activeDirectRuntime.runtimeId === state.runtimeId) {
8711
+ this.activeDirectRuntime = void 0;
8712
+ this.externalLeaderUsage = void 0;
8713
+ }
8714
+ },
8715
+ onContextUsage: (report) => {
8716
+ const ctx = this.activeContext;
8717
+ if (!ctx) return;
8718
+ const activeSid = ctx.sessionManager.getSessionId();
8719
+ if (report.sessionId && report.sessionId !== activeSid) return;
8720
+ this.externalLeaderUsage = report;
8721
+ if (this.activeDirectRuntime && report.pendingCount !== void 0) {
8722
+ this.activeDirectRuntime = {
8723
+ ...this.activeDirectRuntime,
8724
+ pendingCount: report.pendingCount,
8725
+ updatedAt: report.updatedAt
8726
+ };
8727
+ }
8728
+ if (report.settled) {
8729
+ const totalTokens = report.usage?.totalTokens ?? (typeof report.usage?.inputTokens === "number" || typeof report.usage?.outputTokens === "number" ? (report.usage?.inputTokens ?? 0) + (report.usage?.outputTokens ?? 0) : report.tokens);
8730
+ this.recordLedger(ctx.cwd, {
8731
+ event: "run_completed",
8732
+ task_id: `lead:${activeSid}`,
8733
+ role: "lead",
8734
+ profile: this.sessionProfile,
8735
+ engine: report.runtimeId === "agy" ? "agy" : "pi",
8736
+ model: report.model ? `${report.runtimeId}:${report.model}` : this.currentModelRef(ctx),
8737
+ tokens: totalTokens ?? null,
8738
+ wallclock_ms: 0,
8739
+ cost_usd: report.usage?.costUsd ?? null,
8740
+ stop_reason: report.aborted ? "aborted" : "end_turn",
8741
+ ...report.idleMs !== void 0 ? { idle_ms: report.idleMs } : {},
8742
+ ...report.usage ? { usage: report.usage } : {}
8743
+ });
8744
+ if (this.isCurrent(ctx)) {
8745
+ void this.track(this.leaderRuntime.agentSettled(ctx, report.aborted));
8746
+ }
8747
+ }
8748
+ },
7705
8749
  now: () => this.deps.now(),
7706
8750
  randomId: (prefix) => this.deps.randomId(prefix)
7707
8751
  });
@@ -7715,6 +8759,7 @@ var SwarmController = class {
7715
8759
  snapshot: () => this.snapshot(),
7716
8760
  send: (ctx, options) => this.send(ctx, options),
7717
8761
  shutdownPeer: (ctx, targetSessionId) => this.shutdownPeer(ctx, targetSessionId),
8762
+ mission: (ctx, input) => this.manageMission(ctx, input),
7718
8763
  publishLeaderHandoff: (ctx, handoff) => this.publishLeaderHandoff(ctx, handoff)
7719
8764
  },
7720
8765
  deps.runtimeBaseDirectory
@@ -7722,6 +8767,62 @@ var SwarmController = class {
7722
8767
  this.leaderRuntime = new LeaderRuntime(pi, settings, {
7723
8768
  isCurrent: (ctx) => this.isCurrent(ctx),
7724
8769
  leaderSnapshot: (ctx) => this.leaderSnapshot(ctx),
8770
+ externalLeaderContext: (ctx) => {
8771
+ if (!this.isExternalDirectLeadActive(ctx)) return void 0;
8772
+ const direct = this.activeDirectRuntime;
8773
+ if (!direct) return void 0;
8774
+ const usage = this.externalLeaderUsage;
8775
+ return {
8776
+ runtimeId: direct.runtimeId,
8777
+ tokens: usage?.tokens ?? null,
8778
+ contextWindow: usage?.contextWindow ?? 1048576,
8779
+ completedTurns: usage?.completedTurns ?? 0,
8780
+ compactionCount: usage?.compactionCount ?? 0,
8781
+ ...direct.model ? { model: direct.model } : {},
8782
+ ...direct.thoughtLevel ? { thoughtLevel: direct.thoughtLevel } : {},
8783
+ ...direct.mode ? { mode: direct.mode } : {}
8784
+ };
8785
+ },
8786
+ externalPendingCount: (ctx) => {
8787
+ if (!this.isExternalDirectLeadActive(ctx)) return 0;
8788
+ if (this.activeDirectRuntime?.pendingCount !== void 0) {
8789
+ return this.activeDirectRuntime.pendingCount;
8790
+ }
8791
+ return this.externalLeaderUsage?.pendingCount ?? 0;
8792
+ },
8793
+ isPostTimeoutHandoffPending: () => this.postTimeoutHandoffRequired,
8794
+ clearExternalLeaderQueue: (ctx, replaceTag) => {
8795
+ if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return;
8796
+ this.externalRuntime.clearDirectQueue({
8797
+ runtimeId: this.activeDirectRuntime.runtimeId,
8798
+ sessionId: ctx.sessionManager.getSessionId(),
8799
+ ...replaceTag ? { replaceTag } : {}
8800
+ });
8801
+ },
8802
+ deliverExternalLeaderPrompt: (ctx, prompt, source, replaceTag) => {
8803
+ if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return false;
8804
+ this.externalRuntime.deliverToDirect({
8805
+ runtimeId: this.activeDirectRuntime.runtimeId,
8806
+ sessionId: ctx.sessionManager.getSessionId(),
8807
+ prompt,
8808
+ source,
8809
+ ...replaceTag ? { replaceTag } : {}
8810
+ });
8811
+ return true;
8812
+ },
8813
+ restoreExternalLeader: async (ctx, ext, handoffPrompt) => {
8814
+ await this.externalRuntime.restoreDirect(
8815
+ {
8816
+ runtimeId: ext.runtimeId,
8817
+ sessionId: ctx.sessionManager.getSessionId(),
8818
+ ...ext.model ? { model: ext.model } : {},
8819
+ ...ext.thoughtLevel ? { thoughtLevel: ext.thoughtLevel } : {},
8820
+ ...ext.mode ? { mode: ext.mode } : {},
8821
+ handoffPrompt
8822
+ },
8823
+ this.controller.signal
8824
+ );
8825
+ },
7725
8826
  restoreLeaderControl: (ctx, entry) => this.restoreLeaderControl(ctx, entry),
7726
8827
  commitLeaderControl: (ctx, entry) => this.commitLeaderControl(ctx, entry),
7727
8828
  completeLeaderRestore: (ctx) => this.completeLeaderRestore(ctx),
@@ -7787,12 +8888,24 @@ var SwarmController = class {
7787
8888
  pendingKickoffIds = /* @__PURE__ */ new Set();
7788
8889
  ledger;
7789
8890
  budgetTracker;
8891
+ cacheWarmingPolicy = new SwarmCacheWarmingPolicy();
7790
8892
  resourceLeases;
7791
8893
  externalRuntime;
7792
8894
  leadMcpBridge;
7793
8895
  verdictStore = new ReviewerVerdictStore();
7794
8896
  externalRuntimes = /* @__PURE__ */ new Map();
7795
8897
  quotaSeenByModel = /* @__PURE__ */ new Map();
8898
+ activeDirectRuntime;
8899
+ externalLeaderUsage;
8900
+ pendingReviewTasks = /* @__PURE__ */ new Map();
8901
+ activeMission;
8902
+ missionTimer;
8903
+ missionTicker;
8904
+ lastRosterBadgeWidth = 0;
8905
+ lastLeaderGenWidth = 0;
8906
+ lastTransientStatusWidth = 0;
8907
+ postTimeoutHandoffRequired = false;
8908
+ leaderGenerationNumber;
7796
8909
  sessionRole = "lead";
7797
8910
  sessionProfile = "default";
7798
8911
  sessionRuntime = "pi";
@@ -7816,6 +8929,19 @@ var SwarmController = class {
7816
8929
  this.activeContext = ctx;
7817
8930
  registerLeaderSessionActions(ctx.sessionManager, this.pi);
7818
8931
  registerLeaderRestoreGate(ctx.sessionManager, () => this.leaderRuntime.completeRestoreGate(ctx));
8932
+ registerLeaderExternalRestorer(ctx.sessionManager, async (ext, handoffPrompt) => {
8933
+ await this.externalRuntime.restoreDirect(
8934
+ {
8935
+ runtimeId: ext.runtimeId,
8936
+ sessionId: ctx.sessionManager.getSessionId(),
8937
+ ...ext.model ? { model: ext.model } : {},
8938
+ ...ext.thoughtLevel ? { thoughtLevel: ext.thoughtLevel } : {},
8939
+ ...ext.mode ? { mode: ext.mode } : {},
8940
+ handoffPrompt
8941
+ },
8942
+ this.controller.signal
8943
+ );
8944
+ });
7819
8945
  this.color = void 0;
7820
8946
  this.parentSessionId = void 0;
7821
8947
  this.leadSessionId = void 0;
@@ -7833,6 +8959,17 @@ var SwarmController = class {
7833
8959
  this.pendingKickoffIds.clear();
7834
8960
  this.verdictStore.clear();
7835
8961
  this.budgetTracker.clear();
8962
+ this.cacheWarmingPolicy.resetWaitWindow();
8963
+ this.activeDirectRuntime = void 0;
8964
+ this.externalLeaderUsage = void 0;
8965
+ this.pendingReviewTasks.clear();
8966
+ this.stopMissionTimers();
8967
+ this.activeMission = void 0;
8968
+ this.lastRosterBadgeWidth = 0;
8969
+ this.lastLeaderGenWidth = 0;
8970
+ this.lastTransientStatusWidth = 0;
8971
+ this.postTimeoutHandoffRequired = false;
8972
+ this.leaderGenerationNumber = void 0;
7836
8973
  this.sessionRole = "lead";
7837
8974
  this.sessionProfile = "default";
7838
8975
  this.sessionRuntime = "pi";
@@ -7869,8 +9006,11 @@ var SwarmController = class {
7869
9006
  try {
7870
9007
  const restore = await this.leaderRuntime.restore(ctx, event.previousSessionFile);
7871
9008
  if (restore === "restored") {
9009
+ if (!this.isCurrent(owner, ownerGeneration)) return;
9010
+ await this.closePreviousGenerationMissionOnHandoff(ctx);
7872
9011
  if (!this.isCurrent(owner, ownerGeneration)) return;
7873
9012
  this.activateLeaderToolIfLead(ctx);
9013
+ await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
7874
9014
  await this.renderFooterStatus(ctx);
7875
9015
  return;
7876
9016
  }
@@ -7894,6 +9034,9 @@ var SwarmController = class {
7894
9034
  this.autoNameEligible = true;
7895
9035
  this.activateLeaderToolIfLead(ctx);
7896
9036
  await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
9037
+ if (event.reason === "reload") {
9038
+ await this.restoreMissionOnReload(ctx, owner, ownerGeneration);
9039
+ }
7897
9040
  await this.renderFooterStatus(ctx);
7898
9041
  return;
7899
9042
  }
@@ -7951,6 +9094,9 @@ var SwarmController = class {
7951
9094
  );
7952
9095
  this.activateLeaderToolIfLead(ctx);
7953
9096
  await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
9097
+ if (event.reason === "reload" && this.leaderSnapshot(ctx).isLead) {
9098
+ await this.restoreMissionOnReload(ctx, owner, ownerGeneration);
9099
+ }
7954
9100
  const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
7955
9101
  const recyclingLeaderSessionId = this.leadSessionId ?? this.parentSessionId;
7956
9102
  if (recyclingLaunch && recyclingLeaderSessionId) {
@@ -7975,6 +9121,7 @@ var SwarmController = class {
7975
9121
  if (ctx.sessionManager !== this.activeSessionManager) return;
7976
9122
  this.stopLeadWatcher();
7977
9123
  this.stopResizeWatcher();
9124
+ this.stopMissionTimers();
7978
9125
  const pendingTurnMessages = this.leaderRuntime.takeTurnDeferredMessages();
7979
9126
  if (pendingTurnMessages.length > 0) {
7980
9127
  this.preserveDeferredFollowUps(ctx, {
@@ -8039,6 +9186,15 @@ var SwarmController = class {
8039
9186
  this.assertCurrentContext(ctx);
8040
9187
  await this.settings.flush();
8041
9188
  const launchSettings = this.settings.get().settings;
9189
+ const missionGate = checkMissionSpawnGate({
9190
+ mission: this.activeMission,
9191
+ role: "fanout",
9192
+ settings: launchSettings.missionCountdown,
9193
+ busToolName: this.isExternalDirectLeadActive(ctx) ? "swarm_bus" : "session_bus"
9194
+ });
9195
+ if (!missionGate.allowed) {
9196
+ throw new Error(missionGate.reason ?? "Mission countdown gate rejected fanout");
9197
+ }
8042
9198
  const resolvedBranches = [];
8043
9199
  for (const branch of input.branches) {
8044
9200
  const role = branch.role ?? "implementer";
@@ -8166,8 +9322,9 @@ var SwarmController = class {
8166
9322
  denyAsReviewer: doc.readonlyOverlay?.denyAsReviewer === true,
8167
9323
  resources: doc.resources.map((r) => r.id)
8168
9324
  }));
9325
+ const effectiveReview = orgLoaded.config.reviewPolicy ?? settings.reviewPolicy;
8169
9326
  const sections = [
8170
- `Org: ${orgLoaded.config.version} (${orgLoaded.source}, roles: ${Object.keys(orgLoaded.config.roles).join(", ")})`,
9327
+ `Org: ${orgLoaded.config.version} (${orgLoaded.source}, reviewPolicy: ${effectiveReview}, roles: ${Object.keys(orgLoaded.config.roles).join(", ")})`,
8171
9328
  "",
8172
9329
  "Profiles:",
8173
9330
  formatProfileCatalogSummary(profileCatalog),
@@ -8178,7 +9335,9 @@ var SwarmController = class {
8178
9335
  ] : [],
8179
9336
  "",
8180
9337
  "Concrete models:",
8181
- formatModelCatalogSummary(models) || "- (no models enumerated)"
9338
+ formatModelCatalogSummary(models) || "- (no models enumerated)",
9339
+ "",
9340
+ 'Reviewer guidance: For substantive implementer changes, spawn role="reviewer" with a different concrete model family than the implementer.'
8182
9341
  ];
8183
9342
  return {
8184
9343
  profilesDir: profileCatalog.profilesDir,
@@ -8205,6 +9364,9 @@ var SwarmController = class {
8205
9364
  });
8206
9365
  }
8207
9366
  currentModelRef(ctx) {
9367
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime?.model) {
9368
+ return `${this.activeDirectRuntime.runtimeId}:${this.activeDirectRuntime.model}`;
9369
+ }
8208
9370
  if (this.sessionRuntime === "agy" && this.sessionRuntimeModel) {
8209
9371
  return `agy:${this.sessionRuntimeModel}`;
8210
9372
  }
@@ -8216,25 +9378,442 @@ var SwarmController = class {
8216
9378
  async publishLeaderHandoff(ctx, content, signal) {
8217
9379
  this.assertCurrentContext(ctx);
8218
9380
  throwIfAborted5(signal, "Pi Agent Swarm leader handoff aborted");
8219
- const result = await this.leaderRuntime.publish(content, ctx);
9381
+ let effectiveContent = content;
9382
+ if (this.pendingReviewTasks.size > 0) {
9383
+ const pendingLines = [...this.pendingReviewTasks.entries()].map(
9384
+ ([taskId, info]) => `- task "${taskId}" (implementer: ${info.implementerName}, model: ${info.implementerModel})`
9385
+ );
9386
+ const suffix = `
9387
+
9388
+ [Pending Independent Review]
9389
+ ${pendingLines.join("\n")}`;
9390
+ const combined = `${content.remainingWork}${suffix}`;
9391
+ if (Buffer.byteLength(combined, "utf8") <= 8192) {
9392
+ effectiveContent = { ...content, remainingWork: combined };
9393
+ }
9394
+ }
9395
+ const result = await this.leaderRuntime.publish(effectiveContent, ctx);
8220
9396
  if (!this.isCurrent(ctx)) throw staleError();
9397
+ this.postTimeoutHandoffRequired = false;
9398
+ await this.closeActiveMission(ctx, "closed_by_handoff", "handoff", "Closed on leader generation handoff", []);
8221
9399
  return result;
8222
9400
  }
9401
+ getActiveMission() {
9402
+ return this.activeMission ? { ...this.activeMission } : void 0;
9403
+ }
9404
+ async manageMission(ctx, input) {
9405
+ this.assertCurrentContext(ctx);
9406
+ if (!this.leaderSnapshot(ctx).isLead) {
9407
+ throw new Error("Mission countdown management is available only in the lead session.");
9408
+ }
9409
+ const settings = this.settings.get().settings.missionCountdown;
9410
+ if (!settings.enabled) {
9411
+ throw new Error("Mission countdown is disabled in Pi Agent Swarm settings.");
9412
+ }
9413
+ if (input.missionAction === "status") {
9414
+ const live = isMissionLive(this.activeMission) ? this.activeMission : void 0;
9415
+ if (!live) {
9416
+ return { action: "status", message: "No active mission countdown for this leader generation." };
9417
+ }
9418
+ const remainingMs = Math.max(0, live.deadlineAt - this.deps.now());
9419
+ return {
9420
+ action: "status",
9421
+ mission: { ...live },
9422
+ remainingMs,
9423
+ message: `Mission ${live.missionId} is ${live.state} (remaining ${Math.ceil(remainingMs / 1e3)}s / budget ${live.estimatedMinutes}m).`
9424
+ };
9425
+ }
9426
+ if (input.missionAction === "start") {
9427
+ if (isMissionLive(this.activeMission)) {
9428
+ throw new Error(
9429
+ `Mission "${this.activeMission.missionId}" is already ${this.activeMission.state}. Complete it before starting a new mission.`
9430
+ );
9431
+ }
9432
+ if (this.postTimeoutHandoffRequired) {
9433
+ const canRecycle = await this.leaderRuntime.canRecycleLeader(ctx);
9434
+ if (!this.isCurrent(ctx)) throw staleError();
9435
+ if (canRecycle) {
9436
+ const handoffToolName = this.isExternalDirectLeadActive(ctx) ? "swarm_leader_handoff" : "leader_handoff";
9437
+ throw new Error(
9438
+ `The previous mission countdown expired and closed. Do not start a second countdown on the old leader session \u2014 call ${handoffToolName} first to rotate into a fresh successor session, then start the new mission there.`
9439
+ );
9440
+ }
9441
+ this.postTimeoutHandoffRequired = false;
9442
+ }
9443
+ const validated = validateMissionStartInput(
9444
+ {
9445
+ firstPrinciples: input.firstPrinciples ?? "",
9446
+ acceptanceCriteria: input.acceptanceCriteria ?? "",
9447
+ ...input.constraints ? { constraints: input.constraints } : {},
9448
+ estimatedMinutes: input.estimatedMinutes
9449
+ },
9450
+ settings
9451
+ );
9452
+ const now = this.deps.now();
9453
+ const durationMs = Math.max(100, Math.round(validated.estimatedMinutes * 6e4));
9454
+ const record3 = {
9455
+ schemaVersion: 1,
9456
+ missionId: this.deps.randomId("mission"),
9457
+ leaderSessionId: ctx.sessionManager.getSessionId(),
9458
+ firstPrinciples: validated.firstPrinciples,
9459
+ acceptanceCriteria: validated.acceptanceCriteria,
9460
+ ...validated.constraints ? { constraints: validated.constraints } : {},
9461
+ requestedMinutes: validated.requestedMinutes,
9462
+ estimatedMinutes: validated.estimatedMinutes,
9463
+ clamped: validated.clamped,
9464
+ startedAt: now,
9465
+ deadlineAt: now + durationMs,
9466
+ state: "active"
9467
+ };
9468
+ await writeActiveMission(ctx.cwd, record3);
9469
+ if (!this.isCurrent(ctx)) throw staleError();
9470
+ this.activeMission = record3;
9471
+ this.armMissionTimers(ctx, record3);
9472
+ this.recordLedger(ctx.cwd, {
9473
+ event: "mission_started",
9474
+ task_id: record3.missionId,
9475
+ role: "lead",
9476
+ profile: this.sessionProfile,
9477
+ engine: this.isExternalDirectLeadActive(ctx) ? "agy" : this.sessionRuntime,
9478
+ model: this.currentModelRef(ctx),
9479
+ estimated_minutes: record3.estimatedMinutes,
9480
+ requested_minutes: record3.requestedMinutes,
9481
+ clamped: record3.clamped,
9482
+ goal_chars: record3.firstPrinciples.length
9483
+ });
9484
+ this.renderMissionStatus(ctx);
9485
+ return {
9486
+ action: "start",
9487
+ mission: { ...record3 },
9488
+ remainingMs: durationMs,
9489
+ message: `Mission "${record3.missionId}" armed for ${record3.estimatedMinutes}m${record3.clamped ? ` (clamped from ${record3.requestedMinutes}m)` : ""}.`
9490
+ };
9491
+ }
9492
+ if (input.missionAction === "complete") {
9493
+ if (!isMissionLive(this.activeMission)) {
9494
+ throw new Error("No active mission to complete.");
9495
+ }
9496
+ const validated = validateMissionCompleteInput({
9497
+ summary: input.summary ?? "",
9498
+ ...input.outcome ? { outcome: input.outcome } : {},
9499
+ ...input.residuals ? { residuals: input.residuals } : {}
9500
+ });
9501
+ const mergedResiduals = [...validated.residuals];
9502
+ if (this.pendingReviewTasks.size > 0) {
9503
+ for (const [taskId, info] of this.pendingReviewTasks) {
9504
+ const note = `Unreviewed implementer task "${taskId}" (${info.implementerName})`;
9505
+ if (!mergedResiduals.some((r) => r.includes(taskId))) {
9506
+ mergedResiduals.push(note);
9507
+ }
9508
+ }
9509
+ }
9510
+ const effectiveOutcome = validated.outcome === "with_residuals" || mergedResiduals.length > 0 || isMissionConverging(this.activeMission) ? mergedResiduals.length > 0 || validated.outcome === "with_residuals" ? "with_residuals" : "achieved" : "achieved";
9511
+ const archived = await this.closeActiveMission(
9512
+ ctx,
9513
+ "completed",
9514
+ effectiveOutcome,
9515
+ validated.summary,
9516
+ mergedResiduals
9517
+ );
9518
+ return {
9519
+ action: "complete",
9520
+ ...archived ? { mission: archived } : {},
9521
+ message: `Mission "${archived?.missionId ?? ""}" completed (${effectiveOutcome}${mergedResiduals.length > 0 ? `, ${mergedResiduals.length} residual(s)` : ""}).`
9522
+ };
9523
+ }
9524
+ throw new Error(`Unsupported missionAction "${String(input.missionAction)}"`);
9525
+ }
9526
+ async restoreMissionOnReload(ctx, owner, ownerGeneration) {
9527
+ if (!this.settings.get().settings.missionCountdown.enabled) return;
9528
+ const existing = await readActiveMission(ctx.cwd);
9529
+ if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(existing)) return;
9530
+ if (existing.leaderSessionId !== ctx.sessionManager.getSessionId()) return;
9531
+ this.activeMission = existing;
9532
+ this.armMissionTimers(ctx, existing);
9533
+ this.renderMissionStatus(ctx);
9534
+ }
9535
+ async closePreviousGenerationMissionOnHandoff(ctx) {
9536
+ const existing = await readActiveMission(ctx.cwd);
9537
+ if (!isMissionLive(existing)) return;
9538
+ if (existing.leaderSessionId === ctx.sessionManager.getSessionId()) return;
9539
+ const now = this.deps.now();
9540
+ const closed = {
9541
+ ...existing,
9542
+ state: "closed_by_handoff",
9543
+ outcome: "handoff",
9544
+ completedAt: now,
9545
+ summary: "Previous leader generation ended; successor leader will re-evaluate from handoff."
9546
+ };
9547
+ await archiveMission(ctx.cwd, closed).catch(() => void 0);
9548
+ this.recordLedger(ctx.cwd, {
9549
+ event: "mission_completed",
9550
+ task_id: closed.missionId,
9551
+ role: "lead",
9552
+ profile: this.sessionProfile,
9553
+ engine: this.sessionRuntime,
9554
+ model: this.currentModelRef(ctx),
9555
+ outcome: "handoff",
9556
+ final_state: "closed_by_handoff",
9557
+ elapsed_ms: Math.max(0, now - closed.startedAt),
9558
+ residual_count: closed.residuals?.length ?? 0
9559
+ });
9560
+ }
9561
+ async closeActiveMission(ctx, finalState, outcome, summary, residuals) {
9562
+ const current = this.activeMission;
9563
+ this.stopMissionTimers();
9564
+ this.activeMission = void 0;
9565
+ this.renderMissionStatus(ctx);
9566
+ if (!current) return void 0;
9567
+ if (this.isExternalDirectLeadActive(ctx) && this.activeDirectRuntime) {
9568
+ this.externalRuntime.clearDirectQueue({
9569
+ runtimeId: this.activeDirectRuntime.runtimeId,
9570
+ sessionId: ctx.sessionManager.getSessionId(),
9571
+ replaceTag: `mission-timeout:${current.missionId}`
9572
+ });
9573
+ }
9574
+ const wasTimedOut = current.state === "converging" || current.state === "final_wrap_up" || current.convergingAt !== void 0;
9575
+ if (finalState === "auto_completed" || finalState === "completed" && wasTimedOut) {
9576
+ this.postTimeoutHandoffRequired = true;
9577
+ } else if (finalState === "closed_by_handoff") {
9578
+ this.postTimeoutHandoffRequired = false;
9579
+ }
9580
+ const now = this.deps.now();
9581
+ const archived = {
9582
+ ...current,
9583
+ state: finalState,
9584
+ outcome,
9585
+ completedAt: now,
9586
+ summary,
9587
+ ...residuals.length > 0 ? { residuals } : {}
9588
+ };
9589
+ await archiveMission(ctx.cwd, archived).catch(() => void 0);
9590
+ this.recordLedger(ctx.cwd, {
9591
+ event: "mission_completed",
9592
+ task_id: archived.missionId,
9593
+ role: "lead",
9594
+ profile: this.sessionProfile,
9595
+ engine: this.isExternalDirectLeadActive(ctx) ? "agy" : this.sessionRuntime,
9596
+ model: this.currentModelRef(ctx),
9597
+ outcome,
9598
+ final_state: finalState,
9599
+ elapsed_ms: Math.max(0, now - archived.startedAt),
9600
+ residual_count: residuals.length
9601
+ });
9602
+ return archived;
9603
+ }
9604
+ armMissionTimers(ctx, record3) {
9605
+ this.stopMissionTimers();
9606
+ const owner = ctx.sessionManager;
9607
+ const ownerGeneration = this.generation;
9608
+ const settings = this.settings.get().settings.missionCountdown;
9609
+ const now = this.deps.now();
9610
+ if (record3.state === "active") {
9611
+ const delayMs = Math.max(0, record3.deadlineAt - now);
9612
+ this.missionTimer = setTimeout(() => {
9613
+ void this.handleMissionTimeout(ctx, owner, ownerGeneration, "converging");
9614
+ }, delayMs);
9615
+ this.missionTimer.unref?.();
9616
+ } else if (record3.state === "converging") {
9617
+ const targetAt = (record3.convergingAt ?? record3.deadlineAt) + settings.wrapUpGraceMs;
9618
+ const delayMs = Math.max(0, targetAt - now);
9619
+ this.missionTimer = setTimeout(() => {
9620
+ void this.handleMissionTimeout(ctx, owner, ownerGeneration, "final_wrap_up");
9621
+ }, delayMs);
9622
+ this.missionTimer.unref?.();
9623
+ } else if (record3.state === "final_wrap_up") {
9624
+ const autoCloseMs = Math.max(
9625
+ MIN_FINAL_WRAP_UP_MS,
9626
+ Math.round(settings.wrapUpGraceMs * FINAL_WRAP_UP_AUTO_CLOSE_FACTOR)
9627
+ );
9628
+ const targetAt = (record3.finalWrapUpAt ?? now) + autoCloseMs;
9629
+ const delayMs = Math.max(0, targetAt - now);
9630
+ this.missionTimer = setTimeout(() => {
9631
+ void this.handleMissionAutoClose(ctx, owner, ownerGeneration);
9632
+ }, delayMs);
9633
+ this.missionTimer.unref?.();
9634
+ }
9635
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
9636
+ }
9637
+ scheduleNextMissionTick(ctx, owner, ownerGeneration) {
9638
+ if (this.missionTicker !== void 0) {
9639
+ clearTimeout(this.missionTicker);
9640
+ this.missionTicker = void 0;
9641
+ }
9642
+ const delayMs = nextMissionTickDelayMs(this.activeMission, this.deps.now());
9643
+ if (delayMs === void 0) return;
9644
+ this.missionTicker = setTimeout(() => {
9645
+ this.missionTicker = void 0;
9646
+ if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(this.activeMission)) {
9647
+ this.stopMissionTimers();
9648
+ return;
9649
+ }
9650
+ this.renderMissionStatus(ctx);
9651
+ this.scheduleNextMissionTick(ctx, owner, ownerGeneration);
9652
+ }, delayMs);
9653
+ this.missionTicker.unref?.();
9654
+ }
9655
+ async handleMissionTimeout(ctx, owner, ownerGeneration, stage) {
9656
+ if (!this.isCurrent(owner, ownerGeneration)) return;
9657
+ const current = this.activeMission;
9658
+ if (!isMissionLive(current)) return;
9659
+ if (stage === "converging" && current.state !== "active") return;
9660
+ if (stage === "final_wrap_up" && current.state !== "converging") return;
9661
+ const now = this.deps.now();
9662
+ const updated = {
9663
+ ...current,
9664
+ state: stage,
9665
+ ...stage === "converging" ? { convergingAt: now } : { finalWrapUpAt: now }
9666
+ };
9667
+ this.activeMission = updated;
9668
+ await writeActiveMission(ctx.cwd, updated).catch(() => void 0);
9669
+ if (!this.isCurrent(owner, ownerGeneration) || this.activeMission?.missionId !== updated.missionId) return;
9670
+ const isExternal = this.isExternalDirectLeadActive(ctx);
9671
+ const busToolName = isExternal ? "swarm_bus" : "session_bus";
9672
+ const injection = formatMissionTimeoutInjection({
9673
+ mission: updated,
9674
+ stage,
9675
+ now,
9676
+ inFlightWorkerCount: this.pendingKickoffIds.size,
9677
+ busToolName
9678
+ });
9679
+ this.recordLedger(ctx.cwd, {
9680
+ event: "mission_timeout",
9681
+ task_id: updated.missionId,
9682
+ role: "lead",
9683
+ profile: this.sessionProfile,
9684
+ engine: isExternal ? "agy" : this.sessionRuntime,
9685
+ model: this.currentModelRef(ctx),
9686
+ stage,
9687
+ elapsed_ms: Math.max(0, now - updated.startedAt),
9688
+ in_flight_workers: this.pendingKickoffIds.size
9689
+ });
9690
+ if (isExternal && this.activeDirectRuntime) {
9691
+ this.pi.sendMessage(
9692
+ { customType: MISSION_CUSTOM_TYPE, content: injection, display: true },
9693
+ { deliverAs: "followUp", triggerTurn: false }
9694
+ );
9695
+ this.externalRuntime.deliverToDirect({
9696
+ runtimeId: this.activeDirectRuntime.runtimeId,
9697
+ sessionId: ctx.sessionManager.getSessionId(),
9698
+ prompt: injection,
9699
+ source: "leader_advisory",
9700
+ replaceTag: `mission-timeout:${updated.missionId}`
9701
+ });
9702
+ } else {
9703
+ this.pi.sendMessage(
9704
+ { customType: MISSION_CUSTOM_TYPE, content: injection, display: true },
9705
+ { deliverAs: "followUp", triggerTurn: !this.leaderRuntime.shouldDeferFollowUp() }
9706
+ );
9707
+ }
9708
+ this.armMissionTimers(ctx, updated);
9709
+ this.renderMissionStatus(ctx);
9710
+ }
9711
+ async handleMissionAutoClose(ctx, owner, ownerGeneration) {
9712
+ if (!this.isCurrent(owner, ownerGeneration)) return;
9713
+ const current = this.activeMission;
9714
+ if (current?.state !== "final_wrap_up") return;
9715
+ const residuals = [
9716
+ `Mission "${current.missionId}" autonomously auto-closed after exceeding its ${current.estimatedMinutes}m estimate and wrap-up window without an explicit complete call.`
9717
+ ];
9718
+ for (const [taskId, info] of this.pendingReviewTasks) {
9719
+ residuals.push(`Unreviewed implementer task "${taskId}" (${info.implementerName})`);
9720
+ }
9721
+ await this.closeActiveMission(
9722
+ ctx,
9723
+ "auto_completed",
9724
+ "with_residuals",
9725
+ "Autonomously closed after final wrap-up convergence timeout (with residuals).",
9726
+ residuals
9727
+ );
9728
+ if (!this.isCurrent(owner, ownerGeneration)) return;
9729
+ const recyclingConfig = this.settings.get().settings.leaderRecycling;
9730
+ if (recyclingConfig.enabled && recyclingConfig.mode === "auto" && this.postTimeoutHandoffRequired) {
9731
+ const extActive = this.isExternalDirectLeadActive(ctx);
9732
+ const extIdle = !extActive || this.activeDirectRuntime?.busy !== true && (this.activeDirectRuntime?.pendingCount ?? 0) === 0;
9733
+ const nativeIdle = extActive || (typeof ctx.isIdle === "function" ? ctx.isIdle() : true);
9734
+ if (extIdle && nativeIdle) {
9735
+ void this.track(this.leaderRuntime.agentSettled(ctx, false));
9736
+ }
9737
+ }
9738
+ }
9739
+ stopMissionTimers() {
9740
+ if (this.missionTimer !== void 0) {
9741
+ clearTimeout(this.missionTimer);
9742
+ this.missionTimer = void 0;
9743
+ }
9744
+ if (this.missionTicker !== void 0) {
9745
+ clearTimeout(this.missionTicker);
9746
+ this.missionTicker = void 0;
9747
+ }
9748
+ }
9749
+ missionAvailableColumns() {
9750
+ const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
9751
+ let occupied = 0;
9752
+ if (this.lastRosterBadgeWidth > 0) occupied += this.lastRosterBadgeWidth + 1;
9753
+ if (this.lastLeaderGenWidth > 0) occupied += this.lastLeaderGenWidth + 1;
9754
+ if (this.lastTransientStatusWidth > 0) occupied += this.lastTransientStatusWidth + 1;
9755
+ return Math.max(0, columns - occupied);
9756
+ }
9757
+ renderMissionStatus(ctx) {
9758
+ if (!ctx.hasUI) return;
9759
+ const settings = this.settings.get().settings.missionCountdown;
9760
+ const badge2 = formatMissionStatusBadge(this.activeMission, this.deps.now(), {
9761
+ availableColumns: this.missionAvailableColumns(),
9762
+ wrapUpGraceMs: settings.wrapUpGraceMs
9763
+ });
9764
+ try {
9765
+ ctx.ui.setStatus(MISSION_STATUS_KEY, badge2);
9766
+ } catch {
9767
+ }
9768
+ }
8223
9769
  activateLeaderToolIfLead(ctx) {
8224
9770
  if (!this.settings.get().settings.leaderRecycling.enabled || !this.leaderSnapshot(ctx).isLead) return;
8225
9771
  const activeTools = this.pi.getActiveTools();
8226
9772
  if (activeTools.includes("leader_handoff")) return;
8227
9773
  this.pi.setActiveTools([...activeTools, "leader_handoff"]);
8228
9774
  }
9775
+ decideCacheWarming(event, ctx) {
9776
+ const isLead = this.leaderSnapshot(ctx).isLead;
9777
+ const externalDirectActive = this.isExternalDirectLeadActive(ctx);
9778
+ const inFlightWorkerCount = this.pendingKickoffIds.size;
9779
+ const outcome = this.cacheWarmingPolicy.evaluate({
9780
+ defaultAction: event.action,
9781
+ model: ctx.model,
9782
+ isLead,
9783
+ externalDirectActive,
9784
+ inFlightWorkerCount,
9785
+ settings: this.settings.get().settings.cacheWarming,
9786
+ now: this.deps.now()
9787
+ });
9788
+ return { action: outcome.action };
9789
+ }
9790
+ isExternalDirectLeadActive(ctx) {
9791
+ if (!ctx || !this.activeDirectRuntime?.active) return false;
9792
+ return this.sessionRole === "lead" && this.leaderSnapshot(ctx).isLead;
9793
+ }
9794
+ effectiveReviewPolicy(projectRoot) {
9795
+ const orgLoaded = loadProjectOrgConfig(projectRoot);
9796
+ return orgLoaded.config.reviewPolicy ?? this.settings.get().settings.reviewPolicy;
9797
+ }
8229
9798
  leaderSnapshot(ctx) {
8230
9799
  const sessionId = ctx.sessionManager.getSessionId();
9800
+ const isLead = this.leadSessionId === sessionId || !this.membership && this.defaultLead;
9801
+ const direct = isLead && this.activeDirectRuntime?.active ? this.activeDirectRuntime : void 0;
8231
9802
  return {
8232
- isLead: this.leadSessionId === sessionId || !this.membership && this.defaultLead,
9803
+ isLead,
8233
9804
  pendingKickoffIds: [...this.pendingKickoffIds],
8234
9805
  invite: this.membership?.invite,
8235
9806
  groupDirectory: this.membership?.transport.endpointManifest?.directory,
8236
9807
  acceptsRequests: this.membership?.acceptsRequests ?? false,
8237
- color: this.color
9808
+ color: this.color,
9809
+ ...direct ? {
9810
+ externalRuntime: {
9811
+ runtimeId: direct.runtimeId,
9812
+ ...direct.model ? { model: direct.model } : {},
9813
+ ...direct.thoughtLevel ? { thoughtLevel: direct.thoughtLevel } : {},
9814
+ ...direct.mode ? { mode: direct.mode } : {}
9815
+ }
9816
+ } : {}
8238
9817
  };
8239
9818
  }
8240
9819
  async restoreLeaderControl(ctx, entry) {
@@ -8256,6 +9835,16 @@ var SwarmController = class {
8256
9835
  this.defaultLead = !entry.invite;
8257
9836
  this.color = entry.color;
8258
9837
  this.autoNameEligible = false;
9838
+ this.leaderGenerationNumber = entry.generation + 1;
9839
+ this.postTimeoutHandoffRequired = false;
9840
+ const prevShort = entry.previousSessionId.slice(0, 8);
9841
+ const nextShort = sessionId.slice(0, 8);
9842
+ const extSuffix = entry.externalRuntime ? ` [${entry.externalRuntime.runtimeId} fresh session]` : "";
9843
+ this.notify(
9844
+ ctx,
9845
+ `Leader handoff applied: G${entry.generation} (${prevShort}) \u2192 G${entry.generation + 1} (${nextShort})${extSuffix}`,
9846
+ "info"
9847
+ );
8259
9848
  const recover = async (label, action) => {
8260
9849
  if (!this.isCurrent(ctx)) return false;
8261
9850
  try {
@@ -8394,13 +9983,13 @@ var SwarmController = class {
8394
9983
  await attempt("Could not clear the failed leader footer", () => this.clearStatus(ctx));
8395
9984
  await attempt("Could not clear the failed leader roster", () => this.clearRosterStatus(ctx));
8396
9985
  if (this.isCurrent(ctx)) this.preserveDeferredFollowUps(ctx, entry);
8397
- const directory = entry.groupDirectory ?? (group ? join15(this.deps.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), group.id) : void 0);
9986
+ const directory = entry.groupDirectory ?? (group ? join16(this.deps.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), group.id) : void 0);
8398
9987
  if (!directory) return;
8399
9988
  await attempt("Could not remove the dead predecessor lead record after pre-commit failure", async () => {
8400
9989
  try {
8401
- const raw = JSON.parse(await readFile6(join15(directory, "lead.json"), "utf8"));
9990
+ const raw = JSON.parse(await readFile7(join16(directory, "lead.json"), "utf8"));
8402
9991
  if (raw.sessionId === entry.previousSessionId || raw.sessionId === ctx.sessionManager.getSessionId()) {
8403
- await rm10(join15(directory, "lead.json"), { force: true });
9992
+ await rm11(join16(directory, "lead.json"), { force: true });
8404
9993
  }
8405
9994
  } catch (error) {
8406
9995
  if (error.code !== "ENOENT") throw error;
@@ -8408,7 +9997,7 @@ var SwarmController = class {
8408
9997
  });
8409
9998
  }
8410
9999
  async validateWorkerOwnership(ctx, previousSessionId) {
8411
- const directory = resolve12(ctx.cwd, ".pi", "agent-swarm", "lineages");
10000
+ const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
8412
10001
  let entries;
8413
10002
  try {
8414
10003
  entries = await readdir4(directory, { withFileTypes: true });
@@ -8436,7 +10025,7 @@ var SwarmController = class {
8436
10025
  if (previousSessionId.length === 0) throw new Error("The previous leader session id is empty.");
8437
10026
  }
8438
10027
  async rebindWorkerLineages(ctx, previousSessionId, nextSessionId = ctx.sessionManager.getSessionId()) {
8439
- const directory = resolve12(ctx.cwd, ".pi", "agent-swarm", "lineages");
10028
+ const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
8440
10029
  let entries;
8441
10030
  try {
8442
10031
  entries = await readdir4(directory, { withFileTypes: true });
@@ -8576,6 +10165,7 @@ var SwarmController = class {
8576
10165
  }
8577
10166
  async agentStarted(ctx) {
8578
10167
  if (!this.isCurrent(ctx)) return;
10168
+ this.cacheWarmingPolicy.resetWaitWindow();
8579
10169
  await this.leaderRuntime.agentStarted(ctx);
8580
10170
  }
8581
10171
  async agentSettled(ctx, aborted = false) {
@@ -8973,6 +10563,13 @@ var SwarmController = class {
8973
10563
  await this.resourceLeases.releaseMany(childMeta.leases).catch(() => void 0);
8974
10564
  childMeta.leases = [];
8975
10565
  }
10566
+ if (childMeta?.role === "implementer" && this.effectiveReviewPolicy(ctx.cwd) === "required" && !this.verdictStore.hasPassingVerdict(childMeta.taskId)) {
10567
+ this.notify(
10568
+ ctx,
10569
+ `[Swarm Governance] Shutting down implementer for task "${childMeta.taskId}" before any independent reviewer "pass" verdict was recorded.`,
10570
+ "warning"
10571
+ );
10572
+ }
8976
10573
  }
8977
10574
  return { message, acknowledgement };
8978
10575
  }
@@ -8990,6 +10587,19 @@ var SwarmController = class {
8990
10587
  await this.settings.flush();
8991
10588
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
8992
10589
  const launchSettings = this.settings.get().settings;
10590
+ const isWorkerReplacement = input.recyclingLaunch !== void 0 && input.recyclingLaunch.generation > 1;
10591
+ if (!isWorkerReplacement && this.leaderSnapshot(ctx).isLead) {
10592
+ const requestedRole = input.role ?? "implementer";
10593
+ const missionGate = checkMissionSpawnGate({
10594
+ mission: this.activeMission,
10595
+ role: requestedRole,
10596
+ settings: launchSettings.missionCountdown,
10597
+ busToolName: this.isExternalDirectLeadActive(ctx) ? "swarm_bus" : "session_bus"
10598
+ });
10599
+ if (!missionGate.allowed) {
10600
+ throw new Error(missionGate.reason ?? "Mission countdown gate rejected spawn");
10601
+ }
10602
+ }
8993
10603
  const recyclingLaunch = input.recyclingLaunch ?? (input.contextRecycling ? {
8994
10604
  lineageId: this.deps.randomId("lineage"),
8995
10605
  generation: 1,
@@ -9154,7 +10764,8 @@ var SwarmController = class {
9154
10764
  claimedMembership = membership;
9155
10765
  const directory = membership.transport.endpointManifest?.directory;
9156
10766
  if (!directory) throw new Error("Pi Agent Swarm runtime directory is unavailable");
9157
- const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs]);
10767
+ const extraWorkerPiArgs = launchSettings.workerPiArgs ? [...launchSettings.workerPiArgs] : [];
10768
+ const invocation = this.deps.resolveInvocation(["--name", name, ...resolvedProfile.piArgs, ...extraWorkerPiArgs]);
9158
10769
  const envelope = {
9159
10770
  invite: membership.invite,
9160
10771
  parentSessionId: ctx.sessionManager.getSessionId(),
@@ -9474,7 +11085,7 @@ var SwarmController = class {
9474
11085
  this.successorLaunches.set(key, task);
9475
11086
  }
9476
11087
  async recoverProjectHandoffs(ctx) {
9477
- const directory = resolve12(ctx.cwd, ".pi", "agent-swarm", "lineages");
11088
+ const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
9478
11089
  const entries = await readdir4(directory, { withFileTypes: true }).catch((error) => {
9479
11090
  if (error.code === "ENOENT") return [];
9480
11091
  throw error;
@@ -9502,7 +11113,7 @@ var SwarmController = class {
9502
11113
  continue;
9503
11114
  }
9504
11115
  const expectedPath = workerLineagePaths(ctx.cwd, entry.name, lineage.currentGeneration).handoffPath;
9505
- const complete = await readFile6(expectedPath, "utf8").then((markdown) => hasRequiredHandoffSections(markdown)).catch(() => false);
11116
+ const complete = await readFile7(expectedPath, "utf8").then((markdown) => hasRequiredHandoffSections(markdown)).catch(() => false);
9506
11117
  if (!complete) continue;
9507
11118
  try {
9508
11119
  await updateWorkerLineage(
@@ -9537,21 +11148,21 @@ var SwarmController = class {
9537
11148
  async spawnSuccessor(ctx, message) {
9538
11149
  const projectRoot = message.fromCwd;
9539
11150
  if (!projectRoot) throw new Error("Handoff sender did not provide its project cwd");
9540
- const handoffPath = resolve12(message.text);
9541
- const storagePrefix = `${resolve12(projectRoot, ".pi", "agent-swarm", "lineages")}${sep3}`;
11151
+ const handoffPath = resolve13(message.text);
11152
+ const storagePrefix = `${resolve13(projectRoot, ".pi", "agent-swarm", "lineages")}${sep3}`;
9542
11153
  if (!handoffPath.startsWith(storagePrefix) || basename7(dirname7(handoffPath)) !== "generations") {
9543
11154
  throw new Error("Handoff path is outside the sender's project lineage storage");
9544
11155
  }
9545
11156
  const lineageId = basename7(dirname7(dirname7(handoffPath)));
9546
11157
  const lineage = await readWorkerLineage(projectRoot, lineageId);
9547
11158
  if (!this.isCurrent(ctx)) throw staleError();
9548
- if (lineage.leaderSessionId !== ctx.sessionManager.getSessionId() || resolve12(lineage.currentHandoffPath ?? "") !== handoffPath || lineage.state !== "handoff_ready" || !lineage.nextAction) {
11159
+ if (lineage.leaderSessionId !== ctx.sessionManager.getSessionId() || resolve13(lineage.currentHandoffPath ?? "") !== handoffPath || lineage.state !== "handoff_ready" || !lineage.nextAction) {
9549
11160
  throw new Error("Handoff lineage is not ready for this leader");
9550
11161
  }
9551
11162
  if (lineage.replacementCount >= lineage.policy.maxReplacements) {
9552
11163
  throw new Error("Handoff replacement budget is exhausted");
9553
11164
  }
9554
- await readFile6(handoffPath, "utf8");
11165
+ await readFile7(handoffPath, "utf8");
9555
11166
  const nextGeneration = lineage.currentGeneration + 1;
9556
11167
  const replacementCount = lineage.replacementCount + 1;
9557
11168
  await updateWorkerLineage(
@@ -9708,6 +11319,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9708
11319
  return false;
9709
11320
  }
9710
11321
  const shouldTrigger = resolvedTrigger ?? this.resolveTriggerTurn(message);
11322
+ let governanceSuffix = "";
9711
11323
  if (message.mode === "reply" && this.activeContext) {
9712
11324
  if (message.text.includes("[SWARM_SIGNAL:QUOTA_EXHAUSTED]")) {
9713
11325
  const senderMeta = this.childRecords.get(message.fromSessionId);
@@ -9752,9 +11364,54 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9752
11364
  source: message.fromSessionId,
9753
11365
  score: parsedVerdict.score
9754
11366
  });
11367
+ if (parsedVerdict.verdict === "pass") {
11368
+ this.pendingReviewTasks.delete(replyTaskId);
11369
+ } else if (parsedVerdict.verdict === "fail") {
11370
+ const consecutiveFails = this.verdictStore.consecutiveFailsForTask(replyTaskId);
11371
+ if (consecutiveFails >= MAX_CONSECUTIVE_REVIEWER_FAILS) {
11372
+ this.recordLedger(this.activeContext.cwd, {
11373
+ event: "run_escalated",
11374
+ task_id: replyTaskId,
11375
+ role: "lead",
11376
+ profile: replyProfile,
11377
+ engine: replyEngine,
11378
+ model: replyModel,
11379
+ reason: "reviewer_consecutive_failures",
11380
+ budget_left: { consecutiveFails }
11381
+ });
11382
+ governanceSuffix = formatReviewerEscalationNotice({
11383
+ taskId: replyTaskId,
11384
+ consecutiveFails,
11385
+ blockingIssues: parsedVerdict.blocking_issues
11386
+ });
11387
+ }
11388
+ }
9755
11389
  } catch {
9756
11390
  }
9757
11391
  }
11392
+ } else if (childRecord?.role === "implementer") {
11393
+ if (!this.verdictStore.hasPassingVerdict(replyTaskId)) {
11394
+ this.pendingReviewTasks.set(replyTaskId, {
11395
+ implementerSessionId: message.fromSessionId,
11396
+ implementerName: sender,
11397
+ implementerModel: replyModel
11398
+ });
11399
+ const reviewPolicy = this.effectiveReviewPolicy(this.activeContext.cwd);
11400
+ if (reviewPolicy === "suggest" || reviewPolicy === "required") {
11401
+ const catalog = buildModelCatalog(this.activeContext, this.externalRuntimes, this.quotaSeenByModel);
11402
+ const suggestedReviewerModels = suggestCrossFamilyReviewerModels(
11403
+ replyModel,
11404
+ catalog.entries.map((entry) => ({ ref: entry.modelRef, sawQuota: entry.sawQuota }))
11405
+ );
11406
+ governanceSuffix = formatReviewGovernanceReminder({
11407
+ policy: reviewPolicy,
11408
+ taskId: replyTaskId,
11409
+ implementerName: sender,
11410
+ implementerModel: replyModel,
11411
+ suggestedReviewerModels
11412
+ });
11413
+ }
11414
+ }
9758
11415
  }
9759
11416
  if (childRecord) {
9760
11417
  this.recordLedger(this.activeContext.cwd, {
@@ -9771,10 +11428,33 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9771
11428
  });
9772
11429
  }
9773
11430
  }
11431
+ const deliveredContent = `${content}${replyGuidance}${governanceSuffix}`;
11432
+ const wantsTrigger = allowTrigger && shouldTrigger && !this.leaderRuntime.shouldDeferFollowUp();
11433
+ const activeCtx = this.activeContext;
11434
+ if (wantsTrigger && activeCtx && this.isExternalDirectLeadActive(activeCtx) && this.activeDirectRuntime) {
11435
+ this.pi.sendMessage(
11436
+ {
11437
+ customType: SWARM_MESSAGE_TYPE,
11438
+ content: deliveredContent,
11439
+ display: true,
11440
+ details
11441
+ },
11442
+ { deliverAs: "followUp", triggerTurn: false }
11443
+ );
11444
+ this.externalRuntime.deliverToDirect({
11445
+ runtimeId: this.activeDirectRuntime.runtimeId,
11446
+ sessionId: activeCtx.sessionManager.getSessionId(),
11447
+ prompt: deliveredContent,
11448
+ source: "swarm_message",
11449
+ messageId: message.id,
11450
+ fromSessionId: message.fromSessionId
11451
+ });
11452
+ return shouldTrigger;
11453
+ }
9774
11454
  this.pi.sendMessage(
9775
11455
  {
9776
11456
  customType: SWARM_MESSAGE_TYPE,
9777
- content: `${content}${replyGuidance}`,
11457
+ content: deliveredContent,
9778
11458
  display: true,
9779
11459
  details
9780
11460
  },
@@ -9782,7 +11462,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9782
11462
  deliverAs: "followUp",
9783
11463
  // A replayed message must not start a turn while the restoring leader is still being
9784
11464
  // configured; the successor kickoff starts it after setModel/setThinkingLevel.
9785
- triggerTurn: allowTrigger && shouldTrigger && !this.leaderRuntime.shouldDeferFollowUp()
11465
+ triggerTurn: wantsTrigger
9786
11466
  }
9787
11467
  );
9788
11468
  return shouldTrigger;
@@ -9936,7 +11616,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9936
11616
  if (raw.includes("\0") || raw.trim().length === 0) {
9937
11617
  throw new Error(`session_spawn contextFiles entry "${raw}" is invalid`);
9938
11618
  }
9939
- const target = resolve12(cwd, raw.trim());
11619
+ const target = resolve13(cwd, raw.trim());
9940
11620
  let canonical;
9941
11621
  try {
9942
11622
  canonical = await this.deps.realpath(target);
@@ -9961,7 +11641,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9961
11641
  if (raw.includes("\0") || raw.trim().length === 0) {
9962
11642
  throw new Error(`session_spawn readableDirs entry "${raw}" is invalid`);
9963
11643
  }
9964
- const target = resolve12(cwd, raw.trim());
11644
+ const target = resolve13(cwd, raw.trim());
9965
11645
  let canonical;
9966
11646
  try {
9967
11647
  canonical = await this.deps.realpath(target);
@@ -9979,7 +11659,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9979
11659
  return validated;
9980
11660
  }
9981
11661
  async resolveSpawnCwd(ctx, value) {
9982
- const requested = value?.trim() ? resolve12(ctx.cwd, value) : ctx.cwd;
11662
+ const requested = value?.trim() ? resolve13(ctx.cwd, value) : ctx.cwd;
9983
11663
  const canonical = await this.deps.realpath(requested);
9984
11664
  if (canonical.includes("\0") || Buffer.byteLength(canonical) > 4096) {
9985
11665
  throw new Error("Pi Agent Swarm child cwd is invalid or too large");
@@ -9994,6 +11674,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
9994
11674
  }
9995
11675
  async cleanupActive(reloading) {
9996
11676
  this.generation += 1;
11677
+ this.stopMissionTimers();
9997
11678
  this.stopExternalTurnSubscription();
9998
11679
  this.externalAutoNameMessages.length = 0;
9999
11680
  this.controller.abort();
@@ -10022,7 +11703,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
10022
11703
  membership?.group.secret.fill(0);
10023
11704
  }
10024
11705
  if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
10025
- await rm10(join15(directory, "lead.json"), { force: true }).catch(() => void 0);
11706
+ await rm11(join16(directory, "lead.json"), { force: true }).catch(() => void 0);
10026
11707
  }
10027
11708
  this.leadSessionId = void 0;
10028
11709
  this.leadRefreshEpoch += 1;
@@ -10046,40 +11727,52 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
10046
11727
  }
10047
11728
  beginStatus(ctx, text) {
10048
11729
  const token = { ctx, text };
11730
+ this.lastTransientStatusWidth = text ? visibleWidth3(text) + 2 : 0;
10049
11731
  try {
10050
11732
  ctx.ui.setStatus(STATUS_KEY, text);
10051
11733
  } catch {
10052
11734
  }
11735
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
10053
11736
  return token;
10054
11737
  }
10055
11738
  updateStatus(token, text) {
10056
11739
  token.text = text;
11740
+ this.lastTransientStatusWidth = text ? visibleWidth3(text) + 2 : 0;
10057
11741
  try {
10058
11742
  token.ctx.ui.setStatus(STATUS_KEY, text);
10059
11743
  } catch {
10060
11744
  }
11745
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
10061
11746
  }
10062
11747
  endStatus(token) {
11748
+ this.lastTransientStatusWidth = 0;
10063
11749
  try {
10064
11750
  token.ctx.ui.setStatus(STATUS_KEY, void 0);
10065
11751
  } catch {
10066
11752
  }
11753
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(token.ctx);
10067
11754
  }
10068
11755
  clearStatus(ctx) {
11756
+ this.lastTransientStatusWidth = 0;
10069
11757
  try {
10070
11758
  ctx.ui.setStatus(STATUS_KEY, void 0);
10071
11759
  } catch {
10072
11760
  }
11761
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
10073
11762
  }
10074
11763
  clearRosterStatus(ctx) {
11764
+ this.lastRosterBadgeWidth = 0;
11765
+ this.lastLeaderGenWidth = 0;
10075
11766
  try {
10076
11767
  ctx.ui.setStatus(ROSTER_STATUS_KEY, void 0);
11768
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, void 0);
10077
11769
  } catch {
10078
11770
  }
11771
+ if (isMissionLive(this.activeMission)) this.renderMissionStatus(ctx);
10079
11772
  }
10080
11773
  leadPath() {
10081
11774
  const directory = this.membership?.transport.endpointManifest?.directory;
10082
- return directory ? join15(directory, "lead.json") : void 0;
11775
+ return directory ? join16(directory, "lead.json") : void 0;
10083
11776
  }
10084
11777
  async republishCommittedLead() {
10085
11778
  const ctx = this.activeContext;
@@ -10100,7 +11793,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
10100
11793
  const path2 = this.leadPath();
10101
11794
  if (!path2) return this.applyObservedLead(void 0, epoch);
10102
11795
  try {
10103
- const raw = JSON.parse(await readFile6(path2, "utf8"));
11796
+ const raw = JSON.parse(await readFile7(path2, "utf8"));
10104
11797
  const next = typeof raw.sessionId === "string" ? raw.sessionId : void 0;
10105
11798
  return this.applyObservedLead(next, epoch);
10106
11799
  } catch {
@@ -10145,10 +11838,15 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
10145
11838
  const role = this.leadSessionId === sessionId || !self && this.defaultLead ? "LEADER" : "WORKER";
10146
11839
  const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
10147
11840
  const status = buildRosterBadge({ name, sessionId, color, role, columns });
11841
+ this.lastRosterBadgeWidth = visibleWidth3(status);
11842
+ const leaderGenText = role === "LEADER" && this.leaderGenerationNumber && this.leaderGenerationNumber > 1 ? `G${this.leaderGenerationNumber}` : void 0;
11843
+ this.lastLeaderGenWidth = leaderGenText ? visibleWidth3(leaderGenText) + 2 : 0;
10148
11844
  try {
10149
11845
  ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
11846
+ ctx.ui.setStatus(LEADER_GEN_STATUS_KEY, leaderGenText);
10150
11847
  } catch {
10151
11848
  }
11849
+ this.renderMissionStatus(ctx);
10152
11850
  }
10153
11851
  /** Resolve a peer by name or session id from the current snapshot. */
10154
11852
  async resolvePeer(target, signal) {
@@ -10174,7 +11872,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
10174
11872
  `, { encoding: "utf8", flag: "wx" });
10175
11873
  await rename5(temporary, path2);
10176
11874
  } finally {
10177
- await rm10(temporary, { force: true }).catch(() => void 0);
11875
+ await rm11(temporary, { force: true }).catch(() => void 0);
10178
11876
  }
10179
11877
  this.assertCurrentContext(ctx);
10180
11878
  if (target.sessionId !== this.committedLeadSessionId) {
@@ -10514,7 +12212,9 @@ function isRecord6(value) {
10514
12212
  import { StringEnum } from "@earendil-works/pi-ai";
10515
12213
  import { Type } from "typebox";
10516
12214
  var DIRECTIONS = ["right", "down", "left", "up"];
10517
- var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff", "catalog", "fanout"];
12215
+ var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff", "catalog", "fanout", "mission"];
12216
+ var MISSION_ACTIONS = ["start", "complete", "status"];
12217
+ var MISSION_OUTCOMES = ["achieved", "with_residuals"];
10518
12218
  var SEND_MODES = ["notify", "request"];
10519
12219
  var ROLES = ["implementer", "researcher", "reviewer"];
10520
12220
  var MAX_LISTED_PEERS = 64;
@@ -10661,7 +12361,54 @@ var busSchema = Type.Object(
10661
12361
  )
10662
12362
  ),
10663
12363
  deadlineMs: Type.Optional(Type.Integer({ minimum: 1e3, maximum: 36e5 })),
10664
- allowPartial: Type.Optional(Type.Boolean())
12364
+ allowPartial: Type.Optional(Type.Boolean()),
12365
+ missionAction: Type.Optional(
12366
+ StringEnum(MISSION_ACTIONS, {
12367
+ description: 'Sub-action for action="mission": "start" (establish first-principles requirement + time estimate), "complete" (close round, achieved or with_residuals), or "status".'
12368
+ })
12369
+ ),
12370
+ firstPrinciples: Type.Optional(
12371
+ Type.String({
12372
+ description: 'First-principles core requirement for this swarm round (the essential problem to solve, stripped of intermediate hacks). Required for missionAction="start".',
12373
+ maxLength: 4096
12374
+ })
12375
+ ),
12376
+ acceptanceCriteria: Type.Optional(
12377
+ Type.String({
12378
+ description: 'Objective completion criteria for this round. Required for missionAction="start".',
12379
+ maxLength: 4096
12380
+ })
12381
+ ),
12382
+ constraints: Type.Optional(
12383
+ Type.String({
12384
+ description: 'Optional hard constraints or non-goals for missionAction="start".',
12385
+ maxLength: 4096
12386
+ })
12387
+ ),
12388
+ estimatedMinutes: Type.Optional(
12389
+ Type.Number({
12390
+ description: 'Model self-assessed time budget in minutes for this round (clamped to configured bounds). Required for missionAction="start".',
12391
+ minimum: 0.01,
12392
+ maximum: 480
12393
+ })
12394
+ ),
12395
+ summary: Type.Optional(
12396
+ Type.String({
12397
+ description: 'Completion summary for missionAction="complete" (what was achieved and current state).',
12398
+ maxLength: 8192
12399
+ })
12400
+ ),
12401
+ outcome: Type.Optional(
12402
+ StringEnum(MISSION_OUTCOMES, {
12403
+ description: 'Completion outcome for missionAction="complete": "achieved" or "with_residuals" (explicitly acceptable on timeout convergence).'
12404
+ })
12405
+ ),
12406
+ residuals: Type.Optional(
12407
+ Type.Array(Type.String({ minLength: 1, maxLength: 1024 }), {
12408
+ description: "Optional list of remaining open items, residuals, or unresolved contradictions recorded when completing with_residuals.",
12409
+ maxItems: 32
12410
+ })
12411
+ )
10665
12412
  },
10666
12413
  { additionalProperties: false }
10667
12414
  );
@@ -10673,9 +12420,11 @@ function registerSwarmTools(pi, controller) {
10673
12420
  promptSnippet: "Start a collaborating Pi session in an external terminal window",
10674
12421
  promptGuidelines: [
10675
12422
  "Use session_spawn only when the user explicitly asks to open or start another Pi session.",
12423
+ `Before spawning workers for a new swarm round, establish the round's first-principles requirement and time estimate via session_bus(action="mission", missionAction="start", firstPrinciples, acceptanceCriteria, estimatedMinutes); when the countdown expires, converge and complete promptly (completing with documented residuals/contradictions is explicitly preferred over endless iteration).`,
10676
12424
  "Do not claim the child is ready until session_spawn returns authenticated readiness metadata.",
10677
12425
  "Use allowRequests only when the user wants this worker to accept follow-up tasks in the same session; it defaults to false.",
10678
- "Use contextRecycling only with explicit user authorization for bounded automatic worker replacement; the threshold is soft and never interrupts a healthy turn."
12426
+ "Use contextRecycling only with explicit user authorization for bounded automatic worker replacement; the threshold is soft and never interrupts a healthy turn.",
12427
+ 'Separate generation from verification: after substantive implementer changes (multi-file edits, core logic, reverse-engineering/hardware verification, or phase sign-off), spawn an independent read-only reviewer (role="reviewer", preferring a different model family) to obtain an immutable JSON verdict.'
10679
12428
  ],
10680
12429
  parameters: spawnSchema,
10681
12430
  executionMode: "sequential",
@@ -10714,6 +12463,33 @@ function registerSwarmTools(pi, controller) {
10714
12463
  parameters: busSchema,
10715
12464
  executionMode: "sequential",
10716
12465
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
12466
+ if (params.action === "mission") {
12467
+ assertAbsent(params.targetSessionId, "targetSessionId", "mission");
12468
+ assertAbsent(params.message, "message", "mission");
12469
+ assertAbsent(params.mode, "mode", "mission");
12470
+ assertAbsent(params.replyTo, "replyTo", "mission");
12471
+ assertAbsent(params.taskStatus, "taskStatus", "mission");
12472
+ assertAbsent(params.handoff, "handoff", "mission");
12473
+ assertAbsent(params.branches, "branches", "mission");
12474
+ if (!controller.manageMission) throw new Error("session_bus mission is unavailable");
12475
+ if (!params.missionAction) {
12476
+ throw new Error('session_bus missionAction ("start" | "complete" | "status") is required for action mission');
12477
+ }
12478
+ const result2 = await controller.manageMission(ctx, {
12479
+ missionAction: params.missionAction,
12480
+ ...params.firstPrinciples !== void 0 ? { firstPrinciples: params.firstPrinciples } : {},
12481
+ ...params.acceptanceCriteria !== void 0 ? { acceptanceCriteria: params.acceptanceCriteria } : {},
12482
+ ...params.constraints !== void 0 ? { constraints: params.constraints } : {},
12483
+ ...params.estimatedMinutes !== void 0 ? { estimatedMinutes: params.estimatedMinutes } : {},
12484
+ ...params.summary !== void 0 ? { summary: params.summary } : {},
12485
+ ...params.outcome !== void 0 ? { outcome: params.outcome } : {},
12486
+ ...params.residuals !== void 0 ? { residuals: params.residuals } : {}
12487
+ });
12488
+ return {
12489
+ content: [{ type: "text", text: result2.message }],
12490
+ details: result2
12491
+ };
12492
+ }
10717
12493
  if (params.action === "catalog") {
10718
12494
  assertAbsent(params.targetSessionId, "targetSessionId", "catalog");
10719
12495
  assertAbsent(params.message, "message", "catalog");
@@ -10945,7 +12721,7 @@ function createPiSwarmExtension(dependencies = {}) {
10945
12721
  return function piSwarmExtension(pi) {
10946
12722
  const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
10947
12723
  const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
10948
- const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-NLK5I2DA.ts")));
12724
+ const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-A2TQAWN6.ts")));
10949
12725
  pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
10950
12726
  registerSwarmTools(pi, controller);
10951
12727
  pi.on("session_start", async (event, ctx) => {
@@ -10975,6 +12751,9 @@ function createPiSwarmExtension(dependencies = {}) {
10975
12751
  pi.on("agent_settled", async (event, ctx) => {
10976
12752
  await controller.agentSettled(ctx, event.aborted);
10977
12753
  });
12754
+ pi.on("cache_warming_decision", (event, ctx) => {
12755
+ return controller.decideCacheWarming(event, ctx);
12756
+ });
10978
12757
  pi.on("session_info_changed", async (event, ctx) => {
10979
12758
  await controller.noteSessionInfoChanged(event.name, ctx);
10980
12759
  });