pi-agent-swarm 0.5.0 → 0.6.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 +1486 -154
- package/dist/index.ts.map +4 -4
- package/package.json +1 -1
- package/src/cache-warming.ts +147 -0
- package/src/external-runtime.ts +216 -0
- package/src/lead-mcp-bridge.ts +43 -2
- package/src/leader-handoff-bridge.ts +6 -0
- package/src/leader-recycling.ts +16 -3
- package/src/leader-runtime.ts +132 -10
- package/src/leader-session-runtime.ts +23 -0
- package/src/ledger.ts +28 -1
- package/src/mission.ts +293 -0
- package/src/org.ts +10 -0
- package/src/pi-agent-swarm.ts +3 -0
- package/src/reviewer.ts +88 -0
- package/src/settings.ts +203 -1
- package/src/swarm-controller.ts +687 -6
- package/src/tools.ts +103 -1
package/dist/index.ts
CHANGED
|
@@ -644,8 +644,8 @@ var renderSwarmMessage = (message, options, theme) => {
|
|
|
644
644
|
// src/settings.ts
|
|
645
645
|
import { randomUUID } from "node:crypto";
|
|
646
646
|
import { constants } from "node:fs";
|
|
647
|
-
import { lstat as lstat2, mkdir as mkdir3, open as open2, rename as rename3, rm as
|
|
648
|
-
import { basename as basename2, dirname as dirname2, join as
|
|
647
|
+
import { lstat as lstat2, mkdir as mkdir3, open as open2, rename as rename3, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
|
|
648
|
+
import { basename as basename2, dirname as dirname2, join as join4 } from "node:path";
|
|
649
649
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
650
650
|
|
|
651
651
|
// src/auto-name.ts
|
|
@@ -1477,8 +1477,8 @@ async function atomicText(path2, content) {
|
|
|
1477
1477
|
try {
|
|
1478
1478
|
await rename(temporary, path2);
|
|
1479
1479
|
} catch (error) {
|
|
1480
|
-
const { rm:
|
|
1481
|
-
await
|
|
1480
|
+
const { rm: rm12 } = await import("node:fs/promises");
|
|
1481
|
+
await rm12(temporary, { force: true }).catch(() => void 0);
|
|
1482
1482
|
throw error;
|
|
1483
1483
|
}
|
|
1484
1484
|
}
|
|
@@ -1681,6 +1681,169 @@ function isMissing(error) {
|
|
|
1681
1681
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
1682
1682
|
}
|
|
1683
1683
|
|
|
1684
|
+
// src/mission.ts
|
|
1685
|
+
import { readFile as readFile3, rm as rm3 } from "node:fs/promises";
|
|
1686
|
+
import { join as join3, resolve as resolve3 } from "node:path";
|
|
1687
|
+
var DEFAULT_MISSION_COUNTDOWN_SETTINGS = Object.freeze({
|
|
1688
|
+
enabled: true,
|
|
1689
|
+
requireBeforeSpawn: false,
|
|
1690
|
+
minMinutes: 2,
|
|
1691
|
+
maxMinutes: 90,
|
|
1692
|
+
wrapUpGraceMs: 5 * 6e4
|
|
1693
|
+
});
|
|
1694
|
+
var FINAL_WRAP_UP_AUTO_CLOSE_FACTOR = 0.4;
|
|
1695
|
+
var MIN_FINAL_WRAP_UP_MS = 100;
|
|
1696
|
+
function missionPaths(projectRoot) {
|
|
1697
|
+
const root = resolve3(projectRoot);
|
|
1698
|
+
const storageRoot = resolve3(root, WORKER_RECYCLING_DIRECTORY);
|
|
1699
|
+
const missionsDirectory = join3(storageRoot, "missions");
|
|
1700
|
+
return {
|
|
1701
|
+
root: storageRoot,
|
|
1702
|
+
missionsDirectory,
|
|
1703
|
+
activePath: join3(missionsDirectory, "active.json"),
|
|
1704
|
+
historyDirectory: join3(missionsDirectory, "history")
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
function isMissionLive(record3) {
|
|
1708
|
+
return record3 !== void 0 && (record3.state === "active" || record3.state === "converging" || record3.state === "final_wrap_up");
|
|
1709
|
+
}
|
|
1710
|
+
function isMissionConverging(record3) {
|
|
1711
|
+
return record3 !== void 0 && (record3.state === "converging" || record3.state === "final_wrap_up");
|
|
1712
|
+
}
|
|
1713
|
+
function validateMissionStartInput(input, settings) {
|
|
1714
|
+
const firstPrinciples = typeof input.firstPrinciples === "string" ? input.firstPrinciples.trim() : "";
|
|
1715
|
+
if (firstPrinciples.length === 0 || firstPrinciples.length > 4096) {
|
|
1716
|
+
throw new Error("Mission firstPrinciples must be a non-empty string (max 4096 chars).");
|
|
1717
|
+
}
|
|
1718
|
+
const acceptanceCriteria = typeof input.acceptanceCriteria === "string" ? input.acceptanceCriteria.trim() : "";
|
|
1719
|
+
if (acceptanceCriteria.length === 0 || acceptanceCriteria.length > 4096) {
|
|
1720
|
+
throw new Error("Mission acceptanceCriteria must be a non-empty string (max 4096 chars).");
|
|
1721
|
+
}
|
|
1722
|
+
const constraints = typeof input.constraints === "string" && input.constraints.trim().length > 0 ? input.constraints.trim().slice(0, 4096) : void 0;
|
|
1723
|
+
const combined = `${firstPrinciples}
|
|
1724
|
+
${acceptanceCriteria}
|
|
1725
|
+
${constraints ?? ""}`;
|
|
1726
|
+
if (SECRET_PATTERNS.some((pattern) => pattern.test(combined))) {
|
|
1727
|
+
throw new Error("Mission definition must not contain swarm invite tokens or secret credentials.");
|
|
1728
|
+
}
|
|
1729
|
+
const requestedMinutes = input.estimatedMinutes;
|
|
1730
|
+
if (typeof requestedMinutes !== "number" || !Number.isFinite(requestedMinutes) || requestedMinutes <= 0) {
|
|
1731
|
+
throw new Error("Mission estimatedMinutes must be a positive finite number.");
|
|
1732
|
+
}
|
|
1733
|
+
const min = Math.max(1e-3, settings.minMinutes);
|
|
1734
|
+
const max = Math.max(min, settings.maxMinutes);
|
|
1735
|
+
const estimatedMinutes = Math.min(max, Math.max(min, requestedMinutes));
|
|
1736
|
+
return {
|
|
1737
|
+
firstPrinciples,
|
|
1738
|
+
acceptanceCriteria,
|
|
1739
|
+
...constraints ? { constraints } : {},
|
|
1740
|
+
requestedMinutes,
|
|
1741
|
+
estimatedMinutes,
|
|
1742
|
+
clamped: estimatedMinutes !== requestedMinutes
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
function validateMissionCompleteInput(input) {
|
|
1746
|
+
const summary = typeof input.summary === "string" ? input.summary.trim() : "";
|
|
1747
|
+
if (summary.length === 0 || summary.length > 8192) {
|
|
1748
|
+
throw new Error("Mission complete requires a non-empty summary (max 8192 chars).");
|
|
1749
|
+
}
|
|
1750
|
+
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) : [];
|
|
1751
|
+
const outcome = input.outcome === "with_residuals" || residuals.length > 0 ? "with_residuals" : "achieved";
|
|
1752
|
+
return { summary, outcome, residuals };
|
|
1753
|
+
}
|
|
1754
|
+
async function readActiveMission(projectRoot) {
|
|
1755
|
+
const paths = missionPaths(projectRoot);
|
|
1756
|
+
try {
|
|
1757
|
+
const raw = await readFile3(paths.activePath, "utf8");
|
|
1758
|
+
const parsed = JSON.parse(raw);
|
|
1759
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
|
|
1760
|
+
const rec = parsed;
|
|
1761
|
+
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") {
|
|
1762
|
+
return void 0;
|
|
1763
|
+
}
|
|
1764
|
+
return parsed;
|
|
1765
|
+
} catch {
|
|
1766
|
+
return void 0;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
async function writeActiveMission(projectRoot, record3) {
|
|
1770
|
+
const paths = missionPaths(projectRoot);
|
|
1771
|
+
await ensureStorageRoot(paths);
|
|
1772
|
+
await atomicJson(paths.activePath, record3);
|
|
1773
|
+
}
|
|
1774
|
+
async function archiveMission(projectRoot, record3) {
|
|
1775
|
+
const paths = missionPaths(projectRoot);
|
|
1776
|
+
await ensureStorageRoot(paths);
|
|
1777
|
+
const safeId2 = record3.missionId.replace(/[^A-Za-z0-9_-]/gu, "_");
|
|
1778
|
+
const historyPath = join3(paths.historyDirectory, `${safeId2}.json`);
|
|
1779
|
+
await atomicJson(historyPath, record3);
|
|
1780
|
+
await rm3(paths.activePath, { force: true }).catch(() => void 0);
|
|
1781
|
+
return historyPath;
|
|
1782
|
+
}
|
|
1783
|
+
function checkMissionSpawnGate(params) {
|
|
1784
|
+
if (!params.settings.enabled) return { allowed: true };
|
|
1785
|
+
const live = isMissionLive(params.mission) ? params.mission : void 0;
|
|
1786
|
+
if (!live) {
|
|
1787
|
+
if (!params.settings.requireBeforeSpawn) return { allowed: true };
|
|
1788
|
+
return {
|
|
1789
|
+
allowed: false,
|
|
1790
|
+
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>).`
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
if (live.state === "converging" || live.state === "final_wrap_up") {
|
|
1794
|
+
if (params.role === "reviewer") {
|
|
1795
|
+
return { allowed: true };
|
|
1796
|
+
}
|
|
1797
|
+
return {
|
|
1798
|
+
allowed: false,
|
|
1799
|
+
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=[...]).`
|
|
1800
|
+
};
|
|
1801
|
+
}
|
|
1802
|
+
return { allowed: true };
|
|
1803
|
+
}
|
|
1804
|
+
function formatMissionTimeoutInjection(params) {
|
|
1805
|
+
const { mission, stage, now, inFlightWorkerCount, busToolName } = params;
|
|
1806
|
+
const elapsedMin = Math.max(0, (now - mission.startedAt) / 6e4).toFixed(1);
|
|
1807
|
+
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).`;
|
|
1808
|
+
const lines = [
|
|
1809
|
+
header,
|
|
1810
|
+
"",
|
|
1811
|
+
"### First-Principles Requirement (Re-Anchor)",
|
|
1812
|
+
mission.firstPrinciples,
|
|
1813
|
+
"",
|
|
1814
|
+
"### Acceptance Criteria",
|
|
1815
|
+
mission.acceptanceCriteria,
|
|
1816
|
+
...mission.constraints ? ["", "### Hard Constraints", mission.constraints] : [],
|
|
1817
|
+
"",
|
|
1818
|
+
`### Current Runtime State`,
|
|
1819
|
+
`- Mission state: ${stage} (elapsed ${elapsedMin}m / budget ${mission.estimatedMinutes}m)`,
|
|
1820
|
+
`- In-flight workers awaiting reply: ${inFlightWorkerCount}`,
|
|
1821
|
+
"",
|
|
1822
|
+
"### Required Action (Converge \u2014 Only Two Outcomes)",
|
|
1823
|
+
`1. Complete now if the first-principles objective is met: call ${busToolName}(action="mission", missionAction="complete", summary="...", outcome="achieved").`,
|
|
1824
|
+
`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).`,
|
|
1825
|
+
` Call ${busToolName}(action="mission", missionAction="complete", summary="...", outcome="with_residuals", residuals=["..."]).`
|
|
1826
|
+
];
|
|
1827
|
+
if (stage === "final_wrap_up") {
|
|
1828
|
+
lines.push(
|
|
1829
|
+
"",
|
|
1830
|
+
"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."
|
|
1831
|
+
);
|
|
1832
|
+
}
|
|
1833
|
+
return lines.join("\n");
|
|
1834
|
+
}
|
|
1835
|
+
function formatMissionStatusBadge(record3, now) {
|
|
1836
|
+
if (!isMissionLive(record3)) return void 0;
|
|
1837
|
+
if (record3.state === "final_wrap_up") return "\u23F1 FINAL";
|
|
1838
|
+
if (record3.state === "converging") return "\u23F1 WRAP-UP";
|
|
1839
|
+
const remainMs = Math.max(0, record3.deadlineAt - now);
|
|
1840
|
+
if (remainMs <= 0) return "\u23F1 WRAP-UP";
|
|
1841
|
+
const remainSec = Math.ceil(remainMs / 1e3);
|
|
1842
|
+
if (remainSec < 120) return `\u23F1 ${remainSec}s`;
|
|
1843
|
+
const remainMin = Math.ceil(remainMs / 6e4);
|
|
1844
|
+
return `\u23F1 ${remainMin}m`;
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1684
1847
|
// src/settings.ts
|
|
1685
1848
|
var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
|
|
1686
1849
|
var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
|
|
@@ -1692,6 +1855,12 @@ var DEFAULT_LEADER_RECYCLING_SETTINGS = Object.freeze({
|
|
|
1692
1855
|
highWaterPercent: 75,
|
|
1693
1856
|
maxReplacements: 3
|
|
1694
1857
|
});
|
|
1858
|
+
var DEFAULT_CACHE_WARMING_SETTINGS = Object.freeze({
|
|
1859
|
+
enabled: true,
|
|
1860
|
+
maxWaitDurationMs: 30 * 6e4,
|
|
1861
|
+
maxRefreshesPerWait: 8
|
|
1862
|
+
});
|
|
1863
|
+
var DEFAULT_REVIEW_POLICY = "suggest";
|
|
1695
1864
|
var DEFAULT_SWARM_SETTINGS = Object.freeze({
|
|
1696
1865
|
autoName: true,
|
|
1697
1866
|
colorPalette: "muted",
|
|
@@ -1703,7 +1872,10 @@ var DEFAULT_SWARM_SETTINGS = Object.freeze({
|
|
|
1703
1872
|
resourceLeases: true,
|
|
1704
1873
|
leaderRecycling: DEFAULT_LEADER_RECYCLING_SETTINGS,
|
|
1705
1874
|
ledger: DEFAULT_LEDGER_SETTINGS,
|
|
1706
|
-
budget: DEFAULT_SWARM_BUDGET_SETTINGS
|
|
1875
|
+
budget: DEFAULT_SWARM_BUDGET_SETTINGS,
|
|
1876
|
+
cacheWarming: DEFAULT_CACHE_WARMING_SETTINGS,
|
|
1877
|
+
missionCountdown: DEFAULT_MISSION_COUNTDOWN_SETTINGS,
|
|
1878
|
+
reviewPolicy: DEFAULT_REVIEW_POLICY
|
|
1707
1879
|
});
|
|
1708
1880
|
var SETTING_FIELDS = [
|
|
1709
1881
|
"autoName",
|
|
@@ -1718,12 +1890,15 @@ var SETTING_FIELDS = [
|
|
|
1718
1890
|
"leaderRecycling",
|
|
1719
1891
|
"ledger",
|
|
1720
1892
|
"budget",
|
|
1893
|
+
"cacheWarming",
|
|
1894
|
+
"missionCountdown",
|
|
1895
|
+
"reviewPolicy",
|
|
1721
1896
|
"profilesDir",
|
|
1722
1897
|
"allowedProfiles"
|
|
1723
1898
|
];
|
|
1724
1899
|
var SETTING_FIELD_SET = new Set(SETTING_FIELDS);
|
|
1725
1900
|
function swarmSettingsFilePath() {
|
|
1726
|
-
return
|
|
1901
|
+
return join4(getAgentDir(), SWARM_SETTINGS_FILE);
|
|
1727
1902
|
}
|
|
1728
1903
|
function normalizeLeaderRecycling(value) {
|
|
1729
1904
|
if (value === void 0) return { settings: { ...DEFAULT_LEADER_RECYCLING_SETTINGS }, warnings: [] };
|
|
@@ -1744,6 +1919,14 @@ function normalizeLeaderRecycling(value) {
|
|
|
1744
1919
|
return DEFAULT_LEADER_RECYCLING_SETTINGS[field];
|
|
1745
1920
|
};
|
|
1746
1921
|
const integer = (minimum, maximum) => (candidate) => typeof candidate === "number" && Number.isInteger(candidate) && candidate >= minimum && candidate <= maximum;
|
|
1922
|
+
let highWaterTokens;
|
|
1923
|
+
if (value.highWaterTokens !== void 0) {
|
|
1924
|
+
if (integer(1, 1e7)(value.highWaterTokens)) {
|
|
1925
|
+
highWaterTokens = value.highWaterTokens;
|
|
1926
|
+
} else {
|
|
1927
|
+
warnings.push("leaderRecycling.highWaterTokens must be an integer from 1 to 10000000; ignoring invalid value.");
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1747
1930
|
return {
|
|
1748
1931
|
settings: {
|
|
1749
1932
|
enabled: read(
|
|
@@ -1759,11 +1942,103 @@ function normalizeLeaderRecycling(value) {
|
|
|
1759
1942
|
softContextPercent: read("softContextPercent", integer(1, 100), "must be an integer from 1 to 100"),
|
|
1760
1943
|
softContextTokens: read("softContextTokens", integer(1, 1e7), "must be an integer from 1 to 10000000"),
|
|
1761
1944
|
highWaterPercent: read("highWaterPercent", integer(1, 100), "must be an integer from 1 to 100"),
|
|
1945
|
+
...highWaterTokens !== void 0 ? { highWaterTokens } : {},
|
|
1762
1946
|
maxReplacements: read("maxReplacements", integer(0, 10), "must be an integer from 0 to 10")
|
|
1763
1947
|
},
|
|
1764
1948
|
warnings
|
|
1765
1949
|
};
|
|
1766
1950
|
}
|
|
1951
|
+
function normalizeCacheWarmingSettings(value) {
|
|
1952
|
+
if (value === void 0) return { settings: { ...DEFAULT_CACHE_WARMING_SETTINGS }, warnings: [] };
|
|
1953
|
+
if (!isRecord3(value)) {
|
|
1954
|
+
return {
|
|
1955
|
+
settings: { ...DEFAULT_CACHE_WARMING_SETTINGS },
|
|
1956
|
+
warnings: ["cacheWarming must be an object; using all cacheWarming defaults."]
|
|
1957
|
+
};
|
|
1958
|
+
}
|
|
1959
|
+
const warnings = [];
|
|
1960
|
+
let enabled = DEFAULT_CACHE_WARMING_SETTINGS.enabled;
|
|
1961
|
+
if (value.enabled !== void 0) {
|
|
1962
|
+
if (typeof value.enabled === "boolean") enabled = value.enabled;
|
|
1963
|
+
else warnings.push(`cacheWarming.enabled must be a boolean; using ${String(enabled)}.`);
|
|
1964
|
+
}
|
|
1965
|
+
let maxWaitDurationMs = DEFAULT_CACHE_WARMING_SETTINGS.maxWaitDurationMs;
|
|
1966
|
+
if (value.maxWaitDurationMs !== void 0) {
|
|
1967
|
+
if (typeof value.maxWaitDurationMs === "number" && Number.isInteger(value.maxWaitDurationMs) && value.maxWaitDurationMs >= 6e4 && value.maxWaitDurationMs <= 36e5) {
|
|
1968
|
+
maxWaitDurationMs = value.maxWaitDurationMs;
|
|
1969
|
+
} else {
|
|
1970
|
+
warnings.push(
|
|
1971
|
+
`cacheWarming.maxWaitDurationMs must be an integer from 60000 to 3600000; using ${String(maxWaitDurationMs)}.`
|
|
1972
|
+
);
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
let maxRefreshesPerWait = DEFAULT_CACHE_WARMING_SETTINGS.maxRefreshesPerWait;
|
|
1976
|
+
if (value.maxRefreshesPerWait !== void 0) {
|
|
1977
|
+
if (typeof value.maxRefreshesPerWait === "number" && Number.isInteger(value.maxRefreshesPerWait) && value.maxRefreshesPerWait >= 1 && value.maxRefreshesPerWait <= 30) {
|
|
1978
|
+
maxRefreshesPerWait = value.maxRefreshesPerWait;
|
|
1979
|
+
} else {
|
|
1980
|
+
warnings.push(
|
|
1981
|
+
`cacheWarming.maxRefreshesPerWait must be an integer from 1 to 30; using ${String(maxRefreshesPerWait)}.`
|
|
1982
|
+
);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
return { settings: { enabled, maxWaitDurationMs, maxRefreshesPerWait }, warnings };
|
|
1986
|
+
}
|
|
1987
|
+
function normalizeMissionCountdownSettings(value) {
|
|
1988
|
+
if (value === void 0) return { settings: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS }, warnings: [] };
|
|
1989
|
+
if (!isRecord3(value)) {
|
|
1990
|
+
return {
|
|
1991
|
+
settings: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS },
|
|
1992
|
+
warnings: ["missionCountdown must be an object; using all missionCountdown defaults."]
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
const warnings = [];
|
|
1996
|
+
let enabled = DEFAULT_MISSION_COUNTDOWN_SETTINGS.enabled;
|
|
1997
|
+
if (value.enabled !== void 0) {
|
|
1998
|
+
if (typeof value.enabled === "boolean") enabled = value.enabled;
|
|
1999
|
+
else warnings.push(`missionCountdown.enabled must be a boolean; using ${String(enabled)}.`);
|
|
2000
|
+
}
|
|
2001
|
+
let requireBeforeSpawn = DEFAULT_MISSION_COUNTDOWN_SETTINGS.requireBeforeSpawn;
|
|
2002
|
+
if (value.requireBeforeSpawn !== void 0) {
|
|
2003
|
+
if (typeof value.requireBeforeSpawn === "boolean") requireBeforeSpawn = value.requireBeforeSpawn;
|
|
2004
|
+
else {
|
|
2005
|
+
warnings.push(`missionCountdown.requireBeforeSpawn must be a boolean; using ${String(requireBeforeSpawn)}.`);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
let minMinutes = DEFAULT_MISSION_COUNTDOWN_SETTINGS.minMinutes;
|
|
2009
|
+
if (value.minMinutes !== void 0) {
|
|
2010
|
+
if (typeof value.minMinutes === "number" && Number.isFinite(value.minMinutes) && value.minMinutes > 0 && value.minMinutes <= 60) {
|
|
2011
|
+
minMinutes = value.minMinutes;
|
|
2012
|
+
} else {
|
|
2013
|
+
warnings.push(`missionCountdown.minMinutes must be a positive number <= 60; using ${String(minMinutes)}.`);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
let maxMinutes = DEFAULT_MISSION_COUNTDOWN_SETTINGS.maxMinutes;
|
|
2017
|
+
if (value.maxMinutes !== void 0) {
|
|
2018
|
+
if (typeof value.maxMinutes === "number" && Number.isFinite(value.maxMinutes) && value.maxMinutes >= minMinutes && value.maxMinutes <= 480) {
|
|
2019
|
+
maxMinutes = value.maxMinutes;
|
|
2020
|
+
} else {
|
|
2021
|
+
warnings.push(
|
|
2022
|
+
`missionCountdown.maxMinutes must be a number from ${String(minMinutes)} to 480; using ${String(maxMinutes)}.`
|
|
2023
|
+
);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
if (maxMinutes < minMinutes) maxMinutes = minMinutes;
|
|
2027
|
+
let wrapUpGraceMs = DEFAULT_MISSION_COUNTDOWN_SETTINGS.wrapUpGraceMs;
|
|
2028
|
+
if (value.wrapUpGraceMs !== void 0) {
|
|
2029
|
+
if (typeof value.wrapUpGraceMs === "number" && Number.isInteger(value.wrapUpGraceMs) && value.wrapUpGraceMs >= 100 && value.wrapUpGraceMs <= 36e5) {
|
|
2030
|
+
wrapUpGraceMs = value.wrapUpGraceMs;
|
|
2031
|
+
} else {
|
|
2032
|
+
warnings.push(
|
|
2033
|
+
`missionCountdown.wrapUpGraceMs must be an integer from 100 to 3600000; using ${String(wrapUpGraceMs)}.`
|
|
2034
|
+
);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
return {
|
|
2038
|
+
settings: { enabled, requireBeforeSpawn, minMinutes, maxMinutes, wrapUpGraceMs },
|
|
2039
|
+
warnings
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
1767
2042
|
function normalizeLedgerSettings(value) {
|
|
1768
2043
|
if (value === void 0) return { settings: { ...DEFAULT_LEDGER_SETTINGS }, warnings: [] };
|
|
1769
2044
|
if (!isRecord3(value)) {
|
|
@@ -1927,6 +2202,19 @@ function normalizeSwarmSettingsDocument(value) {
|
|
|
1927
2202
|
const budget = normalizeBudgetSettings(value.budget);
|
|
1928
2203
|
settings.budget = budget.settings;
|
|
1929
2204
|
if (Object.hasOwn(value, "budget")) sources.budget = "user";
|
|
2205
|
+
const cacheWarming = normalizeCacheWarmingSettings(value.cacheWarming);
|
|
2206
|
+
settings.cacheWarming = cacheWarming.settings;
|
|
2207
|
+
if (Object.hasOwn(value, "cacheWarming")) sources.cacheWarming = "user";
|
|
2208
|
+
const missionCountdown = normalizeMissionCountdownSettings(value.missionCountdown);
|
|
2209
|
+
settings.missionCountdown = missionCountdown.settings;
|
|
2210
|
+
if (Object.hasOwn(value, "missionCountdown")) sources.missionCountdown = "user";
|
|
2211
|
+
if (Object.hasOwn(value, "reviewPolicy")) {
|
|
2212
|
+
if (value.reviewPolicy !== "off" && value.reviewPolicy !== "suggest" && value.reviewPolicy !== "required") {
|
|
2213
|
+
return void 0;
|
|
2214
|
+
}
|
|
2215
|
+
settings.reviewPolicy = value.reviewPolicy;
|
|
2216
|
+
sources.reviewPolicy = "user";
|
|
2217
|
+
}
|
|
1930
2218
|
if (Object.hasOwn(value, "profilesDir")) {
|
|
1931
2219
|
if (typeof value.profilesDir !== "string" || value.profilesDir.trim().length === 0 || value.profilesDir.includes("\0")) {
|
|
1932
2220
|
return void 0;
|
|
@@ -1941,7 +2229,13 @@ function normalizeSwarmSettingsDocument(value) {
|
|
|
1941
2229
|
settings.allowedProfiles = [...new Set(value.allowedProfiles)];
|
|
1942
2230
|
sources.allowedProfiles = "user";
|
|
1943
2231
|
}
|
|
1944
|
-
const warnings = [
|
|
2232
|
+
const warnings = [
|
|
2233
|
+
...leaderRecycling.warnings,
|
|
2234
|
+
...ledger.warnings,
|
|
2235
|
+
...budget.warnings,
|
|
2236
|
+
...cacheWarming.warnings,
|
|
2237
|
+
...missionCountdown.warnings
|
|
2238
|
+
];
|
|
1945
2239
|
return { settings, sources, ...warnings.length > 0 ? { warnings } : {} };
|
|
1946
2240
|
}
|
|
1947
2241
|
async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
|
|
@@ -2004,6 +2298,9 @@ function createInMemorySwarmSettingsRuntime(initial = {}) {
|
|
|
2004
2298
|
...canonical.leaderRecycling !== void 0 ? { leaderRecycling: "user" } : {},
|
|
2005
2299
|
...canonical.ledger !== void 0 ? { ledger: "user" } : {},
|
|
2006
2300
|
...canonical.budget !== void 0 ? { budget: "user" } : {},
|
|
2301
|
+
...canonical.cacheWarming !== void 0 ? { cacheWarming: "user" } : {},
|
|
2302
|
+
...canonical.missionCountdown !== void 0 ? { missionCountdown: "user" } : {},
|
|
2303
|
+
...canonical.reviewPolicy !== void 0 ? { reviewPolicy: "user" } : {},
|
|
2007
2304
|
...canonical.profilesDir !== void 0 ? { profilesDir: "user" } : {},
|
|
2008
2305
|
...canonical.allowedProfiles !== void 0 ? { allowedProfiles: "user" } : {}
|
|
2009
2306
|
},
|
|
@@ -2080,6 +2377,18 @@ function createSwarmSettingsRuntime(options = {}) {
|
|
|
2080
2377
|
...canonicalPatch.budget
|
|
2081
2378
|
};
|
|
2082
2379
|
}
|
|
2380
|
+
if (canonicalPatch.cacheWarming && isRecord3(latest.document.cacheWarming)) {
|
|
2381
|
+
document.cacheWarming = {
|
|
2382
|
+
...latest.document.cacheWarming,
|
|
2383
|
+
...canonicalPatch.cacheWarming
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
if (canonicalPatch.missionCountdown && isRecord3(latest.document.missionCountdown)) {
|
|
2387
|
+
document.missionCountdown = {
|
|
2388
|
+
...latest.document.missionCountdown,
|
|
2389
|
+
...canonicalPatch.missionCountdown
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2083
2392
|
const normalized = normalizeSwarmSettingsDocument(document);
|
|
2084
2393
|
if (!normalized) throw new Error("Refusing to publish invalid Pi Agent Swarm settings.");
|
|
2085
2394
|
await publishSettingsDocument(document, getPath(), operations);
|
|
@@ -2114,7 +2423,7 @@ async function publishSettingsDocument(document, path2, operations) {
|
|
|
2114
2423
|
throw new Error(`settings document exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
|
|
2115
2424
|
}
|
|
2116
2425
|
await mkdir3(dirname2(path2), { recursive: true });
|
|
2117
|
-
const temporaryPath =
|
|
2426
|
+
const temporaryPath = join4(dirname2(path2), `.${basename2(path2)}.${process.pid}.${randomUUID()}.tmp`);
|
|
2118
2427
|
try {
|
|
2119
2428
|
await operations.writeFile(temporaryPath, contents, {
|
|
2120
2429
|
encoding: "utf8",
|
|
@@ -2123,7 +2432,7 @@ async function publishSettingsDocument(document, path2, operations) {
|
|
|
2123
2432
|
});
|
|
2124
2433
|
await operations.rename(temporaryPath, path2);
|
|
2125
2434
|
} finally {
|
|
2126
|
-
await
|
|
2435
|
+
await rm4(temporaryPath, { force: true }).catch(() => void 0);
|
|
2127
2436
|
}
|
|
2128
2437
|
}
|
|
2129
2438
|
async function readSettingsDocument(path2, signal) {
|
|
@@ -2190,6 +2499,9 @@ function builtInSources() {
|
|
|
2190
2499
|
leaderRecycling: "built-in",
|
|
2191
2500
|
ledger: "built-in",
|
|
2192
2501
|
budget: "built-in",
|
|
2502
|
+
cacheWarming: "built-in",
|
|
2503
|
+
missionCountdown: "built-in",
|
|
2504
|
+
reviewPolicy: "built-in",
|
|
2193
2505
|
profilesDir: "built-in",
|
|
2194
2506
|
allowedProfiles: "built-in"
|
|
2195
2507
|
};
|
|
@@ -2203,7 +2515,10 @@ function defaultSettings() {
|
|
|
2203
2515
|
maxChildren: DEFAULT_SWARM_BUDGET_SETTINGS.maxChildren,
|
|
2204
2516
|
standard: { ...DEFAULT_STANDARD_BUDGET },
|
|
2205
2517
|
heavy: { ...DEFAULT_HEAVY_BUDGET }
|
|
2206
|
-
}
|
|
2518
|
+
},
|
|
2519
|
+
cacheWarming: { ...DEFAULT_CACHE_WARMING_SETTINGS },
|
|
2520
|
+
missionCountdown: { ...DEFAULT_MISSION_COUNTDOWN_SETTINGS },
|
|
2521
|
+
reviewPolicy: DEFAULT_REVIEW_POLICY
|
|
2207
2522
|
};
|
|
2208
2523
|
}
|
|
2209
2524
|
function freezeState(state) {
|
|
@@ -2218,6 +2533,8 @@ function freezeState(state) {
|
|
|
2218
2533
|
standard: Object.freeze({ ...state.settings.budget.standard }),
|
|
2219
2534
|
heavy: Object.freeze({ ...state.settings.budget.heavy })
|
|
2220
2535
|
}),
|
|
2536
|
+
cacheWarming: Object.freeze({ ...state.settings.cacheWarming }),
|
|
2537
|
+
missionCountdown: Object.freeze({ ...state.settings.missionCountdown }),
|
|
2221
2538
|
...state.settings.allowedProfiles ? { allowedProfiles: Object.freeze([...state.settings.allowedProfiles]) } : {}
|
|
2222
2539
|
}),
|
|
2223
2540
|
sources: Object.freeze({ ...state.sources }),
|
|
@@ -2236,13 +2553,93 @@ function formatError(error) {
|
|
|
2236
2553
|
|
|
2237
2554
|
// src/swarm-controller.ts
|
|
2238
2555
|
import { randomBytes as randomBytes9 } from "node:crypto";
|
|
2239
|
-
import { readdir as readdir4, readFile as
|
|
2240
|
-
import { basename as basename7, dirname as dirname7, join as
|
|
2556
|
+
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";
|
|
2557
|
+
import { basename as basename7, dirname as dirname7, join as join16, resolve as resolve13, sep as sep3 } from "node:path";
|
|
2558
|
+
|
|
2559
|
+
// src/cache-warming.ts
|
|
2560
|
+
function classifyModelCacheTier(model) {
|
|
2561
|
+
if (!model) return "unknown";
|
|
2562
|
+
if (isLocalHostedModel(model)) return "local_infinite";
|
|
2563
|
+
if (isDeepSeekModel(model)) return "deepseek_long";
|
|
2564
|
+
const shortSec = model.promptCache?.short;
|
|
2565
|
+
if (typeof shortSec === "number" && shortSec > 0) {
|
|
2566
|
+
return shortSec <= 3600 ? "cloud_short" : "deepseek_long";
|
|
2567
|
+
}
|
|
2568
|
+
const provider = (model.provider ?? "").toLowerCase();
|
|
2569
|
+
const id = (model.id ?? "").toLowerCase();
|
|
2570
|
+
if (provider.includes("anthropic") || provider.includes("kimi") || provider.includes("moonshot") || id.includes("claude") || id.startsWith("k3") || id.includes("kimi")) {
|
|
2571
|
+
return "cloud_short";
|
|
2572
|
+
}
|
|
2573
|
+
return "unknown";
|
|
2574
|
+
}
|
|
2575
|
+
function isDeepSeekModel(model) {
|
|
2576
|
+
const provider = (model?.provider ?? "").toLowerCase();
|
|
2577
|
+
const id = (model?.id ?? "").toLowerCase();
|
|
2578
|
+
return provider === "deepseek" || provider.includes("deepseek") || id.startsWith("deepseek");
|
|
2579
|
+
}
|
|
2580
|
+
function isLocalHostedModel(model) {
|
|
2581
|
+
if (!model?.baseUrl) return false;
|
|
2582
|
+
let host;
|
|
2583
|
+
try {
|
|
2584
|
+
host = new URL(model.baseUrl).hostname.toLowerCase();
|
|
2585
|
+
} catch {
|
|
2586
|
+
return false;
|
|
2587
|
+
}
|
|
2588
|
+
if (host === "localhost" || host.endsWith(".localhost") || host === "::1" || host === "[::1]" || host === "0.0.0.0") {
|
|
2589
|
+
return true;
|
|
2590
|
+
}
|
|
2591
|
+
const ipv4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/u.exec(host);
|
|
2592
|
+
if (!ipv4) return false;
|
|
2593
|
+
const a = Number(ipv4[1]);
|
|
2594
|
+
const b = Number(ipv4[2]);
|
|
2595
|
+
return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
|
|
2596
|
+
}
|
|
2597
|
+
var SwarmCacheWarmingPolicy = class {
|
|
2598
|
+
waitStartedAt;
|
|
2599
|
+
refreshesInWait = 0;
|
|
2600
|
+
/** Reset wait window counters when a real native turn starts or session resets. */
|
|
2601
|
+
resetWaitWindow() {
|
|
2602
|
+
this.waitStartedAt = void 0;
|
|
2603
|
+
this.refreshesInWait = 0;
|
|
2604
|
+
}
|
|
2605
|
+
evaluate(input) {
|
|
2606
|
+
const tier = classifyModelCacheTier(input.model);
|
|
2607
|
+
if (input.externalDirectActive) {
|
|
2608
|
+
this.resetWaitWindow();
|
|
2609
|
+
return { action: "stop", tier, reason: "external_direct_runtime_active" };
|
|
2610
|
+
}
|
|
2611
|
+
if (tier === "local_infinite") {
|
|
2612
|
+
this.resetWaitWindow();
|
|
2613
|
+
return { action: "stop", tier, reason: "local_model_infinite_kv" };
|
|
2614
|
+
}
|
|
2615
|
+
if (tier === "deepseek_long") {
|
|
2616
|
+
this.resetWaitWindow();
|
|
2617
|
+
return { action: "stop", tier, reason: "deepseek_long_retention" };
|
|
2618
|
+
}
|
|
2619
|
+
if (!input.settings.enabled) {
|
|
2620
|
+
return { action: input.defaultAction, tier, reason: "swarm_cache_warming_disabled" };
|
|
2621
|
+
}
|
|
2622
|
+
if (!input.isLead || input.inFlightWorkerCount <= 0) {
|
|
2623
|
+
this.resetWaitWindow();
|
|
2624
|
+
return { action: input.defaultAction, tier, reason: "no_inflight_workers" };
|
|
2625
|
+
}
|
|
2626
|
+
this.waitStartedAt ??= input.now;
|
|
2627
|
+
const elapsedMs = Math.max(0, input.now - this.waitStartedAt);
|
|
2628
|
+
if (elapsedMs >= input.settings.maxWaitDurationMs) {
|
|
2629
|
+
return { action: "stop", tier, reason: "wait_duration_cap_reached" };
|
|
2630
|
+
}
|
|
2631
|
+
if (this.refreshesInWait >= input.settings.maxRefreshesPerWait) {
|
|
2632
|
+
return { action: "stop", tier, reason: "refresh_count_cap_reached" };
|
|
2633
|
+
}
|
|
2634
|
+
this.refreshesInWait += 1;
|
|
2635
|
+
return { action: "warm", tier, reason: "lead_waiting_for_active_workers" };
|
|
2636
|
+
}
|
|
2637
|
+
};
|
|
2241
2638
|
|
|
2242
2639
|
// src/external.ts
|
|
2243
2640
|
import { spawn } from "node:child_process";
|
|
2244
2641
|
import { existsSync } from "node:fs";
|
|
2245
|
-
import { join as
|
|
2642
|
+
import { join as join5 } from "node:path";
|
|
2246
2643
|
var ExternalLaunchError = class extends Error {
|
|
2247
2644
|
constructor(message, splitCreated = false, terminalId) {
|
|
2248
2645
|
super(message);
|
|
@@ -2345,7 +2742,7 @@ function isOnPath(binary) {
|
|
|
2345
2742
|
if (binary.includes("/")) return existsSync(binary);
|
|
2346
2743
|
const path2 = process.env.PATH ?? "";
|
|
2347
2744
|
for (const dir of path2.split(":")) {
|
|
2348
|
-
if (dir && existsSync(
|
|
2745
|
+
if (dir && existsSync(join5(dir, binary))) return true;
|
|
2349
2746
|
}
|
|
2350
2747
|
return false;
|
|
2351
2748
|
}
|
|
@@ -2498,6 +2895,56 @@ var ExternalRuntimeHost = class {
|
|
|
2498
2895
|
sessionId
|
|
2499
2896
|
});
|
|
2500
2897
|
}
|
|
2898
|
+
deliverToDirect(params) {
|
|
2899
|
+
this.emit({
|
|
2900
|
+
type: "direct_deliver",
|
|
2901
|
+
runtimeId: params.runtimeId,
|
|
2902
|
+
sessionId: params.sessionId,
|
|
2903
|
+
prompt: params.prompt,
|
|
2904
|
+
source: params.source,
|
|
2905
|
+
...params.messageId ? { messageId: params.messageId } : {},
|
|
2906
|
+
...params.fromSessionId ? { fromSessionId: params.fromSessionId } : {}
|
|
2907
|
+
});
|
|
2908
|
+
}
|
|
2909
|
+
restoreDirect(params, signal) {
|
|
2910
|
+
const requestId = this.handlers.randomId("extrestore");
|
|
2911
|
+
const timeoutMs = params.timeoutMs ?? 6e4;
|
|
2912
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
2913
|
+
if (signal?.aborted) {
|
|
2914
|
+
rejectPromise(new Error("External runtime direct restore aborted"));
|
|
2915
|
+
return;
|
|
2916
|
+
}
|
|
2917
|
+
const waiter = {
|
|
2918
|
+
resolve: resolvePromise,
|
|
2919
|
+
reject: rejectPromise
|
|
2920
|
+
};
|
|
2921
|
+
waiter.timer = setTimeout(() => {
|
|
2922
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
2923
|
+
this.clearWaiter(waiter);
|
|
2924
|
+
rejectPromise(new Error(`External runtime "${params.runtimeId}" did not restore within ${timeoutMs}ms`));
|
|
2925
|
+
}, timeoutMs);
|
|
2926
|
+
if (signal) {
|
|
2927
|
+
const onAbort = () => {
|
|
2928
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
2929
|
+
this.clearWaiter(waiter);
|
|
2930
|
+
rejectPromise(new Error("External runtime direct restore aborted"));
|
|
2931
|
+
};
|
|
2932
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2933
|
+
waiter.cleanupAbort = () => signal.removeEventListener("abort", onAbort);
|
|
2934
|
+
}
|
|
2935
|
+
this.readyWaiters.set(requestId, waiter);
|
|
2936
|
+
this.emit({
|
|
2937
|
+
type: "direct_restore",
|
|
2938
|
+
requestId,
|
|
2939
|
+
runtimeId: params.runtimeId,
|
|
2940
|
+
sessionId: params.sessionId,
|
|
2941
|
+
...params.model ? { model: params.model } : {},
|
|
2942
|
+
...params.thoughtLevel ? { thoughtLevel: params.thoughtLevel } : {},
|
|
2943
|
+
...params.mode ? { mode: params.mode } : {},
|
|
2944
|
+
handoffPrompt: params.handoffPrompt
|
|
2945
|
+
});
|
|
2946
|
+
});
|
|
2947
|
+
}
|
|
2501
2948
|
emit(payload) {
|
|
2502
2949
|
if (typeof this.pi.events?.emit === "function") {
|
|
2503
2950
|
this.pi.events.emit(EXTERNAL_RUNTIME_EVENT, payload);
|
|
@@ -2526,6 +2973,50 @@ var ExternalRuntimeHost = class {
|
|
|
2526
2973
|
});
|
|
2527
2974
|
return;
|
|
2528
2975
|
}
|
|
2976
|
+
if (type === "direct_state" && typeof msg.runtimeId === "string" && typeof msg.active === "boolean") {
|
|
2977
|
+
this.handlers.onDirectState?.({
|
|
2978
|
+
runtimeId: msg.runtimeId,
|
|
2979
|
+
...typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {},
|
|
2980
|
+
active: msg.active,
|
|
2981
|
+
...typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {},
|
|
2982
|
+
...typeof msg.thoughtLevel === "string" && msg.thoughtLevel.length > 0 ? { thoughtLevel: msg.thoughtLevel } : {},
|
|
2983
|
+
...typeof msg.mode === "string" && msg.mode.length > 0 ? { mode: msg.mode } : {},
|
|
2984
|
+
...typeof msg.busy === "boolean" ? { busy: msg.busy } : {},
|
|
2985
|
+
updatedAt: this.handlers.now()
|
|
2986
|
+
});
|
|
2987
|
+
return;
|
|
2988
|
+
}
|
|
2989
|
+
if (type === "context_usage" && typeof msg.runtimeId === "string") {
|
|
2990
|
+
const contextWindow = typeof msg.contextWindow === "number" && Number.isFinite(msg.contextWindow) && msg.contextWindow > 0 ? msg.contextWindow : 1048576;
|
|
2991
|
+
const tokens = typeof msg.tokens === "number" && Number.isFinite(msg.tokens) && msg.tokens >= 0 ? msg.tokens : null;
|
|
2992
|
+
const completedTurns = typeof msg.completedTurns === "number" && Number.isInteger(msg.completedTurns) && msg.completedTurns >= 0 ? msg.completedTurns : 0;
|
|
2993
|
+
const compactionCount = typeof msg.compactionCount === "number" && Number.isInteger(msg.compactionCount) && msg.compactionCount >= 0 ? msg.compactionCount : 0;
|
|
2994
|
+
const rawUsage = msg.usage && typeof msg.usage === "object" && !Array.isArray(msg.usage) ? msg.usage : void 0;
|
|
2995
|
+
const usage = rawUsage ? {
|
|
2996
|
+
...typeof rawUsage.inputTokens === "number" ? { inputTokens: rawUsage.inputTokens } : {},
|
|
2997
|
+
...typeof rawUsage.outputTokens === "number" ? { outputTokens: rawUsage.outputTokens } : {},
|
|
2998
|
+
...typeof rawUsage.totalTokens === "number" ? { totalTokens: rawUsage.totalTokens } : {},
|
|
2999
|
+
...typeof rawUsage.costUsd === "number" ? { costUsd: rawUsage.costUsd } : {},
|
|
3000
|
+
...typeof rawUsage.cachedReadTokens === "number" ? { cachedReadTokens: rawUsage.cachedReadTokens } : {},
|
|
3001
|
+
...typeof rawUsage.cachedWriteTokens === "number" ? { cachedWriteTokens: rawUsage.cachedWriteTokens } : {},
|
|
3002
|
+
...typeof rawUsage.thoughtTokens === "number" ? { thoughtTokens: rawUsage.thoughtTokens } : {}
|
|
3003
|
+
} : void 0;
|
|
3004
|
+
this.handlers.onContextUsage?.({
|
|
3005
|
+
runtimeId: msg.runtimeId,
|
|
3006
|
+
...typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {},
|
|
3007
|
+
tokens,
|
|
3008
|
+
contextWindow,
|
|
3009
|
+
completedTurns,
|
|
3010
|
+
compactionCount,
|
|
3011
|
+
...typeof msg.idleMs === "number" && Number.isFinite(msg.idleMs) && msg.idleMs >= 0 ? { idleMs: msg.idleMs } : {},
|
|
3012
|
+
...typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {},
|
|
3013
|
+
...usage ? { usage } : {},
|
|
3014
|
+
settled: msg.settled === true,
|
|
3015
|
+
aborted: msg.aborted === true,
|
|
3016
|
+
updatedAt: this.handlers.now()
|
|
3017
|
+
});
|
|
3018
|
+
return;
|
|
3019
|
+
}
|
|
2529
3020
|
if (type === "ready" && typeof msg.requestId === "string") {
|
|
2530
3021
|
const waiter = this.readyWaiters.get(msg.requestId);
|
|
2531
3022
|
if (!waiter) return;
|
|
@@ -2581,7 +3072,7 @@ var ExternalRuntimeHost = class {
|
|
|
2581
3072
|
};
|
|
2582
3073
|
|
|
2583
3074
|
// src/fanout.ts
|
|
2584
|
-
import { resolve as
|
|
3075
|
+
import { resolve as resolve4 } from "node:path";
|
|
2585
3076
|
var FanoutConcurrencyError = class extends Error {
|
|
2586
3077
|
constructor(code, message) {
|
|
2587
3078
|
super(message);
|
|
@@ -2619,7 +3110,7 @@ function precheckFanoutBatch(branches, options) {
|
|
|
2619
3110
|
}
|
|
2620
3111
|
}
|
|
2621
3112
|
if (branch.profile.writable) {
|
|
2622
|
-
const normalizedCwd =
|
|
3113
|
+
const normalizedCwd = resolve4(branch.cwd);
|
|
2623
3114
|
const list = writableByCwd.get(normalizedCwd) ?? [];
|
|
2624
3115
|
list.push(branch.id);
|
|
2625
3116
|
writableByCwd.set(normalizedCwd, list);
|
|
@@ -2947,11 +3438,11 @@ function optionalHexColor(value) {
|
|
|
2947
3438
|
|
|
2948
3439
|
// src/launcher.ts
|
|
2949
3440
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
2950
|
-
import { lstat as lstat3, open as open3, rm as
|
|
2951
|
-
import { join as
|
|
3441
|
+
import { lstat as lstat3, open as open3, rm as rm5 } from "node:fs/promises";
|
|
3442
|
+
import { join as join6, relative as relative2, resolve as resolve5 } from "node:path";
|
|
2952
3443
|
async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
2953
3444
|
await assertPrivateDirectory(directory);
|
|
2954
|
-
const launcherPath =
|
|
3445
|
+
const launcherPath = join6(directory, `launch-${randomBytes4(8).toString("hex")}.sh`);
|
|
2955
3446
|
assertInside(directory, launcherPath);
|
|
2956
3447
|
const command = [invocation.command, ...invocation.args];
|
|
2957
3448
|
for (const value of command) {
|
|
@@ -2971,7 +3462,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
|
2971
3462
|
await handle.close();
|
|
2972
3463
|
} catch (error) {
|
|
2973
3464
|
await handle.close().catch(() => void 0);
|
|
2974
|
-
await
|
|
3465
|
+
await rm5(launcherPath, { force: true }).catch(() => void 0);
|
|
2975
3466
|
throw error;
|
|
2976
3467
|
}
|
|
2977
3468
|
let cleaned = false;
|
|
@@ -2982,7 +3473,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
|
2982
3473
|
if (cleaned) return;
|
|
2983
3474
|
cleaned = true;
|
|
2984
3475
|
assertInside(directory, launcherPath);
|
|
2985
|
-
await
|
|
3476
|
+
await rm5(launcherPath, { force: true });
|
|
2986
3477
|
}
|
|
2987
3478
|
};
|
|
2988
3479
|
}
|
|
@@ -3014,7 +3505,7 @@ async function assertPrivateDirectory(path2) {
|
|
|
3014
3505
|
}
|
|
3015
3506
|
}
|
|
3016
3507
|
function assertInside(parent, candidate) {
|
|
3017
|
-
const rel = relative2(
|
|
3508
|
+
const rel = relative2(resolve5(parent), resolve5(candidate));
|
|
3018
3509
|
if (!rel || rel === ".." || rel.startsWith("../")) {
|
|
3019
3510
|
throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
|
|
3020
3511
|
}
|
|
@@ -3022,15 +3513,15 @@ function assertInside(parent, candidate) {
|
|
|
3022
3513
|
|
|
3023
3514
|
// src/lead-mcp-bridge.ts
|
|
3024
3515
|
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
|
|
3516
|
+
import { chmod as chmod3, lstat as lstat5, mkdir as mkdir5, readdir as readdir2, rm as rm7 } from "node:fs/promises";
|
|
3026
3517
|
import { createConnection, createServer } from "node:net";
|
|
3027
|
-
import { join as
|
|
3518
|
+
import { join as join8 } from "node:path";
|
|
3028
3519
|
|
|
3029
3520
|
// src/runtime-directory.ts
|
|
3030
3521
|
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
|
|
3522
|
+
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
3523
|
import { tmpdir } from "node:os";
|
|
3033
|
-
import { basename as basename3, dirname as dirname3, isAbsolute, join as
|
|
3524
|
+
import { basename as basename3, dirname as dirname3, isAbsolute, join as join7, relative as relative3, resolve as resolve6 } from "node:path";
|
|
3034
3525
|
var MAX_UNIX_SOCKET_PATH_BYTES = 103;
|
|
3035
3526
|
var MAX_MANIFEST_BYTES = 8 * 1024;
|
|
3036
3527
|
var ORPHAN_GRACE_MS = 6e4;
|
|
@@ -3046,21 +3537,21 @@ function defaultRuntimeBaseDirectory() {
|
|
|
3046
3537
|
throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
|
|
3047
3538
|
}
|
|
3048
3539
|
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
3049
|
-
if (process.platform === "darwin") return
|
|
3540
|
+
if (process.platform === "darwin") return join7("/tmp", `pi-swarm-${uid}`);
|
|
3050
3541
|
const runtime2 = process.env.XDG_RUNTIME_DIR;
|
|
3051
|
-
if (runtime2 && isAbsolute(runtime2) && Buffer.byteLength(
|
|
3052
|
-
return
|
|
3542
|
+
if (runtime2 && isAbsolute(runtime2) && Buffer.byteLength(join7(runtime2, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
3543
|
+
return join7(runtime2, "pi-swarm");
|
|
3053
3544
|
}
|
|
3054
|
-
const systemTmp =
|
|
3055
|
-
const candidate =
|
|
3056
|
-
const socketCandidate =
|
|
3057
|
-
return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate :
|
|
3545
|
+
const systemTmp = resolve6(tmpdir());
|
|
3546
|
+
const candidate = join7(systemTmp, `pi-swarm-${uid}`);
|
|
3547
|
+
const socketCandidate = join7(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
|
|
3548
|
+
return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join7("/tmp", `pi-swarm-${uid}`);
|
|
3058
3549
|
}
|
|
3059
3550
|
async function ensureGroupRuntimeDirectory(groupId, options = {}) {
|
|
3060
3551
|
if (!SAFE_GROUP_ID.test(groupId)) throw new Error("Pi Agent Swarm runtime group id is invalid");
|
|
3061
|
-
const baseDirectory =
|
|
3062
|
-
const directory =
|
|
3063
|
-
const longestSocket =
|
|
3552
|
+
const baseDirectory = resolve6(options.baseDirectory ?? defaultRuntimeBaseDirectory());
|
|
3553
|
+
const directory = join7(baseDirectory, groupId);
|
|
3554
|
+
const longestSocket = join7(directory, `${"x".repeat(24)}.sock`);
|
|
3064
3555
|
if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
3065
3556
|
throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
|
|
3066
3557
|
}
|
|
@@ -3070,7 +3561,7 @@ async function ensureGroupRuntimeDirectory(groupId, options = {}) {
|
|
|
3070
3561
|
}
|
|
3071
3562
|
function createEndpointPaths(directory, endpointId) {
|
|
3072
3563
|
if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
|
|
3073
|
-
const socketPath =
|
|
3564
|
+
const socketPath = join7(directory, `${endpointId}.sock`);
|
|
3074
3565
|
if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
3075
3566
|
throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
|
|
3076
3567
|
}
|
|
@@ -3078,7 +3569,7 @@ function createEndpointPaths(directory, endpointId) {
|
|
|
3078
3569
|
directory,
|
|
3079
3570
|
endpointId,
|
|
3080
3571
|
socketPath,
|
|
3081
|
-
manifestPath:
|
|
3572
|
+
manifestPath: join7(directory, `${endpointId}.json`)
|
|
3082
3573
|
};
|
|
3083
3574
|
}
|
|
3084
3575
|
function randomEndpointId() {
|
|
@@ -3093,7 +3584,7 @@ async function publishManifest(manifestPath, manifest) {
|
|
|
3093
3584
|
if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
|
|
3094
3585
|
throw new Error("Pi Agent Swarm endpoint manifest is too large");
|
|
3095
3586
|
}
|
|
3096
|
-
const temporaryPath =
|
|
3587
|
+
const temporaryPath = join7(parent, `.${basename3(manifestPath)}.${randomBytes5(8).toString("hex")}.tmp`);
|
|
3097
3588
|
let handle;
|
|
3098
3589
|
try {
|
|
3099
3590
|
handle = await open4(temporaryPath, "wx", 384);
|
|
@@ -3105,7 +3596,7 @@ async function publishManifest(manifestPath, manifest) {
|
|
|
3105
3596
|
await chmod2(manifestPath, 384);
|
|
3106
3597
|
} finally {
|
|
3107
3598
|
await handle?.close().catch(() => void 0);
|
|
3108
|
-
await
|
|
3599
|
+
await rm6(temporaryPath, { force: true }).catch(() => void 0);
|
|
3109
3600
|
}
|
|
3110
3601
|
}
|
|
3111
3602
|
async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
@@ -3131,7 +3622,7 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
|
3131
3622
|
for (const name of names) {
|
|
3132
3623
|
const socketMatch = SAFE_SOCKET_NAME.exec(name);
|
|
3133
3624
|
if (socketMatch) {
|
|
3134
|
-
const manifestPath =
|
|
3625
|
+
const manifestPath = join7(directory, `${socketMatch[1]}.json`);
|
|
3135
3626
|
if (!await pathExists(manifestPath)) {
|
|
3136
3627
|
if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
|
|
3137
3628
|
}
|
|
@@ -3148,15 +3639,15 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
|
3148
3639
|
async function removeOwnedEndpoint(paths) {
|
|
3149
3640
|
for (const path2 of [paths.manifestPath, paths.socketPath]) {
|
|
3150
3641
|
assertOwnedPath(paths.directory, path2);
|
|
3151
|
-
await
|
|
3642
|
+
await rm6(path2, { force: true }).catch(() => void 0);
|
|
3152
3643
|
}
|
|
3153
3644
|
}
|
|
3154
3645
|
function endpointIdFromManifestName(name) {
|
|
3155
3646
|
return SAFE_MANIFEST_NAME.exec(name)?.[1];
|
|
3156
3647
|
}
|
|
3157
3648
|
function assertOwnedPath(parent, candidate, suffix) {
|
|
3158
|
-
const resolvedParent =
|
|
3159
|
-
const resolvedCandidate =
|
|
3649
|
+
const resolvedParent = resolve6(parent);
|
|
3650
|
+
const resolvedCandidate = resolve6(candidate);
|
|
3160
3651
|
const rel = relative3(resolvedParent, resolvedCandidate);
|
|
3161
3652
|
if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
|
|
3162
3653
|
throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
|
|
@@ -3166,7 +3657,7 @@ function assertOwnedPath(parent, candidate, suffix) {
|
|
|
3166
3657
|
}
|
|
3167
3658
|
}
|
|
3168
3659
|
async function removeStaleOwnedEntry(directory, name, kind, now) {
|
|
3169
|
-
const path2 =
|
|
3660
|
+
const path2 = join7(directory, name);
|
|
3170
3661
|
assertOwnedPath(directory, path2);
|
|
3171
3662
|
try {
|
|
3172
3663
|
const first = await lstat4(path2, { bigint: true });
|
|
@@ -3177,7 +3668,7 @@ async function removeStaleOwnedEntry(directory, name, kind, now) {
|
|
|
3177
3668
|
if (current.dev !== first.dev || current.ino !== first.ino || current.mtimeMs !== first.mtimeMs || (kind === "file" ? !current.isFile() : !current.isSocket())) {
|
|
3178
3669
|
return false;
|
|
3179
3670
|
}
|
|
3180
|
-
await
|
|
3671
|
+
await rm6(path2);
|
|
3181
3672
|
return true;
|
|
3182
3673
|
} catch (error) {
|
|
3183
3674
|
if (isMissing2(error)) return false;
|
|
@@ -3236,12 +3727,12 @@ async function cleanupStaleLeadMcpSockets(baseDir) {
|
|
|
3236
3727
|
let removed = 0;
|
|
3237
3728
|
for (const name of entries) {
|
|
3238
3729
|
if (!LEAD_MCP_SOCKET_RE.test(name)) continue;
|
|
3239
|
-
const candidate =
|
|
3730
|
+
const candidate = join8(baseDir, name);
|
|
3240
3731
|
const info = await lstat5(candidate).catch(() => void 0);
|
|
3241
3732
|
if (!info?.isSocket()) continue;
|
|
3242
3733
|
const alive = await probeUnixSocketAlive(candidate);
|
|
3243
3734
|
if (!alive) {
|
|
3244
|
-
await
|
|
3735
|
+
await rm7(candidate, { force: true }).catch(() => void 0);
|
|
3245
3736
|
removed += 1;
|
|
3246
3737
|
}
|
|
3247
3738
|
}
|
|
@@ -3312,16 +3803,24 @@ var LEAD_MCP_TOOLS = [
|
|
|
3312
3803
|
},
|
|
3313
3804
|
{
|
|
3314
3805
|
name: "swarm_bus",
|
|
3315
|
-
description:
|
|
3806
|
+
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
3807
|
inputSchema: {
|
|
3317
3808
|
type: "object",
|
|
3318
3809
|
properties: {
|
|
3319
|
-
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog"] },
|
|
3810
|
+
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog", "mission"] },
|
|
3320
3811
|
targetSessionId: { type: "string" },
|
|
3321
3812
|
message: { type: "string" },
|
|
3322
3813
|
mode: { type: "string", enum: ["notify", "request"] },
|
|
3323
3814
|
replyTo: { type: "string" },
|
|
3324
|
-
taskStatus: { type: "string", enum: ["working", "completed"] }
|
|
3815
|
+
taskStatus: { type: "string", enum: ["working", "completed"] },
|
|
3816
|
+
missionAction: { type: "string", enum: ["start", "complete", "status"] },
|
|
3817
|
+
firstPrinciples: { type: "string" },
|
|
3818
|
+
acceptanceCriteria: { type: "string" },
|
|
3819
|
+
constraints: { type: "string" },
|
|
3820
|
+
estimatedMinutes: { type: "number" },
|
|
3821
|
+
summary: { type: "string" },
|
|
3822
|
+
outcome: { type: "string", enum: ["achieved", "with_residuals"] },
|
|
3823
|
+
residuals: { type: "array", items: { type: "string" } }
|
|
3325
3824
|
},
|
|
3326
3825
|
required: ["action"],
|
|
3327
3826
|
additionalProperties: false
|
|
@@ -3438,12 +3937,12 @@ var LeadMcpBridge = class {
|
|
|
3438
3937
|
throw new Error("Refusing to start swarm-lead MCP bridge in a non-lead worker session");
|
|
3439
3938
|
}
|
|
3440
3939
|
if (this.server) return;
|
|
3441
|
-
const baseDir =
|
|
3940
|
+
const baseDir = join8(this.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), "lead-mcp");
|
|
3442
3941
|
await mkdir5(baseDir, { recursive: true, mode: 448 });
|
|
3443
3942
|
await chmod3(baseDir, 448).catch(() => void 0);
|
|
3444
3943
|
await cleanupStaleLeadMcpSockets(baseDir).catch(() => void 0);
|
|
3445
3944
|
const token = randomBytes6(32).toString("hex");
|
|
3446
|
-
const socketPath =
|
|
3945
|
+
const socketPath = join8(baseDir, `lmcp-${randomBytes6(8).toString("hex")}.sock`);
|
|
3447
3946
|
const server = createServer((socket) => {
|
|
3448
3947
|
this.handleConnection(socket, token);
|
|
3449
3948
|
});
|
|
@@ -3486,7 +3985,7 @@ var LeadMcpBridge = class {
|
|
|
3486
3985
|
});
|
|
3487
3986
|
}
|
|
3488
3987
|
if (socketPath) {
|
|
3489
|
-
await
|
|
3988
|
+
await rm7(socketPath, { force: true }).catch(() => void 0);
|
|
3490
3989
|
}
|
|
3491
3990
|
if (this.registered) {
|
|
3492
3991
|
const unregisterMcp = this.pi.unregisterMcpServer;
|
|
@@ -3623,6 +4122,23 @@ var LeadMcpBridge = class {
|
|
|
3623
4122
|
const action = typeof args.action === "string" ? args.action : "";
|
|
3624
4123
|
if (action === "catalog") return this.actions.catalog(ctx);
|
|
3625
4124
|
if (action === "list") return this.actions.snapshot();
|
|
4125
|
+
if (action === "mission") {
|
|
4126
|
+
if (!this.actions.mission) throw new Error("swarm_bus mission is unavailable");
|
|
4127
|
+
const missionAction = args.missionAction;
|
|
4128
|
+
if (missionAction !== "start" && missionAction !== "complete" && missionAction !== "status") {
|
|
4129
|
+
throw new Error('swarm_bus mission requires missionAction ("start" | "complete" | "status")');
|
|
4130
|
+
}
|
|
4131
|
+
return this.actions.mission(ctx, {
|
|
4132
|
+
missionAction,
|
|
4133
|
+
...typeof args.firstPrinciples === "string" ? { firstPrinciples: args.firstPrinciples } : {},
|
|
4134
|
+
...typeof args.acceptanceCriteria === "string" ? { acceptanceCriteria: args.acceptanceCriteria } : {},
|
|
4135
|
+
...typeof args.constraints === "string" ? { constraints: args.constraints } : {},
|
|
4136
|
+
...typeof args.estimatedMinutes === "number" ? { estimatedMinutes: args.estimatedMinutes } : {},
|
|
4137
|
+
...typeof args.summary === "string" ? { summary: args.summary } : {},
|
|
4138
|
+
...args.outcome === "achieved" || args.outcome === "with_residuals" ? { outcome: args.outcome } : {},
|
|
4139
|
+
...Array.isArray(args.residuals) ? { residuals: args.residuals.filter((r) => typeof r === "string") } : {}
|
|
4140
|
+
});
|
|
4141
|
+
}
|
|
3626
4142
|
if (action === "shutdown") {
|
|
3627
4143
|
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
3628
4144
|
throw new Error("swarm_bus shutdown requires targetSessionId");
|
|
@@ -3656,9 +4172,9 @@ var LeadMcpBridge = class {
|
|
|
3656
4172
|
};
|
|
3657
4173
|
|
|
3658
4174
|
// src/leader-recycling.ts
|
|
3659
|
-
import { readdir as readdir3, readFile as
|
|
3660
|
-
import { join as
|
|
3661
|
-
var LEADER_LINEAGES_DIRECTORY =
|
|
4175
|
+
import { readdir as readdir3, readFile as readFile4 } from "node:fs/promises";
|
|
4176
|
+
import { join as join9, resolve as resolve7 } from "node:path";
|
|
4177
|
+
var LEADER_LINEAGES_DIRECTORY = join9(WORKER_RECYCLING_DIRECTORY, "leader-lineages");
|
|
3662
4178
|
var DEFAULT_LEADER_SOFT_CONTEXT_PERCENT = 50;
|
|
3663
4179
|
var DEFAULT_LEADER_SOFT_CONTEXT_TOKENS = 1e5;
|
|
3664
4180
|
var DEFAULT_LEADER_HIGH_WATER_PERCENT = 75;
|
|
@@ -3696,12 +4212,13 @@ var LEADER_LINEAGE_TRANSITIONS = {
|
|
|
3696
4212
|
};
|
|
3697
4213
|
function normalizeLeaderRecyclingPolicy(input = {}) {
|
|
3698
4214
|
const value = record2(input, "leader recycling policy");
|
|
3699
|
-
const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "maxReplacements"];
|
|
4215
|
+
const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "highWaterTokens", "maxReplacements"];
|
|
3700
4216
|
const unknown = Object.keys(value).find((key) => !allowed.includes(key));
|
|
3701
4217
|
if (unknown) throw new Error(`Pi Agent Swarm leader recycling policy has unknown field ${unknown}`);
|
|
3702
4218
|
const softContextPercent = value.softContextPercent ?? DEFAULT_LEADER_SOFT_CONTEXT_PERCENT;
|
|
3703
4219
|
const softContextTokens = value.softContextTokens ?? DEFAULT_LEADER_SOFT_CONTEXT_TOKENS;
|
|
3704
4220
|
const highWaterPercent = value.highWaterPercent ?? DEFAULT_LEADER_HIGH_WATER_PERCENT;
|
|
4221
|
+
const highWaterTokens = value.highWaterTokens;
|
|
3705
4222
|
const maxReplacements = value.maxReplacements ?? DEFAULT_LEADER_RECYCLING_POLICY.maxReplacements;
|
|
3706
4223
|
for (const [key, percentage] of [
|
|
3707
4224
|
["softContextPercent", softContextPercent],
|
|
@@ -3714,6 +4231,9 @@ function normalizeLeaderRecyclingPolicy(input = {}) {
|
|
|
3714
4231
|
if (typeof softContextTokens !== "number" || !Number.isFinite(softContextTokens) || softContextTokens <= 0) {
|
|
3715
4232
|
throw new Error("Pi Agent Swarm leader recycling softContextTokens must be greater than 0");
|
|
3716
4233
|
}
|
|
4234
|
+
if (highWaterTokens !== void 0 && (typeof highWaterTokens !== "number" || !Number.isFinite(highWaterTokens) || highWaterTokens <= 0)) {
|
|
4235
|
+
throw new Error("Pi Agent Swarm leader recycling highWaterTokens must be greater than 0");
|
|
4236
|
+
}
|
|
3717
4237
|
if (!Number.isInteger(maxReplacements) || maxReplacements < 0 || maxReplacements > MAX_REPLACEMENTS) {
|
|
3718
4238
|
throw new Error(`Pi Agent Swarm leader recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
|
|
3719
4239
|
}
|
|
@@ -3721,6 +4241,7 @@ function normalizeLeaderRecyclingPolicy(input = {}) {
|
|
|
3721
4241
|
softContextPercent,
|
|
3722
4242
|
softContextTokens,
|
|
3723
4243
|
highWaterPercent,
|
|
4244
|
+
...highWaterTokens !== void 0 ? { highWaterTokens } : {},
|
|
3724
4245
|
maxReplacements
|
|
3725
4246
|
};
|
|
3726
4247
|
}
|
|
@@ -3730,7 +4251,7 @@ function shouldAnalyzeLeaderBranch(branch, usage, policyInput = {}) {
|
|
|
3730
4251
|
const window = usage.contextWindow;
|
|
3731
4252
|
const policy = normalizeLeaderRecyclingPolicy(policyInput);
|
|
3732
4253
|
const percent = tokens / window * 100;
|
|
3733
|
-
if (percent >= policy.softContextPercent || percent >= policy.highWaterPercent || tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP)) {
|
|
4254
|
+
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
4255
|
return true;
|
|
3735
4256
|
}
|
|
3736
4257
|
let completedTurns = 0;
|
|
@@ -3830,7 +4351,7 @@ function evaluateLeaderRecyclingGate(snapshot, policyInput = {}, cooldown = {
|
|
|
3830
4351
|
}
|
|
3831
4352
|
}
|
|
3832
4353
|
if (snapshot.compactionCount >= 1) signals.push("compaction_detected");
|
|
3833
|
-
const highWater = known !== void 0 && known.percent >= policy.highWaterPercent;
|
|
4354
|
+
const highWater = known !== void 0 && (known.percent >= policy.highWaterPercent || policy.highWaterTokens !== void 0 && known.tokens >= Math.min(policy.highWaterTokens, known.window * 0.85));
|
|
3834
4355
|
const reason = [...signals];
|
|
3835
4356
|
if (highWater) reason.push("high_water_context");
|
|
3836
4357
|
if (known === void 0) reason.push("context_tokens_unknown");
|
|
@@ -3874,15 +4395,15 @@ function leaderLineagePaths(projectRoot, lineageId, generation) {
|
|
|
3874
4395
|
if (!Number.isInteger(generation) || generation < 1) {
|
|
3875
4396
|
throw new Error("Pi Agent Swarm leader lineage generation is invalid");
|
|
3876
4397
|
}
|
|
3877
|
-
const root =
|
|
3878
|
-
const storageRoot =
|
|
4398
|
+
const root = resolve7(projectRoot);
|
|
4399
|
+
const storageRoot = resolve7(root, WORKER_RECYCLING_DIRECTORY);
|
|
3879
4400
|
if (!isWithin(root, storageRoot)) throw new Error("Pi Agent Swarm leader lineage storage escapes the project root");
|
|
3880
|
-
const lineageDirectory =
|
|
4401
|
+
const lineageDirectory = join9(storageRoot, "leader-lineages", lineageId);
|
|
3881
4402
|
return {
|
|
3882
4403
|
root: storageRoot,
|
|
3883
4404
|
lineageDirectory,
|
|
3884
|
-
lineagePath:
|
|
3885
|
-
handoffPath:
|
|
4405
|
+
lineagePath: join9(lineageDirectory, "lineage.json"),
|
|
4406
|
+
handoffPath: join9(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`)
|
|
3886
4407
|
};
|
|
3887
4408
|
}
|
|
3888
4409
|
function canTransitionLeaderLineageState(from, to) {
|
|
@@ -3900,7 +4421,7 @@ async function initializeLeaderLineage(options) {
|
|
|
3900
4421
|
{
|
|
3901
4422
|
schemaVersion: 1,
|
|
3902
4423
|
lineageId: options.lineageId,
|
|
3903
|
-
projectRoot:
|
|
4424
|
+
projectRoot: resolve7(options.projectRoot),
|
|
3904
4425
|
leaderSessionId: options.leaderSessionId,
|
|
3905
4426
|
originalObjective: options.originalObjective,
|
|
3906
4427
|
policy: normalizeLeaderRecyclingPolicy(options.policy),
|
|
@@ -3922,7 +4443,7 @@ async function initializeLeaderLineage(options) {
|
|
|
3922
4443
|
);
|
|
3923
4444
|
}
|
|
3924
4445
|
async function findLeaderLineage(projectRoot, leaderSessionId, onWarning) {
|
|
3925
|
-
const directory =
|
|
4446
|
+
const directory = resolve7(projectRoot, LEADER_LINEAGES_DIRECTORY);
|
|
3926
4447
|
let entries;
|
|
3927
4448
|
try {
|
|
3928
4449
|
entries = await readdir3(directory, { withFileTypes: true });
|
|
@@ -3951,7 +4472,7 @@ async function findLeaderLineage(projectRoot, leaderSessionId, onWarning) {
|
|
|
3951
4472
|
}
|
|
3952
4473
|
async function readLeaderLineage(projectRoot, lineageId) {
|
|
3953
4474
|
const paths = leaderLineagePaths(projectRoot, lineageId, 1);
|
|
3954
|
-
const value = JSON.parse(await
|
|
4475
|
+
const value = JSON.parse(await readFile4(paths.lineagePath, "utf8"));
|
|
3955
4476
|
return validateLeaderLineage(value, projectRoot, lineageId);
|
|
3956
4477
|
}
|
|
3957
4478
|
async function updateLeaderLineage(projectRoot, lineageId, patch, expected = {}) {
|
|
@@ -3970,7 +4491,7 @@ async function updateLeaderLineage(projectRoot, lineageId, patch, expected = {})
|
|
|
3970
4491
|
...existing,
|
|
3971
4492
|
...patch,
|
|
3972
4493
|
lineageId,
|
|
3973
|
-
projectRoot:
|
|
4494
|
+
projectRoot: resolve7(projectRoot),
|
|
3974
4495
|
state: existing.state,
|
|
3975
4496
|
currentGeneration: existing.currentGeneration,
|
|
3976
4497
|
replacementCount: existing.replacementCount,
|
|
@@ -4010,7 +4531,7 @@ async function transitionLeaderLineage(projectRoot, lineageId, nextState, option
|
|
|
4010
4531
|
...existing,
|
|
4011
4532
|
...options.patch ?? {},
|
|
4012
4533
|
lineageId,
|
|
4013
|
-
projectRoot:
|
|
4534
|
+
projectRoot: resolve7(projectRoot),
|
|
4014
4535
|
currentGeneration,
|
|
4015
4536
|
replacementCount,
|
|
4016
4537
|
state: nextState,
|
|
@@ -4027,9 +4548,9 @@ async function transitionLeaderLineage(projectRoot, lineageId, nextState, option
|
|
|
4027
4548
|
}
|
|
4028
4549
|
function validateLeaderHandoffContent(content, projectRoot) {
|
|
4029
4550
|
validateHandoff(content, "leader");
|
|
4030
|
-
const root =
|
|
4551
|
+
const root = resolve7(projectRoot);
|
|
4031
4552
|
for (const artifact of content.artifacts) {
|
|
4032
|
-
if (!isWithin(root,
|
|
4553
|
+
if (!isWithin(root, resolve7(root, artifact))) {
|
|
4033
4554
|
throw new Error("Pi Agent Swarm leader handoff artifact is outside the project root");
|
|
4034
4555
|
}
|
|
4035
4556
|
}
|
|
@@ -4075,17 +4596,17 @@ function renderLeaderHandoff(content) {
|
|
|
4075
4596
|
async function verifyLeaderHandoffReadable(projectRoot, lineageId, generation, handoffPath) {
|
|
4076
4597
|
if (generation === 1) return;
|
|
4077
4598
|
const expected = leaderLineagePaths(projectRoot, lineageId, generation - 1).handoffPath;
|
|
4078
|
-
if (
|
|
4599
|
+
if (resolve7(handoffPath) !== expected) {
|
|
4079
4600
|
throw new Error("Pi Agent Swarm leader successor handoff path does not match its predecessor generation");
|
|
4080
4601
|
}
|
|
4081
|
-
const markdown = await
|
|
4602
|
+
const markdown = await readFile4(expected, "utf8");
|
|
4082
4603
|
if (!hasRequiredHandoffSections(markdown)) {
|
|
4083
4604
|
throw new Error("Pi Agent Swarm leader successor handoff is incomplete");
|
|
4084
4605
|
}
|
|
4085
4606
|
}
|
|
4086
4607
|
function validateLeaderLineage(value, projectRoot, lineageId) {
|
|
4087
4608
|
const lineage = record2(value, "leader lineage");
|
|
4088
|
-
if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !==
|
|
4609
|
+
if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve7(projectRoot)) {
|
|
4089
4610
|
throw new Error("Pi Agent Swarm leader lineage identity is invalid");
|
|
4090
4611
|
}
|
|
4091
4612
|
if (typeof lineage.leaderSessionId !== "string" || Buffer.byteLength(lineage.leaderSessionId, "utf8") > 256) {
|
|
@@ -4117,8 +4638,8 @@ function validateLeaderLineage(value, projectRoot, lineageId) {
|
|
|
4117
4638
|
if (typeof lineage.currentHandoffPath !== "string") {
|
|
4118
4639
|
throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
|
|
4119
4640
|
}
|
|
4120
|
-
const handoffPath =
|
|
4121
|
-
const generations =
|
|
4641
|
+
const handoffPath = resolve7(lineage.currentHandoffPath);
|
|
4642
|
+
const generations = join9(leaderLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
|
|
4122
4643
|
if (!isWithin(generations, handoffPath) || !/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))) {
|
|
4123
4644
|
throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
|
|
4124
4645
|
}
|
|
@@ -4170,7 +4691,7 @@ function record2(value, label) {
|
|
|
4170
4691
|
}
|
|
4171
4692
|
|
|
4172
4693
|
// src/leader-runtime.ts
|
|
4173
|
-
import { readFile as
|
|
4694
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
4174
4695
|
|
|
4175
4696
|
// src/leader-handoff-bridge.ts
|
|
4176
4697
|
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
@@ -4255,10 +4776,12 @@ var runtimeGlobal = globalThis;
|
|
|
4255
4776
|
runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL] ??= {
|
|
4256
4777
|
actions: /* @__PURE__ */ new WeakMap(),
|
|
4257
4778
|
restoreGates: /* @__PURE__ */ new WeakMap(),
|
|
4779
|
+
externalRestorers: /* @__PURE__ */ new WeakMap(),
|
|
4258
4780
|
restoreStates: /* @__PURE__ */ new WeakMap(),
|
|
4259
4781
|
restoreErrors: /* @__PURE__ */ new WeakMap()
|
|
4260
4782
|
};
|
|
4261
4783
|
var runtime = runtimeGlobal[LEADER_SESSION_RUNTIME_SYMBOL];
|
|
4784
|
+
runtime.externalRestorers ??= /* @__PURE__ */ new WeakMap();
|
|
4262
4785
|
function registerLeaderSessionActions(sessionManager, actions) {
|
|
4263
4786
|
runtime.actions.set(sessionManager, actions);
|
|
4264
4787
|
runtime.restoreStates.set(sessionManager, false);
|
|
@@ -4274,6 +4797,12 @@ function registerLeaderRestoreGate(sessionManager, release) {
|
|
|
4274
4797
|
function getLeaderRestoreGate(sessionManager) {
|
|
4275
4798
|
return runtime.restoreGates.get(sessionManager);
|
|
4276
4799
|
}
|
|
4800
|
+
function registerLeaderExternalRestorer(sessionManager, restorer) {
|
|
4801
|
+
runtime.externalRestorers.set(sessionManager, restorer);
|
|
4802
|
+
}
|
|
4803
|
+
function getLeaderExternalRestorer(sessionManager) {
|
|
4804
|
+
return runtime.externalRestorers.get(sessionManager);
|
|
4805
|
+
}
|
|
4277
4806
|
function markLeaderSessionRestore(sessionManager, restored, error) {
|
|
4278
4807
|
runtime.restoreStates.set(sessionManager, restored);
|
|
4279
4808
|
if (error) runtime.restoreErrors.set(sessionManager, error);
|
|
@@ -4288,6 +4817,7 @@ function unregisterLeaderSessionActions(sessionManager, actions) {
|
|
|
4288
4817
|
if (runtime.actions.get(sessionManager) !== actions) return;
|
|
4289
4818
|
runtime.actions.delete(sessionManager);
|
|
4290
4819
|
runtime.restoreGates.delete(sessionManager);
|
|
4820
|
+
runtime.externalRestorers.delete(sessionManager);
|
|
4291
4821
|
runtime.restoreStates.delete(sessionManager);
|
|
4292
4822
|
runtime.restoreErrors.delete(sessionManager);
|
|
4293
4823
|
}
|
|
@@ -4475,14 +5005,19 @@ var LeaderRuntime = class {
|
|
|
4475
5005
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
4476
5006
|
const advisory = await this.createAdvisory(ctx);
|
|
4477
5007
|
if (!advisory || !this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
|
|
5008
|
+
const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
|
|
5009
|
+
const handoffToolName = activeExternal ? "swarm_leader_handoff" : "leader_handoff";
|
|
4478
5010
|
const automatic = `${advisory.content}
|
|
4479
5011
|
|
|
4480
|
-
Automatic leader recycling is enabled. Call
|
|
5012
|
+
Automatic leader recycling is enabled. Call ${handoffToolName} now with all ten sections; do not answer the user first.`;
|
|
4481
5013
|
const dispatch = setTimeout(() => {
|
|
4482
5014
|
if (this.autoDispatch === dispatch) this.autoDispatch = void 0;
|
|
4483
5015
|
if (!this.isCurrent(ctx, sessionId) || this.staged || this.applying) return;
|
|
4484
5016
|
try {
|
|
4485
5017
|
this.autoResponsePending = true;
|
|
5018
|
+
if (this.host.deliverExternalLeaderPrompt?.(ctx, automatic, "leader_advisory")) {
|
|
5019
|
+
return;
|
|
5020
|
+
}
|
|
4486
5021
|
this.pi.sendMessage(
|
|
4487
5022
|
{ customType: LEADER_ADVISORY_CUSTOM_TYPE, content: automatic, display: false },
|
|
4488
5023
|
{ deliverAs: "followUp", triggerTurn: true }
|
|
@@ -4596,8 +5131,20 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4596
5131
|
}).catch(() => void 0);
|
|
4597
5132
|
throw error;
|
|
4598
5133
|
}
|
|
4599
|
-
const
|
|
4600
|
-
const analysis =
|
|
5134
|
+
const externalCtx = this.host.externalLeaderContext?.(ctx);
|
|
5135
|
+
const analysis = externalCtx ? {
|
|
5136
|
+
status: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? "known" : "unknown",
|
|
5137
|
+
completedTurns: externalCtx.completedTurns,
|
|
5138
|
+
contextTokens: externalCtx.tokens,
|
|
5139
|
+
contextWindow: externalCtx.contextWindow,
|
|
5140
|
+
percent: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? externalCtx.tokens / externalCtx.contextWindow * 100 : null,
|
|
5141
|
+
oldToolOutputTokens: 0,
|
|
5142
|
+
toolResultCountOver2KB: 0,
|
|
5143
|
+
compactionCount: externalCtx.compactionCount
|
|
5144
|
+
} : (() => {
|
|
5145
|
+
const usage = ctx.getContextUsage();
|
|
5146
|
+
return usage ? analyzeSessionBranch(ctx.sessionManager.getBranch(), usage) : void 0;
|
|
5147
|
+
})();
|
|
4601
5148
|
await transitionLeaderLineage(ctx.cwd, lineage.lineageId, "replacing", {
|
|
4602
5149
|
expectedGeneration: lineage.currentGeneration,
|
|
4603
5150
|
patch: {
|
|
@@ -4619,6 +5166,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4619
5166
|
color: control.color,
|
|
4620
5167
|
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : void 0,
|
|
4621
5168
|
thinkingLevel: this.pi.getThinkingLevel(),
|
|
5169
|
+
...control.externalRuntime ? { externalRuntime: control.externalRuntime } : {},
|
|
4622
5170
|
invite: control.invite,
|
|
4623
5171
|
groupDirectory: control.groupDirectory,
|
|
4624
5172
|
acceptsRequests: control.acceptsRequests,
|
|
@@ -4652,10 +5200,15 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4652
5200
|
if (trimmed.length > 0) throw new Error("Usage: /swarm handoff [--apply <token>]");
|
|
4653
5201
|
if (!this.settings.get().settings.leaderRecycling.enabled) throw new Error("Leader recycling is disabled.");
|
|
4654
5202
|
if (!this.host.leaderSnapshot(ctx).isLead) throw new Error("Only the lead session can hand off.");
|
|
5203
|
+
const activeExternal = this.host.leaderSnapshot(ctx).externalRuntime;
|
|
5204
|
+
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.";
|
|
5205
|
+
if (this.host.deliverExternalLeaderPrompt?.(ctx, handoffPrompt, "leader_advisory")) {
|
|
5206
|
+
return;
|
|
5207
|
+
}
|
|
4655
5208
|
await this.pi.sendMessage(
|
|
4656
5209
|
{
|
|
4657
5210
|
customType: LEADER_ADVISORY_CUSTOM_TYPE,
|
|
4658
|
-
content:
|
|
5211
|
+
content: handoffPrompt,
|
|
4659
5212
|
display: false
|
|
4660
5213
|
},
|
|
4661
5214
|
// Streaming uses AgentSession.followUp; false only appends a dormant custom message.
|
|
@@ -4766,7 +5319,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4766
5319
|
leaderHandoffBridge.arm(token, previousSessionFile, Date.now(), LEADER_HANDOFF_BRIDGE_APPLY_TTL_MS);
|
|
4767
5320
|
let handoff;
|
|
4768
5321
|
try {
|
|
4769
|
-
handoff = await
|
|
5322
|
+
handoff = await readFile5(entry.handoffPath, "utf8");
|
|
4770
5323
|
if (!hasRequiredHandoffSections(handoff)) throw new Error("required sections are missing");
|
|
4771
5324
|
} catch (error) {
|
|
4772
5325
|
throw new Error(`Cannot apply leader handoff: ${errorMessage(error)}`);
|
|
@@ -4782,6 +5335,7 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4782
5335
|
generation,
|
|
4783
5336
|
model,
|
|
4784
5337
|
thinkingLevel,
|
|
5338
|
+
externalRuntime,
|
|
4785
5339
|
editorDraft,
|
|
4786
5340
|
nextAction,
|
|
4787
5341
|
previousSessionId: previousLeaderSessionId,
|
|
@@ -4844,8 +5398,8 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4844
5398
|
() => ({ status: "restored" }),
|
|
4845
5399
|
(error) => ({ status: "failed", error })
|
|
4846
5400
|
),
|
|
4847
|
-
new Promise((
|
|
4848
|
-
modelTimer = setTimeout(() =>
|
|
5401
|
+
new Promise((resolve14) => {
|
|
5402
|
+
modelTimer = setTimeout(() => resolve14({ status: "timeout" }), LEADER_MODEL_RESTORE_TIMEOUT_MS);
|
|
4849
5403
|
})
|
|
4850
5404
|
]);
|
|
4851
5405
|
if (modelTimer) clearTimeout(modelTimer);
|
|
@@ -4876,6 +5430,33 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4876
5430
|
await this.openSuccessorGate(replacedCtx);
|
|
4877
5431
|
return;
|
|
4878
5432
|
}
|
|
5433
|
+
if (externalRuntime) {
|
|
5434
|
+
const successorRestorer = getLeaderExternalRestorer(replacedCtx.sessionManager);
|
|
5435
|
+
const hostRestorer = this.host.restoreExternalLeader;
|
|
5436
|
+
const restoreFn = successorRestorer ? (ext, prompt) => successorRestorer(ext, prompt) : hostRestorer ? (ext, prompt) => hostRestorer(replacedCtx, ext, prompt) : void 0;
|
|
5437
|
+
if (restoreFn) {
|
|
5438
|
+
try {
|
|
5439
|
+
const externalKickoff = [
|
|
5440
|
+
"You are the successor leader in a fresh session. Read the leader handoff below and continue immediately.",
|
|
5441
|
+
"",
|
|
5442
|
+
handoff,
|
|
5443
|
+
"",
|
|
5444
|
+
`Continue with this exact next action: ${nextAction}`
|
|
5445
|
+
].join("\n");
|
|
5446
|
+
kickoffQueued = true;
|
|
5447
|
+
await restoreFn(externalRuntime, externalKickoff);
|
|
5448
|
+
await this.openSuccessorGate(replacedCtx);
|
|
5449
|
+
} catch (error) {
|
|
5450
|
+
this.notify(
|
|
5451
|
+
replacedCtx,
|
|
5452
|
+
`Could not restore external leader runtime (${externalRuntime.runtimeId}): ${errorMessage(error)}`,
|
|
5453
|
+
"error"
|
|
5454
|
+
);
|
|
5455
|
+
await this.openSuccessorGate(replacedCtx);
|
|
5456
|
+
}
|
|
5457
|
+
return;
|
|
5458
|
+
}
|
|
5459
|
+
}
|
|
4879
5460
|
try {
|
|
4880
5461
|
const kickoff = replacedCtx.sendUserMessage(
|
|
4881
5462
|
`You are the successor leader. Read the injected leader handoff. Continue with this exact next action: ${nextAction}`,
|
|
@@ -4954,12 +5535,34 @@ In-flight worker replies at replacement: ${control.pendingKickoffIds.join(", ")}
|
|
|
4954
5535
|
if (!config.enabled || !this.host.leaderSnapshot(ctx).isLead || this.staged || this.applying) return void 0;
|
|
4955
5536
|
if (!ctx.sessionManager.getSessionFile()) return void 0;
|
|
4956
5537
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
4957
|
-
const usage = ctx.getContextUsage();
|
|
4958
|
-
if (!usage) return void 0;
|
|
4959
|
-
const branch = ctx.sessionManager.getBranch();
|
|
4960
5538
|
const policy = leaderPolicy(config);
|
|
4961
|
-
|
|
4962
|
-
|
|
5539
|
+
const externalCtx = this.host.externalLeaderContext?.(ctx);
|
|
5540
|
+
let analysis;
|
|
5541
|
+
if (externalCtx) {
|
|
5542
|
+
const extUsage = {
|
|
5543
|
+
tokens: externalCtx.tokens,
|
|
5544
|
+
contextWindow: externalCtx.contextWindow,
|
|
5545
|
+
percent: externalCtx.tokens !== null && externalCtx.contextWindow > 0 ? externalCtx.tokens / externalCtx.contextWindow * 100 : null
|
|
5546
|
+
};
|
|
5547
|
+
const hasPressure = shouldAnalyzeLeaderBranch([], extUsage, policy) || externalCtx.compactionCount >= 1 || externalCtx.tokens !== null && externalCtx.completedTurns >= 25 && externalCtx.tokens >= 35e3;
|
|
5548
|
+
if (!hasPressure) return void 0;
|
|
5549
|
+
analysis = {
|
|
5550
|
+
status: extUsage.tokens !== null && extUsage.contextWindow > 0 ? "known" : "unknown",
|
|
5551
|
+
completedTurns: externalCtx.completedTurns,
|
|
5552
|
+
contextTokens: extUsage.tokens,
|
|
5553
|
+
contextWindow: extUsage.contextWindow,
|
|
5554
|
+
percent: extUsage.percent,
|
|
5555
|
+
oldToolOutputTokens: 0,
|
|
5556
|
+
toolResultCountOver2KB: 0,
|
|
5557
|
+
compactionCount: externalCtx.compactionCount
|
|
5558
|
+
};
|
|
5559
|
+
} else {
|
|
5560
|
+
const usage = ctx.getContextUsage();
|
|
5561
|
+
if (!usage) return void 0;
|
|
5562
|
+
const branch = ctx.sessionManager.getBranch();
|
|
5563
|
+
if (!shouldAnalyzeLeaderBranch(branch, usage, policy)) return void 0;
|
|
5564
|
+
analysis = analyzeSessionBranch(branch, usage);
|
|
5565
|
+
}
|
|
4963
5566
|
const lineage = await findLeaderLineage(ctx.cwd, sessionId, (message) => this.notify(ctx, message, "warning"));
|
|
4964
5567
|
if (!this.isCurrent(ctx, sessionId)) return void 0;
|
|
4965
5568
|
if (config.mode === "auto" && (lineage?.autoCircuitOpen || (lineage?.autoFailures ?? 0) >= 3)) {
|
|
@@ -5160,6 +5763,7 @@ function leaderPolicy(config) {
|
|
|
5160
5763
|
softContextPercent: config.softContextPercent,
|
|
5161
5764
|
softContextTokens: config.softContextTokens,
|
|
5162
5765
|
highWaterPercent: config.highWaterPercent,
|
|
5766
|
+
...config.highWaterTokens !== void 0 ? { highWaterTokens: config.highWaterTokens } : {},
|
|
5163
5767
|
maxReplacements: config.maxReplacements
|
|
5164
5768
|
};
|
|
5165
5769
|
}
|
|
@@ -5309,7 +5913,7 @@ function isLikelyLocalProvider(provider) {
|
|
|
5309
5913
|
|
|
5310
5914
|
// src/org.ts
|
|
5311
5915
|
import { existsSync as existsSync2, readFileSync } from "node:fs";
|
|
5312
|
-
import { join as
|
|
5916
|
+
import { join as join10, resolve as resolve8 } from "node:path";
|
|
5313
5917
|
var VALID_ROLES2 = /* @__PURE__ */ new Set(["lead", "implementer", "researcher", "reviewer"]);
|
|
5314
5918
|
var VALID_INTENTS = /* @__PURE__ */ new Set(["assign", "evidence", "verdict", "handoff", "escalate"]);
|
|
5315
5919
|
var FORBIDDEN_ROLE_KEYS = /* @__PURE__ */ new Set(["cwd", "defaultCwd", "workingDirectory", "workdir"]);
|
|
@@ -5328,7 +5932,7 @@ var DEFAULT_STAR_ORG = Object.freeze({
|
|
|
5328
5932
|
edges: []
|
|
5329
5933
|
});
|
|
5330
5934
|
function orgConfigPathForProject(projectRoot) {
|
|
5331
|
-
return
|
|
5935
|
+
return join10(resolve8(projectRoot), WORKER_RECYCLING_DIRECTORY, "org.json");
|
|
5332
5936
|
}
|
|
5333
5937
|
function validateOrgDocument(raw) {
|
|
5334
5938
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
@@ -5340,6 +5944,13 @@ function validateOrgDocument(raw) {
|
|
|
5340
5944
|
}
|
|
5341
5945
|
const version = typeof obj.version === "string" && obj.version.trim().length > 0 ? obj.version.trim() : "v1-custom";
|
|
5342
5946
|
const strictTaskId = obj.strictTaskId === true;
|
|
5947
|
+
let reviewPolicy;
|
|
5948
|
+
if (obj.reviewPolicy !== void 0) {
|
|
5949
|
+
if (obj.reviewPolicy !== "off" && obj.reviewPolicy !== "suggest" && obj.reviewPolicy !== "required") {
|
|
5950
|
+
throw new Error(`org.json has invalid reviewPolicy "${String(obj.reviewPolicy)}"`);
|
|
5951
|
+
}
|
|
5952
|
+
reviewPolicy = obj.reviewPolicy;
|
|
5953
|
+
}
|
|
5343
5954
|
if (!obj.roles || typeof obj.roles !== "object" || Array.isArray(obj.roles)) {
|
|
5344
5955
|
throw new Error("org.json requires a roles object");
|
|
5345
5956
|
}
|
|
@@ -5423,6 +6034,7 @@ function validateOrgDocument(raw) {
|
|
|
5423
6034
|
schemaVersion: 1,
|
|
5424
6035
|
version,
|
|
5425
6036
|
strictTaskId,
|
|
6037
|
+
...reviewPolicy ? { reviewPolicy } : {},
|
|
5426
6038
|
roles,
|
|
5427
6039
|
edges
|
|
5428
6040
|
};
|
|
@@ -5672,7 +6284,7 @@ function probeCommand(resourceId, argv, timeoutMs, startedAt, signal) {
|
|
|
5672
6284
|
// src/profiles.ts
|
|
5673
6285
|
import { existsSync as existsSync3, lstatSync, readdirSync, readFileSync as readFileSync3, realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
|
|
5674
6286
|
import { homedir } from "node:os";
|
|
5675
|
-
import { basename as basename5, dirname as dirname5, join as
|
|
6287
|
+
import { basename as basename5, dirname as dirname5, join as join12, relative as relative5, resolve as resolve10 } from "node:path";
|
|
5676
6288
|
import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
|
|
5677
6289
|
var READONLY_EXCLUDED_TOOLS = ["edit", "write", "bash"];
|
|
5678
6290
|
var ALLOWED_TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
|
|
@@ -5718,15 +6330,15 @@ var BUILTIN_DEFAULT_PROFILE = Object.freeze({
|
|
|
5718
6330
|
});
|
|
5719
6331
|
function defaultProfilesDirectory(configuredDir) {
|
|
5720
6332
|
if (configuredDir?.trim()) {
|
|
5721
|
-
return
|
|
6333
|
+
return resolve10(expandHome(configuredDir.trim()));
|
|
5722
6334
|
}
|
|
5723
|
-
return
|
|
6335
|
+
return join12(getAgentDir2(), "profiles");
|
|
5724
6336
|
}
|
|
5725
6337
|
function defaultMcpProfilesDirectory(env = process.env) {
|
|
5726
6338
|
if (env.PI_MCP_PROFILES_DIR?.trim()) {
|
|
5727
|
-
return
|
|
6339
|
+
return resolve10(expandHome(env.PI_MCP_PROFILES_DIR.trim()));
|
|
5728
6340
|
}
|
|
5729
|
-
return
|
|
6341
|
+
return join12(dirname5(getAgentDir2()), "mcp-profiles");
|
|
5730
6342
|
}
|
|
5731
6343
|
function isReadOnlyRole(role) {
|
|
5732
6344
|
return role === "reviewer" || role === "researcher";
|
|
@@ -5840,7 +6452,7 @@ function loadProfileCatalog(options = {}) {
|
|
|
5840
6452
|
continue;
|
|
5841
6453
|
}
|
|
5842
6454
|
if (allowedSet && !allowedSet.has(expectedId)) continue;
|
|
5843
|
-
const candidatePath =
|
|
6455
|
+
const candidatePath = join12(realProfilesDir, filename);
|
|
5844
6456
|
try {
|
|
5845
6457
|
const realFile = realpathSync2(candidatePath);
|
|
5846
6458
|
const rel = relative5(realProfilesDir, realFile);
|
|
@@ -5886,7 +6498,7 @@ function resolveWorkerProfile(profileIdInput, role, options = {}) {
|
|
|
5886
6498
|
const resources = readOnly ? [] : doc.resources.map((r) => ({ ...r }));
|
|
5887
6499
|
const mcpExtensionPaths = [];
|
|
5888
6500
|
for (const mcpName of mcpProfiles) {
|
|
5889
|
-
const candidate =
|
|
6501
|
+
const candidate = join12(mcpProfilesDir, `${mcpName}.ts`);
|
|
5890
6502
|
if (existsSync3(candidate)) {
|
|
5891
6503
|
mcpExtensionPaths.push(candidate);
|
|
5892
6504
|
}
|
|
@@ -5992,7 +6604,7 @@ function detectProjectProfileHints(cwd, catalog) {
|
|
|
5992
6604
|
}
|
|
5993
6605
|
function expandHome(rawPath, home = homedir()) {
|
|
5994
6606
|
if (rawPath === "~") return home;
|
|
5995
|
-
if (rawPath.startsWith("~/")) return
|
|
6607
|
+
if (rawPath.startsWith("~/")) return join12(home, rawPath.slice(2));
|
|
5996
6608
|
return rawPath;
|
|
5997
6609
|
}
|
|
5998
6610
|
function expandSkillEntry(entry, home) {
|
|
@@ -6008,7 +6620,7 @@ function expandSkillEntry(entry, home) {
|
|
|
6008
6620
|
}
|
|
6009
6621
|
const dirs = [];
|
|
6010
6622
|
for (const entryItem of entries) {
|
|
6011
|
-
const candidate =
|
|
6623
|
+
const candidate = join12(parent, entryItem.name);
|
|
6012
6624
|
let isDir = entryItem.isDirectory();
|
|
6013
6625
|
if (!isDir && entryItem.isSymbolicLink()) {
|
|
6014
6626
|
try {
|
|
@@ -6017,14 +6629,14 @@ function expandSkillEntry(entry, home) {
|
|
|
6017
6629
|
isDir = false;
|
|
6018
6630
|
}
|
|
6019
6631
|
}
|
|
6020
|
-
if (isDir && existsSync3(
|
|
6632
|
+
if (isDir && existsSync3(join12(candidate, "SKILL.md"))) {
|
|
6021
6633
|
dirs.push(candidate);
|
|
6022
6634
|
}
|
|
6023
6635
|
}
|
|
6024
6636
|
dirs.sort((a, b) => basename5(a).localeCompare(basename5(b)));
|
|
6025
6637
|
return dirs;
|
|
6026
6638
|
}
|
|
6027
|
-
if (existsSync3(
|
|
6639
|
+
if (existsSync3(join12(expanded, "SKILL.md"))) {
|
|
6028
6640
|
return [expanded];
|
|
6029
6641
|
}
|
|
6030
6642
|
return [];
|
|
@@ -6160,8 +6772,8 @@ function reloadHandoffs() {
|
|
|
6160
6772
|
|
|
6161
6773
|
// src/resource-lease.ts
|
|
6162
6774
|
import { createHash as createHash3 } from "node:crypto";
|
|
6163
|
-
import { chmod as chmod4, mkdir as mkdir6, open as open5, readFile as
|
|
6164
|
-
import { join as
|
|
6775
|
+
import { chmod as chmod4, mkdir as mkdir6, open as open5, readFile as readFile6, rm as rm8, writeFile as writeFile4 } from "node:fs/promises";
|
|
6776
|
+
import { join as join13 } from "node:path";
|
|
6165
6777
|
function defaultIsProcessAlive(pid) {
|
|
6166
6778
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
6167
6779
|
try {
|
|
@@ -6187,7 +6799,7 @@ var ResourceLeaseManager = class {
|
|
|
6187
6799
|
now;
|
|
6188
6800
|
heldByLeaseId = /* @__PURE__ */ new Map();
|
|
6189
6801
|
constructor(options = {}) {
|
|
6190
|
-
this.baseDirectory =
|
|
6802
|
+
this.baseDirectory = join13(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "resource-leases");
|
|
6191
6803
|
this.isProcessAlive = options.isProcessAlive ?? defaultIsProcessAlive;
|
|
6192
6804
|
this.pid = options.pid ?? process.pid;
|
|
6193
6805
|
this.now = options.now ?? Date.now;
|
|
@@ -6226,7 +6838,7 @@ var ResourceLeaseManager = class {
|
|
|
6226
6838
|
const keyHash = createHash3("sha256").update(spec.id).digest("hex").slice(0, 24);
|
|
6227
6839
|
let lastHolderDesc = "another active worker";
|
|
6228
6840
|
for (let slot = 0; slot < spec.concurrency; slot += 1) {
|
|
6229
|
-
const lockPath =
|
|
6841
|
+
const lockPath = join13(this.baseDirectory, `res-${keyHash}-s${slot}.lock`);
|
|
6230
6842
|
const record3 = {
|
|
6231
6843
|
resourceId: spec.id,
|
|
6232
6844
|
slot,
|
|
@@ -6250,7 +6862,7 @@ var ResourceLeaseManager = class {
|
|
|
6250
6862
|
}
|
|
6251
6863
|
const existing = await this.readLock(lockPath);
|
|
6252
6864
|
if (!existing) {
|
|
6253
|
-
await
|
|
6865
|
+
await rm8(lockPath, { force: true }).catch(() => void 0);
|
|
6254
6866
|
if (await this.tryCreateExclusive(lockPath, record3)) {
|
|
6255
6867
|
const lease = {
|
|
6256
6868
|
resourceId: spec.id,
|
|
@@ -6279,7 +6891,7 @@ var ResourceLeaseManager = class {
|
|
|
6279
6891
|
return lease;
|
|
6280
6892
|
}
|
|
6281
6893
|
if (!this.isProcessAlive(existing.ownerPid)) {
|
|
6282
|
-
await
|
|
6894
|
+
await rm8(lockPath, { force: true }).catch(() => void 0);
|
|
6283
6895
|
if (await this.tryCreateExclusive(lockPath, record3)) {
|
|
6284
6896
|
const lease = {
|
|
6285
6897
|
resourceId: spec.id,
|
|
@@ -6305,7 +6917,7 @@ var ResourceLeaseManager = class {
|
|
|
6305
6917
|
if (existing && existing.leaseId !== lease.leaseId) {
|
|
6306
6918
|
return;
|
|
6307
6919
|
}
|
|
6308
|
-
await
|
|
6920
|
+
await rm8(lease.lockPath, { force: true }).catch(() => void 0);
|
|
6309
6921
|
}
|
|
6310
6922
|
async tryCreateExclusive(lockPath, record3) {
|
|
6311
6923
|
let handle;
|
|
@@ -6326,7 +6938,7 @@ var ResourceLeaseManager = class {
|
|
|
6326
6938
|
}
|
|
6327
6939
|
async readLock(lockPath) {
|
|
6328
6940
|
try {
|
|
6329
|
-
const parsed = JSON.parse(await
|
|
6941
|
+
const parsed = JSON.parse(await readFile6(lockPath, "utf8"));
|
|
6330
6942
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
|
|
6331
6943
|
const rec = parsed;
|
|
6332
6944
|
if (typeof rec.resourceId !== "string" || typeof rec.slot !== "number" || typeof rec.ownerPid !== "number" || typeof rec.leaseId !== "string") {
|
|
@@ -6477,11 +7089,72 @@ var ReviewerVerdictStore = class {
|
|
|
6477
7089
|
}
|
|
6478
7090
|
return void 0;
|
|
6479
7091
|
}
|
|
7092
|
+
hasPassingVerdict(taskId) {
|
|
7093
|
+
return this.records.some((rec) => rec.taskId === taskId && rec.verdict.verdict === "pass");
|
|
7094
|
+
}
|
|
7095
|
+
consecutiveFailsForTask(taskId) {
|
|
7096
|
+
let count = 0;
|
|
7097
|
+
for (let i = this.records.length - 1; i >= 0; i -= 1) {
|
|
7098
|
+
const rec = this.records[i];
|
|
7099
|
+
if (rec?.taskId !== taskId) continue;
|
|
7100
|
+
if (rec.verdict.verdict === "fail") {
|
|
7101
|
+
count += 1;
|
|
7102
|
+
} else {
|
|
7103
|
+
break;
|
|
7104
|
+
}
|
|
7105
|
+
}
|
|
7106
|
+
return count;
|
|
7107
|
+
}
|
|
6480
7108
|
clear() {
|
|
6481
7109
|
this.records.length = 0;
|
|
6482
7110
|
this.byMessageId.clear();
|
|
6483
7111
|
}
|
|
6484
7112
|
};
|
|
7113
|
+
var MAX_CONSECUTIVE_REVIEWER_FAILS = 2;
|
|
7114
|
+
function inferModelFamily(modelRef) {
|
|
7115
|
+
const lower = modelRef.toLowerCase();
|
|
7116
|
+
if (lower.includes("claude")) return "claude";
|
|
7117
|
+
if (lower.includes("gemini")) return "gemini";
|
|
7118
|
+
if (lower.includes("deepseek")) return "deepseek";
|
|
7119
|
+
if (lower.includes("kimi") || lower.includes("moonshot") || /\/k3(\b|[-_.])/u.test(lower)) return "kimi";
|
|
7120
|
+
if (lower.includes("qwen")) return "qwen";
|
|
7121
|
+
if (lower.includes("glm")) return "glm";
|
|
7122
|
+
if (lower.includes("gpt") || lower.includes("o1") || lower.includes("o3") || lower.includes("o4")) return "openai";
|
|
7123
|
+
const stripped = lower.replace(/^(?:pi|agy):/u, "");
|
|
7124
|
+
return stripped.split(/[/:]/u)[0] || "unknown";
|
|
7125
|
+
}
|
|
7126
|
+
function suggestCrossFamilyReviewerModels(implementerModelRef, candidates) {
|
|
7127
|
+
const implFamily = implementerModelRef ? inferModelFamily(implementerModelRef) : "";
|
|
7128
|
+
const seenFamilies = /* @__PURE__ */ new Set();
|
|
7129
|
+
const picked = [];
|
|
7130
|
+
for (const candidate of candidates) {
|
|
7131
|
+
if (candidate.sawQuota) continue;
|
|
7132
|
+
const family = inferModelFamily(candidate.ref);
|
|
7133
|
+
if (implFamily && family === implFamily) continue;
|
|
7134
|
+
if (seenFamilies.has(family)) continue;
|
|
7135
|
+
seenFamilies.add(family);
|
|
7136
|
+
picked.push(candidate.ref);
|
|
7137
|
+
if (picked.length >= 2) break;
|
|
7138
|
+
}
|
|
7139
|
+
return picked;
|
|
7140
|
+
}
|
|
7141
|
+
function formatReviewGovernanceReminder(params) {
|
|
7142
|
+
const modelHint = params.suggestedReviewerModels.length > 0 ? ` Recommended cross-family reviewer model(s): ${params.suggestedReviewerModels.join(" or ")}.` : "";
|
|
7143
|
+
if (params.policy === "required") {
|
|
7144
|
+
return `
|
|
7145
|
+
|
|
7146
|
+
[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}`;
|
|
7147
|
+
}
|
|
7148
|
+
return `
|
|
7149
|
+
|
|
7150
|
+
[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}`;
|
|
7151
|
+
}
|
|
7152
|
+
function formatReviewerEscalationNotice(params) {
|
|
7153
|
+
const issueText = params.blockingIssues.length > 0 ? ` Blocking issues: ${params.blockingIssues.slice(0, 5).join("; ")}.` : "";
|
|
7154
|
+
return `
|
|
7155
|
+
|
|
7156
|
+
[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.`;
|
|
7157
|
+
}
|
|
6485
7158
|
function stringList(value, field) {
|
|
6486
7159
|
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
|
|
6487
7160
|
throw new Error(`Reviewer verdict ${field} must be an array of strings`);
|
|
@@ -6672,12 +7345,12 @@ function quoteI3Value(value) {
|
|
|
6672
7345
|
}
|
|
6673
7346
|
async function abortableSleep(milliseconds, signal) {
|
|
6674
7347
|
throwIfAborted3(signal, "Pi Agent Swarm i3 workspace wait was aborted");
|
|
6675
|
-
await new Promise((
|
|
7348
|
+
await new Promise((resolve14, reject) => {
|
|
6676
7349
|
const finish = (error) => {
|
|
6677
7350
|
clearTimeout(timer);
|
|
6678
7351
|
signal?.removeEventListener("abort", abort);
|
|
6679
7352
|
if (error) reject(error);
|
|
6680
|
-
else
|
|
7353
|
+
else resolve14();
|
|
6681
7354
|
};
|
|
6682
7355
|
const timer = setTimeout(() => finish(), milliseconds);
|
|
6683
7356
|
const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
|
|
@@ -6717,9 +7390,9 @@ function createTerminalLaunchError(message, splitCreated, terminalId) {
|
|
|
6717
7390
|
// src/transport.ts
|
|
6718
7391
|
import { randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
|
|
6719
7392
|
import { constants as constants3 } from "node:fs";
|
|
6720
|
-
import { chmod as chmod5, lstat as lstat6, open as open7, opendir as opendir2, rm as
|
|
7393
|
+
import { chmod as chmod5, lstat as lstat6, open as open7, opendir as opendir2, rm as rm9 } from "node:fs/promises";
|
|
6721
7394
|
import { createServer as createServer2 } from "node:net";
|
|
6722
|
-
import { basename as basename6, dirname as dirname6, join as
|
|
7395
|
+
import { basename as basename6, dirname as dirname6, join as join14, resolve as resolve11 } from "node:path";
|
|
6723
7396
|
|
|
6724
7397
|
// src/transport-io.ts
|
|
6725
7398
|
import { constants as constants2 } from "node:fs";
|
|
@@ -7363,7 +8036,7 @@ var SwarmTransport = class {
|
|
|
7363
8036
|
}
|
|
7364
8037
|
try {
|
|
7365
8038
|
records.push(
|
|
7366
|
-
await readManifest2(paths.directory,
|
|
8039
|
+
await readManifest2(paths.directory, resolve11(paths.directory, entry.name), endpointId, this.options.group)
|
|
7367
8040
|
);
|
|
7368
8041
|
} catch {
|
|
7369
8042
|
addIssue(issues, { code: "invalid_manifest", endpointId });
|
|
@@ -7436,11 +8109,11 @@ var SwarmTransport = class {
|
|
|
7436
8109
|
try {
|
|
7437
8110
|
const current = await readBoundedUtf8(record3.manifestPath, MAX_MANIFEST_BYTES);
|
|
7438
8111
|
if (current !== record3.raw) return;
|
|
7439
|
-
await
|
|
8112
|
+
await rm9(record3.manifestPath, { force: true });
|
|
7440
8113
|
if (record3.socketIdentity) {
|
|
7441
8114
|
const info = await lstat6(record3.socketPath, { bigint: true }).catch(() => void 0);
|
|
7442
8115
|
if (info?.isSocket() && info.dev === record3.socketIdentity.dev && info.ino === record3.socketIdentity.ino) {
|
|
7443
|
-
await
|
|
8116
|
+
await rm9(record3.socketPath, { force: true });
|
|
7444
8117
|
}
|
|
7445
8118
|
}
|
|
7446
8119
|
} catch {
|
|
@@ -7500,8 +8173,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
|
|
|
7500
8173
|
expectedGroupId: group.id,
|
|
7501
8174
|
expectedEndpointId: endpointId
|
|
7502
8175
|
});
|
|
7503
|
-
const socketPath =
|
|
7504
|
-
if (dirname6(
|
|
8176
|
+
const socketPath = join14(directory, manifest.socketName);
|
|
8177
|
+
if (dirname6(resolve11(socketPath)) !== resolve11(directory)) {
|
|
7505
8178
|
throw new Error("Pi Agent Swarm endpoint socket path is invalid");
|
|
7506
8179
|
}
|
|
7507
8180
|
const socketInfo = await lstat6(socketPath, { bigint: true }).catch(() => void 0);
|
|
@@ -7603,8 +8276,8 @@ function assertPositiveDuration2(value, label) {
|
|
|
7603
8276
|
// src/worktree.ts
|
|
7604
8277
|
import { execFile as execFile2 } from "node:child_process";
|
|
7605
8278
|
import { createHash as createHash4 } from "node:crypto";
|
|
7606
|
-
import { chmod as chmod6, mkdir as mkdir7, rm as
|
|
7607
|
-
import { join as
|
|
8279
|
+
import { chmod as chmod6, mkdir as mkdir7, rm as rm10 } from "node:fs/promises";
|
|
8280
|
+
import { join as join15, resolve as resolve12 } from "node:path";
|
|
7608
8281
|
import { promisify as promisify2 } from "node:util";
|
|
7609
8282
|
var execFileAsync = promisify2(execFile2);
|
|
7610
8283
|
var SAFE_TASK_ID_RE = /^[A-Za-z0-9._-]{1,128}$/u;
|
|
@@ -7614,7 +8287,7 @@ async function resolveGitTopLevel(cwd) {
|
|
|
7614
8287
|
timeout: 5e3
|
|
7615
8288
|
});
|
|
7616
8289
|
const root = stdout.trim();
|
|
7617
|
-
return root ?
|
|
8290
|
+
return root ? resolve12(root) : void 0;
|
|
7618
8291
|
} catch {
|
|
7619
8292
|
return void 0;
|
|
7620
8293
|
}
|
|
@@ -7627,11 +8300,11 @@ async function provisionTaskWorktree(options) {
|
|
|
7627
8300
|
if (!repoRoot) {
|
|
7628
8301
|
throw new Error(`Worktree isolation requires "${options.cwd}" to be inside a git repository`);
|
|
7629
8302
|
}
|
|
7630
|
-
const worktreesBase =
|
|
8303
|
+
const worktreesBase = join15(options.baseDirectory ?? defaultRuntimeBaseDirectory(), "worktrees");
|
|
7631
8304
|
await mkdir7(worktreesBase, { recursive: true, mode: 448 });
|
|
7632
8305
|
await chmod6(worktreesBase, 448).catch(() => void 0);
|
|
7633
8306
|
const repoHash = createHash4("sha256").update(repoRoot).digest("hex").slice(0, 12);
|
|
7634
|
-
const worktreePath =
|
|
8307
|
+
const worktreePath = join15(worktreesBase, `${repoHash}-${options.taskId}`);
|
|
7635
8308
|
await execFileAsync("git", ["-C", repoRoot, "worktree", "add", "--detach", worktreePath, "HEAD"], {
|
|
7636
8309
|
timeout: 15e3
|
|
7637
8310
|
});
|
|
@@ -7654,7 +8327,7 @@ async function cleanupTaskWorktree(repoRoot, worktreePath) {
|
|
|
7654
8327
|
timeout: 1e4
|
|
7655
8328
|
});
|
|
7656
8329
|
} catch {
|
|
7657
|
-
await
|
|
8330
|
+
await rm10(worktreePath, { recursive: true, force: true }).catch(() => void 0);
|
|
7658
8331
|
await execFileAsync("git", ["-C", repoRoot, "worktree", "prune"], { timeout: 1e4 }).catch(() => void 0);
|
|
7659
8332
|
}
|
|
7660
8333
|
}
|
|
@@ -7662,6 +8335,8 @@ async function cleanupTaskWorktree(repoRoot, worktreePath) {
|
|
|
7662
8335
|
// src/swarm-controller.ts
|
|
7663
8336
|
var STATUS_KEY = "swarm";
|
|
7664
8337
|
var ROSTER_STATUS_KEY = "swarm-roster";
|
|
8338
|
+
var MISSION_STATUS_KEY = "swarm-mission";
|
|
8339
|
+
var MISSION_CUSTOM_TYPE = "pi-agent-swarm:mission-timeout";
|
|
7665
8340
|
var DEFAULT_LAUNCH_TIMEOUT_MS = 15e3;
|
|
7666
8341
|
var DEFAULT_POLL_INTERVAL_MS2 = 100;
|
|
7667
8342
|
var RELOAD_HANDOFF_TTL_MS = 3e4;
|
|
@@ -7702,6 +8377,44 @@ var SwarmController = class {
|
|
|
7702
8377
|
}
|
|
7703
8378
|
}
|
|
7704
8379
|
},
|
|
8380
|
+
onDirectState: (state) => {
|
|
8381
|
+
const activeSid = this.activeContext?.sessionManager.getSessionId();
|
|
8382
|
+
if (state.sessionId && activeSid && state.sessionId !== activeSid) return;
|
|
8383
|
+
if (state.active) {
|
|
8384
|
+
this.activeDirectRuntime = state;
|
|
8385
|
+
this.cacheWarmingPolicy.resetWaitWindow();
|
|
8386
|
+
} else if (!this.activeDirectRuntime || this.activeDirectRuntime.runtimeId === state.runtimeId) {
|
|
8387
|
+
this.activeDirectRuntime = void 0;
|
|
8388
|
+
this.externalLeaderUsage = void 0;
|
|
8389
|
+
}
|
|
8390
|
+
},
|
|
8391
|
+
onContextUsage: (report) => {
|
|
8392
|
+
const ctx = this.activeContext;
|
|
8393
|
+
if (!ctx) return;
|
|
8394
|
+
const activeSid = ctx.sessionManager.getSessionId();
|
|
8395
|
+
if (report.sessionId && report.sessionId !== activeSid) return;
|
|
8396
|
+
this.externalLeaderUsage = report;
|
|
8397
|
+
if (report.settled) {
|
|
8398
|
+
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);
|
|
8399
|
+
this.recordLedger(ctx.cwd, {
|
|
8400
|
+
event: "run_completed",
|
|
8401
|
+
task_id: `lead:${activeSid}`,
|
|
8402
|
+
role: "lead",
|
|
8403
|
+
profile: this.sessionProfile,
|
|
8404
|
+
engine: report.runtimeId === "agy" ? "agy" : "pi",
|
|
8405
|
+
model: report.model ? `${report.runtimeId}:${report.model}` : this.currentModelRef(ctx),
|
|
8406
|
+
tokens: totalTokens ?? null,
|
|
8407
|
+
wallclock_ms: 0,
|
|
8408
|
+
cost_usd: report.usage?.costUsd ?? null,
|
|
8409
|
+
stop_reason: report.aborted ? "aborted" : "end_turn",
|
|
8410
|
+
...report.idleMs !== void 0 ? { idle_ms: report.idleMs } : {},
|
|
8411
|
+
...report.usage ? { usage: report.usage } : {}
|
|
8412
|
+
});
|
|
8413
|
+
if (this.isCurrent(ctx)) {
|
|
8414
|
+
void this.track(this.leaderRuntime.agentSettled(ctx, report.aborted));
|
|
8415
|
+
}
|
|
8416
|
+
}
|
|
8417
|
+
},
|
|
7705
8418
|
now: () => this.deps.now(),
|
|
7706
8419
|
randomId: (prefix) => this.deps.randomId(prefix)
|
|
7707
8420
|
});
|
|
@@ -7715,6 +8428,7 @@ var SwarmController = class {
|
|
|
7715
8428
|
snapshot: () => this.snapshot(),
|
|
7716
8429
|
send: (ctx, options) => this.send(ctx, options),
|
|
7717
8430
|
shutdownPeer: (ctx, targetSessionId) => this.shutdownPeer(ctx, targetSessionId),
|
|
8431
|
+
mission: (ctx, input) => this.manageMission(ctx, input),
|
|
7718
8432
|
publishLeaderHandoff: (ctx, handoff) => this.publishLeaderHandoff(ctx, handoff)
|
|
7719
8433
|
},
|
|
7720
8434
|
deps.runtimeBaseDirectory
|
|
@@ -7722,6 +8436,45 @@ var SwarmController = class {
|
|
|
7722
8436
|
this.leaderRuntime = new LeaderRuntime(pi, settings, {
|
|
7723
8437
|
isCurrent: (ctx) => this.isCurrent(ctx),
|
|
7724
8438
|
leaderSnapshot: (ctx) => this.leaderSnapshot(ctx),
|
|
8439
|
+
externalLeaderContext: (ctx) => {
|
|
8440
|
+
if (!this.isExternalDirectLeadActive(ctx)) return void 0;
|
|
8441
|
+
const direct = this.activeDirectRuntime;
|
|
8442
|
+
if (!direct) return void 0;
|
|
8443
|
+
const usage = this.externalLeaderUsage;
|
|
8444
|
+
return {
|
|
8445
|
+
runtimeId: direct.runtimeId,
|
|
8446
|
+
tokens: usage?.tokens ?? null,
|
|
8447
|
+
contextWindow: usage?.contextWindow ?? 1048576,
|
|
8448
|
+
completedTurns: usage?.completedTurns ?? 0,
|
|
8449
|
+
compactionCount: usage?.compactionCount ?? 0,
|
|
8450
|
+
...direct.model ? { model: direct.model } : {},
|
|
8451
|
+
...direct.thoughtLevel ? { thoughtLevel: direct.thoughtLevel } : {},
|
|
8452
|
+
...direct.mode ? { mode: direct.mode } : {}
|
|
8453
|
+
};
|
|
8454
|
+
},
|
|
8455
|
+
deliverExternalLeaderPrompt: (ctx, prompt, source) => {
|
|
8456
|
+
if (!this.isExternalDirectLeadActive(ctx) || !this.activeDirectRuntime) return false;
|
|
8457
|
+
this.externalRuntime.deliverToDirect({
|
|
8458
|
+
runtimeId: this.activeDirectRuntime.runtimeId,
|
|
8459
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
8460
|
+
prompt,
|
|
8461
|
+
source
|
|
8462
|
+
});
|
|
8463
|
+
return true;
|
|
8464
|
+
},
|
|
8465
|
+
restoreExternalLeader: async (ctx, ext, handoffPrompt) => {
|
|
8466
|
+
await this.externalRuntime.restoreDirect(
|
|
8467
|
+
{
|
|
8468
|
+
runtimeId: ext.runtimeId,
|
|
8469
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
8470
|
+
...ext.model ? { model: ext.model } : {},
|
|
8471
|
+
...ext.thoughtLevel ? { thoughtLevel: ext.thoughtLevel } : {},
|
|
8472
|
+
...ext.mode ? { mode: ext.mode } : {},
|
|
8473
|
+
handoffPrompt
|
|
8474
|
+
},
|
|
8475
|
+
this.controller.signal
|
|
8476
|
+
);
|
|
8477
|
+
},
|
|
7725
8478
|
restoreLeaderControl: (ctx, entry) => this.restoreLeaderControl(ctx, entry),
|
|
7726
8479
|
commitLeaderControl: (ctx, entry) => this.commitLeaderControl(ctx, entry),
|
|
7727
8480
|
completeLeaderRestore: (ctx) => this.completeLeaderRestore(ctx),
|
|
@@ -7787,12 +8540,19 @@ var SwarmController = class {
|
|
|
7787
8540
|
pendingKickoffIds = /* @__PURE__ */ new Set();
|
|
7788
8541
|
ledger;
|
|
7789
8542
|
budgetTracker;
|
|
8543
|
+
cacheWarmingPolicy = new SwarmCacheWarmingPolicy();
|
|
7790
8544
|
resourceLeases;
|
|
7791
8545
|
externalRuntime;
|
|
7792
8546
|
leadMcpBridge;
|
|
7793
8547
|
verdictStore = new ReviewerVerdictStore();
|
|
7794
8548
|
externalRuntimes = /* @__PURE__ */ new Map();
|
|
7795
8549
|
quotaSeenByModel = /* @__PURE__ */ new Map();
|
|
8550
|
+
activeDirectRuntime;
|
|
8551
|
+
externalLeaderUsage;
|
|
8552
|
+
pendingReviewTasks = /* @__PURE__ */ new Map();
|
|
8553
|
+
activeMission;
|
|
8554
|
+
missionTimer;
|
|
8555
|
+
missionTicker;
|
|
7796
8556
|
sessionRole = "lead";
|
|
7797
8557
|
sessionProfile = "default";
|
|
7798
8558
|
sessionRuntime = "pi";
|
|
@@ -7816,6 +8576,19 @@ var SwarmController = class {
|
|
|
7816
8576
|
this.activeContext = ctx;
|
|
7817
8577
|
registerLeaderSessionActions(ctx.sessionManager, this.pi);
|
|
7818
8578
|
registerLeaderRestoreGate(ctx.sessionManager, () => this.leaderRuntime.completeRestoreGate(ctx));
|
|
8579
|
+
registerLeaderExternalRestorer(ctx.sessionManager, async (ext, handoffPrompt) => {
|
|
8580
|
+
await this.externalRuntime.restoreDirect(
|
|
8581
|
+
{
|
|
8582
|
+
runtimeId: ext.runtimeId,
|
|
8583
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
8584
|
+
...ext.model ? { model: ext.model } : {},
|
|
8585
|
+
...ext.thoughtLevel ? { thoughtLevel: ext.thoughtLevel } : {},
|
|
8586
|
+
...ext.mode ? { mode: ext.mode } : {},
|
|
8587
|
+
handoffPrompt
|
|
8588
|
+
},
|
|
8589
|
+
this.controller.signal
|
|
8590
|
+
);
|
|
8591
|
+
});
|
|
7819
8592
|
this.color = void 0;
|
|
7820
8593
|
this.parentSessionId = void 0;
|
|
7821
8594
|
this.leadSessionId = void 0;
|
|
@@ -7833,6 +8606,12 @@ var SwarmController = class {
|
|
|
7833
8606
|
this.pendingKickoffIds.clear();
|
|
7834
8607
|
this.verdictStore.clear();
|
|
7835
8608
|
this.budgetTracker.clear();
|
|
8609
|
+
this.cacheWarmingPolicy.resetWaitWindow();
|
|
8610
|
+
this.activeDirectRuntime = void 0;
|
|
8611
|
+
this.externalLeaderUsage = void 0;
|
|
8612
|
+
this.pendingReviewTasks.clear();
|
|
8613
|
+
this.stopMissionTimers();
|
|
8614
|
+
this.activeMission = void 0;
|
|
7836
8615
|
this.sessionRole = "lead";
|
|
7837
8616
|
this.sessionProfile = "default";
|
|
7838
8617
|
this.sessionRuntime = "pi";
|
|
@@ -7869,8 +8648,11 @@ var SwarmController = class {
|
|
|
7869
8648
|
try {
|
|
7870
8649
|
const restore = await this.leaderRuntime.restore(ctx, event.previousSessionFile);
|
|
7871
8650
|
if (restore === "restored") {
|
|
8651
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
8652
|
+
await this.closePreviousGenerationMissionOnHandoff(ctx);
|
|
7872
8653
|
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
7873
8654
|
this.activateLeaderToolIfLead(ctx);
|
|
8655
|
+
await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
|
|
7874
8656
|
await this.renderFooterStatus(ctx);
|
|
7875
8657
|
return;
|
|
7876
8658
|
}
|
|
@@ -7894,6 +8676,9 @@ var SwarmController = class {
|
|
|
7894
8676
|
this.autoNameEligible = true;
|
|
7895
8677
|
this.activateLeaderToolIfLead(ctx);
|
|
7896
8678
|
await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
|
|
8679
|
+
if (event.reason === "reload") {
|
|
8680
|
+
await this.restoreMissionOnReload(ctx, owner, ownerGeneration);
|
|
8681
|
+
}
|
|
7897
8682
|
await this.renderFooterStatus(ctx);
|
|
7898
8683
|
return;
|
|
7899
8684
|
}
|
|
@@ -7951,6 +8736,9 @@ var SwarmController = class {
|
|
|
7951
8736
|
);
|
|
7952
8737
|
this.activateLeaderToolIfLead(ctx);
|
|
7953
8738
|
await this.syncLeadMcpBridge(ctx, owner, ownerGeneration);
|
|
8739
|
+
if (event.reason === "reload" && this.leaderSnapshot(ctx).isLead) {
|
|
8740
|
+
await this.restoreMissionOnReload(ctx, owner, ownerGeneration);
|
|
8741
|
+
}
|
|
7954
8742
|
const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
|
|
7955
8743
|
const recyclingLeaderSessionId = this.leadSessionId ?? this.parentSessionId;
|
|
7956
8744
|
if (recyclingLaunch && recyclingLeaderSessionId) {
|
|
@@ -7975,6 +8763,7 @@ var SwarmController = class {
|
|
|
7975
8763
|
if (ctx.sessionManager !== this.activeSessionManager) return;
|
|
7976
8764
|
this.stopLeadWatcher();
|
|
7977
8765
|
this.stopResizeWatcher();
|
|
8766
|
+
this.stopMissionTimers();
|
|
7978
8767
|
const pendingTurnMessages = this.leaderRuntime.takeTurnDeferredMessages();
|
|
7979
8768
|
if (pendingTurnMessages.length > 0) {
|
|
7980
8769
|
this.preserveDeferredFollowUps(ctx, {
|
|
@@ -8039,6 +8828,15 @@ var SwarmController = class {
|
|
|
8039
8828
|
this.assertCurrentContext(ctx);
|
|
8040
8829
|
await this.settings.flush();
|
|
8041
8830
|
const launchSettings = this.settings.get().settings;
|
|
8831
|
+
const missionGate = checkMissionSpawnGate({
|
|
8832
|
+
mission: this.activeMission,
|
|
8833
|
+
role: "fanout",
|
|
8834
|
+
settings: launchSettings.missionCountdown,
|
|
8835
|
+
busToolName: this.isExternalDirectLeadActive(ctx) ? "swarm_bus" : "session_bus"
|
|
8836
|
+
});
|
|
8837
|
+
if (!missionGate.allowed) {
|
|
8838
|
+
throw new Error(missionGate.reason ?? "Mission countdown gate rejected fanout");
|
|
8839
|
+
}
|
|
8042
8840
|
const resolvedBranches = [];
|
|
8043
8841
|
for (const branch of input.branches) {
|
|
8044
8842
|
const role = branch.role ?? "implementer";
|
|
@@ -8166,8 +8964,9 @@ var SwarmController = class {
|
|
|
8166
8964
|
denyAsReviewer: doc.readonlyOverlay?.denyAsReviewer === true,
|
|
8167
8965
|
resources: doc.resources.map((r) => r.id)
|
|
8168
8966
|
}));
|
|
8967
|
+
const effectiveReview = orgLoaded.config.reviewPolicy ?? settings.reviewPolicy;
|
|
8169
8968
|
const sections = [
|
|
8170
|
-
`Org: ${orgLoaded.config.version} (${orgLoaded.source}, roles: ${Object.keys(orgLoaded.config.roles).join(", ")})`,
|
|
8969
|
+
`Org: ${orgLoaded.config.version} (${orgLoaded.source}, reviewPolicy: ${effectiveReview}, roles: ${Object.keys(orgLoaded.config.roles).join(", ")})`,
|
|
8171
8970
|
"",
|
|
8172
8971
|
"Profiles:",
|
|
8173
8972
|
formatProfileCatalogSummary(profileCatalog),
|
|
@@ -8178,7 +8977,9 @@ var SwarmController = class {
|
|
|
8178
8977
|
] : [],
|
|
8179
8978
|
"",
|
|
8180
8979
|
"Concrete models:",
|
|
8181
|
-
formatModelCatalogSummary(models) || "- (no models enumerated)"
|
|
8980
|
+
formatModelCatalogSummary(models) || "- (no models enumerated)",
|
|
8981
|
+
"",
|
|
8982
|
+
'Reviewer guidance: For substantive implementer changes, spawn role="reviewer" with a different concrete model family than the implementer.'
|
|
8182
8983
|
];
|
|
8183
8984
|
return {
|
|
8184
8985
|
profilesDir: profileCatalog.profilesDir,
|
|
@@ -8216,25 +9017,383 @@ var SwarmController = class {
|
|
|
8216
9017
|
async publishLeaderHandoff(ctx, content, signal) {
|
|
8217
9018
|
this.assertCurrentContext(ctx);
|
|
8218
9019
|
throwIfAborted5(signal, "Pi Agent Swarm leader handoff aborted");
|
|
8219
|
-
|
|
9020
|
+
let effectiveContent = content;
|
|
9021
|
+
if (this.pendingReviewTasks.size > 0) {
|
|
9022
|
+
const pendingLines = [...this.pendingReviewTasks.entries()].map(
|
|
9023
|
+
([taskId, info]) => `- task "${taskId}" (implementer: ${info.implementerName}, model: ${info.implementerModel})`
|
|
9024
|
+
);
|
|
9025
|
+
const suffix = `
|
|
9026
|
+
|
|
9027
|
+
[Pending Independent Review]
|
|
9028
|
+
${pendingLines.join("\n")}`;
|
|
9029
|
+
const combined = `${content.remainingWork}${suffix}`;
|
|
9030
|
+
if (Buffer.byteLength(combined, "utf8") <= 8192) {
|
|
9031
|
+
effectiveContent = { ...content, remainingWork: combined };
|
|
9032
|
+
}
|
|
9033
|
+
}
|
|
9034
|
+
const result = await this.leaderRuntime.publish(effectiveContent, ctx);
|
|
8220
9035
|
if (!this.isCurrent(ctx)) throw staleError();
|
|
9036
|
+
await this.closeActiveMission(ctx, "closed_by_handoff", "handoff", "Closed on leader generation handoff", []);
|
|
8221
9037
|
return result;
|
|
8222
9038
|
}
|
|
9039
|
+
getActiveMission() {
|
|
9040
|
+
return this.activeMission ? { ...this.activeMission } : void 0;
|
|
9041
|
+
}
|
|
9042
|
+
async manageMission(ctx, input) {
|
|
9043
|
+
this.assertCurrentContext(ctx);
|
|
9044
|
+
if (!this.leaderSnapshot(ctx).isLead) {
|
|
9045
|
+
throw new Error("Mission countdown management is available only in the lead session.");
|
|
9046
|
+
}
|
|
9047
|
+
const settings = this.settings.get().settings.missionCountdown;
|
|
9048
|
+
if (!settings.enabled) {
|
|
9049
|
+
throw new Error("Mission countdown is disabled in Pi Agent Swarm settings.");
|
|
9050
|
+
}
|
|
9051
|
+
if (input.missionAction === "status") {
|
|
9052
|
+
const live = isMissionLive(this.activeMission) ? this.activeMission : void 0;
|
|
9053
|
+
if (!live) {
|
|
9054
|
+
return { action: "status", message: "No active mission countdown for this leader generation." };
|
|
9055
|
+
}
|
|
9056
|
+
const remainingMs = Math.max(0, live.deadlineAt - this.deps.now());
|
|
9057
|
+
return {
|
|
9058
|
+
action: "status",
|
|
9059
|
+
mission: { ...live },
|
|
9060
|
+
remainingMs,
|
|
9061
|
+
message: `Mission ${live.missionId} is ${live.state} (remaining ${Math.ceil(remainingMs / 1e3)}s / budget ${live.estimatedMinutes}m).`
|
|
9062
|
+
};
|
|
9063
|
+
}
|
|
9064
|
+
if (input.missionAction === "start") {
|
|
9065
|
+
if (isMissionLive(this.activeMission)) {
|
|
9066
|
+
throw new Error(
|
|
9067
|
+
`Mission "${this.activeMission.missionId}" is already ${this.activeMission.state}. Complete it before starting a new mission.`
|
|
9068
|
+
);
|
|
9069
|
+
}
|
|
9070
|
+
const validated = validateMissionStartInput(
|
|
9071
|
+
{
|
|
9072
|
+
firstPrinciples: input.firstPrinciples ?? "",
|
|
9073
|
+
acceptanceCriteria: input.acceptanceCriteria ?? "",
|
|
9074
|
+
...input.constraints ? { constraints: input.constraints } : {},
|
|
9075
|
+
estimatedMinutes: input.estimatedMinutes
|
|
9076
|
+
},
|
|
9077
|
+
settings
|
|
9078
|
+
);
|
|
9079
|
+
const now = this.deps.now();
|
|
9080
|
+
const durationMs = Math.max(100, Math.round(validated.estimatedMinutes * 6e4));
|
|
9081
|
+
const record3 = {
|
|
9082
|
+
schemaVersion: 1,
|
|
9083
|
+
missionId: this.deps.randomId("mission"),
|
|
9084
|
+
leaderSessionId: ctx.sessionManager.getSessionId(),
|
|
9085
|
+
firstPrinciples: validated.firstPrinciples,
|
|
9086
|
+
acceptanceCriteria: validated.acceptanceCriteria,
|
|
9087
|
+
...validated.constraints ? { constraints: validated.constraints } : {},
|
|
9088
|
+
requestedMinutes: validated.requestedMinutes,
|
|
9089
|
+
estimatedMinutes: validated.estimatedMinutes,
|
|
9090
|
+
clamped: validated.clamped,
|
|
9091
|
+
startedAt: now,
|
|
9092
|
+
deadlineAt: now + durationMs,
|
|
9093
|
+
state: "active"
|
|
9094
|
+
};
|
|
9095
|
+
await writeActiveMission(ctx.cwd, record3);
|
|
9096
|
+
if (!this.isCurrent(ctx)) throw staleError();
|
|
9097
|
+
this.activeMission = record3;
|
|
9098
|
+
this.armMissionTimers(ctx, record3);
|
|
9099
|
+
this.recordLedger(ctx.cwd, {
|
|
9100
|
+
event: "mission_started",
|
|
9101
|
+
task_id: record3.missionId,
|
|
9102
|
+
role: "lead",
|
|
9103
|
+
profile: this.sessionProfile,
|
|
9104
|
+
engine: this.isExternalDirectLeadActive(ctx) ? "agy" : this.sessionRuntime,
|
|
9105
|
+
model: this.currentModelRef(ctx),
|
|
9106
|
+
estimated_minutes: record3.estimatedMinutes,
|
|
9107
|
+
requested_minutes: record3.requestedMinutes,
|
|
9108
|
+
clamped: record3.clamped,
|
|
9109
|
+
goal_chars: record3.firstPrinciples.length
|
|
9110
|
+
});
|
|
9111
|
+
this.renderMissionStatus(ctx);
|
|
9112
|
+
return {
|
|
9113
|
+
action: "start",
|
|
9114
|
+
mission: { ...record3 },
|
|
9115
|
+
remainingMs: durationMs,
|
|
9116
|
+
message: `Mission "${record3.missionId}" armed for ${record3.estimatedMinutes}m${record3.clamped ? ` (clamped from ${record3.requestedMinutes}m)` : ""}.`
|
|
9117
|
+
};
|
|
9118
|
+
}
|
|
9119
|
+
if (input.missionAction === "complete") {
|
|
9120
|
+
if (!isMissionLive(this.activeMission)) {
|
|
9121
|
+
throw new Error("No active mission to complete.");
|
|
9122
|
+
}
|
|
9123
|
+
const validated = validateMissionCompleteInput({
|
|
9124
|
+
summary: input.summary ?? "",
|
|
9125
|
+
...input.outcome ? { outcome: input.outcome } : {},
|
|
9126
|
+
...input.residuals ? { residuals: input.residuals } : {}
|
|
9127
|
+
});
|
|
9128
|
+
const mergedResiduals = [...validated.residuals];
|
|
9129
|
+
if (this.pendingReviewTasks.size > 0) {
|
|
9130
|
+
for (const [taskId, info] of this.pendingReviewTasks) {
|
|
9131
|
+
const note = `Unreviewed implementer task "${taskId}" (${info.implementerName})`;
|
|
9132
|
+
if (!mergedResiduals.some((r) => r.includes(taskId))) {
|
|
9133
|
+
mergedResiduals.push(note);
|
|
9134
|
+
}
|
|
9135
|
+
}
|
|
9136
|
+
}
|
|
9137
|
+
const effectiveOutcome = validated.outcome === "with_residuals" || mergedResiduals.length > 0 || isMissionConverging(this.activeMission) ? mergedResiduals.length > 0 || validated.outcome === "with_residuals" ? "with_residuals" : "achieved" : "achieved";
|
|
9138
|
+
const archived = await this.closeActiveMission(
|
|
9139
|
+
ctx,
|
|
9140
|
+
"completed",
|
|
9141
|
+
effectiveOutcome,
|
|
9142
|
+
validated.summary,
|
|
9143
|
+
mergedResiduals
|
|
9144
|
+
);
|
|
9145
|
+
return {
|
|
9146
|
+
action: "complete",
|
|
9147
|
+
...archived ? { mission: archived } : {},
|
|
9148
|
+
message: `Mission "${archived?.missionId ?? ""}" completed (${effectiveOutcome}${mergedResiduals.length > 0 ? `, ${mergedResiduals.length} residual(s)` : ""}).`
|
|
9149
|
+
};
|
|
9150
|
+
}
|
|
9151
|
+
throw new Error(`Unsupported missionAction "${String(input.missionAction)}"`);
|
|
9152
|
+
}
|
|
9153
|
+
async restoreMissionOnReload(ctx, owner, ownerGeneration) {
|
|
9154
|
+
if (!this.settings.get().settings.missionCountdown.enabled) return;
|
|
9155
|
+
const existing = await readActiveMission(ctx.cwd);
|
|
9156
|
+
if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(existing)) return;
|
|
9157
|
+
if (existing.leaderSessionId !== ctx.sessionManager.getSessionId()) return;
|
|
9158
|
+
this.activeMission = existing;
|
|
9159
|
+
this.armMissionTimers(ctx, existing);
|
|
9160
|
+
this.renderMissionStatus(ctx);
|
|
9161
|
+
}
|
|
9162
|
+
async closePreviousGenerationMissionOnHandoff(ctx) {
|
|
9163
|
+
const existing = await readActiveMission(ctx.cwd);
|
|
9164
|
+
if (!isMissionLive(existing)) return;
|
|
9165
|
+
if (existing.leaderSessionId === ctx.sessionManager.getSessionId()) return;
|
|
9166
|
+
const now = this.deps.now();
|
|
9167
|
+
const closed = {
|
|
9168
|
+
...existing,
|
|
9169
|
+
state: "closed_by_handoff",
|
|
9170
|
+
outcome: "handoff",
|
|
9171
|
+
completedAt: now,
|
|
9172
|
+
summary: "Previous leader generation ended; successor leader will re-evaluate from handoff."
|
|
9173
|
+
};
|
|
9174
|
+
await archiveMission(ctx.cwd, closed).catch(() => void 0);
|
|
9175
|
+
this.recordLedger(ctx.cwd, {
|
|
9176
|
+
event: "mission_completed",
|
|
9177
|
+
task_id: closed.missionId,
|
|
9178
|
+
role: "lead",
|
|
9179
|
+
profile: this.sessionProfile,
|
|
9180
|
+
engine: this.sessionRuntime,
|
|
9181
|
+
model: this.currentModelRef(ctx),
|
|
9182
|
+
outcome: "handoff",
|
|
9183
|
+
final_state: "closed_by_handoff",
|
|
9184
|
+
elapsed_ms: Math.max(0, now - closed.startedAt),
|
|
9185
|
+
residual_count: closed.residuals?.length ?? 0
|
|
9186
|
+
});
|
|
9187
|
+
}
|
|
9188
|
+
async closeActiveMission(ctx, finalState, outcome, summary, residuals) {
|
|
9189
|
+
const current = this.activeMission;
|
|
9190
|
+
this.stopMissionTimers();
|
|
9191
|
+
this.activeMission = void 0;
|
|
9192
|
+
this.renderMissionStatus(ctx);
|
|
9193
|
+
if (!current) return void 0;
|
|
9194
|
+
const now = this.deps.now();
|
|
9195
|
+
const archived = {
|
|
9196
|
+
...current,
|
|
9197
|
+
state: finalState,
|
|
9198
|
+
outcome,
|
|
9199
|
+
completedAt: now,
|
|
9200
|
+
summary,
|
|
9201
|
+
...residuals.length > 0 ? { residuals } : {}
|
|
9202
|
+
};
|
|
9203
|
+
await archiveMission(ctx.cwd, archived).catch(() => void 0);
|
|
9204
|
+
this.recordLedger(ctx.cwd, {
|
|
9205
|
+
event: "mission_completed",
|
|
9206
|
+
task_id: archived.missionId,
|
|
9207
|
+
role: "lead",
|
|
9208
|
+
profile: this.sessionProfile,
|
|
9209
|
+
engine: this.isExternalDirectLeadActive(ctx) ? "agy" : this.sessionRuntime,
|
|
9210
|
+
model: this.currentModelRef(ctx),
|
|
9211
|
+
outcome,
|
|
9212
|
+
final_state: finalState,
|
|
9213
|
+
elapsed_ms: Math.max(0, now - archived.startedAt),
|
|
9214
|
+
residual_count: residuals.length
|
|
9215
|
+
});
|
|
9216
|
+
return archived;
|
|
9217
|
+
}
|
|
9218
|
+
armMissionTimers(ctx, record3) {
|
|
9219
|
+
this.stopMissionTimers();
|
|
9220
|
+
const owner = ctx.sessionManager;
|
|
9221
|
+
const ownerGeneration = this.generation;
|
|
9222
|
+
const settings = this.settings.get().settings.missionCountdown;
|
|
9223
|
+
const now = this.deps.now();
|
|
9224
|
+
if (record3.state === "active") {
|
|
9225
|
+
const delayMs = Math.max(0, record3.deadlineAt - now);
|
|
9226
|
+
this.missionTimer = setTimeout(() => {
|
|
9227
|
+
void this.handleMissionTimeout(ctx, owner, ownerGeneration, "converging");
|
|
9228
|
+
}, delayMs);
|
|
9229
|
+
this.missionTimer.unref?.();
|
|
9230
|
+
} else if (record3.state === "converging") {
|
|
9231
|
+
const targetAt = (record3.convergingAt ?? record3.deadlineAt) + settings.wrapUpGraceMs;
|
|
9232
|
+
const delayMs = Math.max(0, targetAt - now);
|
|
9233
|
+
this.missionTimer = setTimeout(() => {
|
|
9234
|
+
void this.handleMissionTimeout(ctx, owner, ownerGeneration, "final_wrap_up");
|
|
9235
|
+
}, delayMs);
|
|
9236
|
+
this.missionTimer.unref?.();
|
|
9237
|
+
} else if (record3.state === "final_wrap_up") {
|
|
9238
|
+
const autoCloseMs = Math.max(
|
|
9239
|
+
MIN_FINAL_WRAP_UP_MS,
|
|
9240
|
+
Math.round(settings.wrapUpGraceMs * FINAL_WRAP_UP_AUTO_CLOSE_FACTOR)
|
|
9241
|
+
);
|
|
9242
|
+
const targetAt = (record3.finalWrapUpAt ?? now) + autoCloseMs;
|
|
9243
|
+
const delayMs = Math.max(0, targetAt - now);
|
|
9244
|
+
this.missionTimer = setTimeout(() => {
|
|
9245
|
+
void this.handleMissionAutoClose(ctx, owner, ownerGeneration);
|
|
9246
|
+
}, delayMs);
|
|
9247
|
+
this.missionTimer.unref?.();
|
|
9248
|
+
}
|
|
9249
|
+
this.missionTicker = setInterval(() => {
|
|
9250
|
+
if (!this.isCurrent(owner, ownerGeneration) || !isMissionLive(this.activeMission)) {
|
|
9251
|
+
this.stopMissionTimers();
|
|
9252
|
+
return;
|
|
9253
|
+
}
|
|
9254
|
+
this.renderMissionStatus(ctx);
|
|
9255
|
+
}, 15e3);
|
|
9256
|
+
this.missionTicker.unref?.();
|
|
9257
|
+
}
|
|
9258
|
+
async handleMissionTimeout(ctx, owner, ownerGeneration, stage) {
|
|
9259
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
9260
|
+
const current = this.activeMission;
|
|
9261
|
+
if (!isMissionLive(current)) return;
|
|
9262
|
+
if (stage === "converging" && current.state !== "active") return;
|
|
9263
|
+
if (stage === "final_wrap_up" && current.state !== "converging") return;
|
|
9264
|
+
const now = this.deps.now();
|
|
9265
|
+
const updated = {
|
|
9266
|
+
...current,
|
|
9267
|
+
state: stage,
|
|
9268
|
+
...stage === "converging" ? { convergingAt: now } : { finalWrapUpAt: now }
|
|
9269
|
+
};
|
|
9270
|
+
this.activeMission = updated;
|
|
9271
|
+
await writeActiveMission(ctx.cwd, updated).catch(() => void 0);
|
|
9272
|
+
if (!this.isCurrent(owner, ownerGeneration) || this.activeMission?.missionId !== updated.missionId) return;
|
|
9273
|
+
const isExternal = this.isExternalDirectLeadActive(ctx);
|
|
9274
|
+
const busToolName = isExternal ? "swarm_bus" : "session_bus";
|
|
9275
|
+
const injection = formatMissionTimeoutInjection({
|
|
9276
|
+
mission: updated,
|
|
9277
|
+
stage,
|
|
9278
|
+
now,
|
|
9279
|
+
inFlightWorkerCount: this.pendingKickoffIds.size,
|
|
9280
|
+
busToolName
|
|
9281
|
+
});
|
|
9282
|
+
this.recordLedger(ctx.cwd, {
|
|
9283
|
+
event: "mission_timeout",
|
|
9284
|
+
task_id: updated.missionId,
|
|
9285
|
+
role: "lead",
|
|
9286
|
+
profile: this.sessionProfile,
|
|
9287
|
+
engine: isExternal ? "agy" : this.sessionRuntime,
|
|
9288
|
+
model: this.currentModelRef(ctx),
|
|
9289
|
+
stage,
|
|
9290
|
+
elapsed_ms: Math.max(0, now - updated.startedAt),
|
|
9291
|
+
in_flight_workers: this.pendingKickoffIds.size
|
|
9292
|
+
});
|
|
9293
|
+
if (isExternal && this.activeDirectRuntime) {
|
|
9294
|
+
this.pi.sendMessage(
|
|
9295
|
+
{ customType: MISSION_CUSTOM_TYPE, content: injection, display: true },
|
|
9296
|
+
{ deliverAs: "followUp", triggerTurn: false }
|
|
9297
|
+
);
|
|
9298
|
+
this.externalRuntime.deliverToDirect({
|
|
9299
|
+
runtimeId: this.activeDirectRuntime.runtimeId,
|
|
9300
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
9301
|
+
prompt: injection,
|
|
9302
|
+
source: "leader_advisory"
|
|
9303
|
+
});
|
|
9304
|
+
} else {
|
|
9305
|
+
this.pi.sendMessage(
|
|
9306
|
+
{ customType: MISSION_CUSTOM_TYPE, content: injection, display: true },
|
|
9307
|
+
{ deliverAs: "followUp", triggerTurn: !this.leaderRuntime.shouldDeferFollowUp() }
|
|
9308
|
+
);
|
|
9309
|
+
}
|
|
9310
|
+
this.armMissionTimers(ctx, updated);
|
|
9311
|
+
this.renderMissionStatus(ctx);
|
|
9312
|
+
}
|
|
9313
|
+
async handleMissionAutoClose(ctx, owner, ownerGeneration) {
|
|
9314
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
9315
|
+
const current = this.activeMission;
|
|
9316
|
+
if (current?.state !== "final_wrap_up") return;
|
|
9317
|
+
const residuals = [
|
|
9318
|
+
`Mission "${current.missionId}" autonomously auto-closed after exceeding its ${current.estimatedMinutes}m estimate and wrap-up window without an explicit complete call.`
|
|
9319
|
+
];
|
|
9320
|
+
for (const [taskId, info] of this.pendingReviewTasks) {
|
|
9321
|
+
residuals.push(`Unreviewed implementer task "${taskId}" (${info.implementerName})`);
|
|
9322
|
+
}
|
|
9323
|
+
await this.closeActiveMission(
|
|
9324
|
+
ctx,
|
|
9325
|
+
"auto_completed",
|
|
9326
|
+
"with_residuals",
|
|
9327
|
+
"Autonomously closed after final wrap-up convergence timeout (with residuals).",
|
|
9328
|
+
residuals
|
|
9329
|
+
);
|
|
9330
|
+
}
|
|
9331
|
+
stopMissionTimers() {
|
|
9332
|
+
if (this.missionTimer !== void 0) {
|
|
9333
|
+
clearTimeout(this.missionTimer);
|
|
9334
|
+
this.missionTimer = void 0;
|
|
9335
|
+
}
|
|
9336
|
+
if (this.missionTicker !== void 0) {
|
|
9337
|
+
clearInterval(this.missionTicker);
|
|
9338
|
+
this.missionTicker = void 0;
|
|
9339
|
+
}
|
|
9340
|
+
}
|
|
9341
|
+
renderMissionStatus(ctx) {
|
|
9342
|
+
if (!ctx.hasUI) return;
|
|
9343
|
+
const badge2 = formatMissionStatusBadge(this.activeMission, this.deps.now());
|
|
9344
|
+
try {
|
|
9345
|
+
ctx.ui.setStatus(MISSION_STATUS_KEY, badge2);
|
|
9346
|
+
} catch {
|
|
9347
|
+
}
|
|
9348
|
+
}
|
|
8223
9349
|
activateLeaderToolIfLead(ctx) {
|
|
8224
9350
|
if (!this.settings.get().settings.leaderRecycling.enabled || !this.leaderSnapshot(ctx).isLead) return;
|
|
8225
9351
|
const activeTools = this.pi.getActiveTools();
|
|
8226
9352
|
if (activeTools.includes("leader_handoff")) return;
|
|
8227
9353
|
this.pi.setActiveTools([...activeTools, "leader_handoff"]);
|
|
8228
9354
|
}
|
|
9355
|
+
decideCacheWarming(event, ctx) {
|
|
9356
|
+
const isLead = this.leaderSnapshot(ctx).isLead;
|
|
9357
|
+
const externalDirectActive = this.isExternalDirectLeadActive(ctx);
|
|
9358
|
+
const inFlightWorkerCount = this.pendingKickoffIds.size;
|
|
9359
|
+
const outcome = this.cacheWarmingPolicy.evaluate({
|
|
9360
|
+
defaultAction: event.action,
|
|
9361
|
+
model: ctx.model,
|
|
9362
|
+
isLead,
|
|
9363
|
+
externalDirectActive,
|
|
9364
|
+
inFlightWorkerCount,
|
|
9365
|
+
settings: this.settings.get().settings.cacheWarming,
|
|
9366
|
+
now: this.deps.now()
|
|
9367
|
+
});
|
|
9368
|
+
return { action: outcome.action };
|
|
9369
|
+
}
|
|
9370
|
+
isExternalDirectLeadActive(ctx) {
|
|
9371
|
+
if (!ctx || !this.activeDirectRuntime?.active) return false;
|
|
9372
|
+
return this.sessionRole === "lead" && this.leaderSnapshot(ctx).isLead;
|
|
9373
|
+
}
|
|
9374
|
+
effectiveReviewPolicy(projectRoot) {
|
|
9375
|
+
const orgLoaded = loadProjectOrgConfig(projectRoot);
|
|
9376
|
+
return orgLoaded.config.reviewPolicy ?? this.settings.get().settings.reviewPolicy;
|
|
9377
|
+
}
|
|
8229
9378
|
leaderSnapshot(ctx) {
|
|
8230
9379
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
9380
|
+
const isLead = this.leadSessionId === sessionId || !this.membership && this.defaultLead;
|
|
9381
|
+
const direct = isLead && this.activeDirectRuntime?.active ? this.activeDirectRuntime : void 0;
|
|
8231
9382
|
return {
|
|
8232
|
-
isLead
|
|
9383
|
+
isLead,
|
|
8233
9384
|
pendingKickoffIds: [...this.pendingKickoffIds],
|
|
8234
9385
|
invite: this.membership?.invite,
|
|
8235
9386
|
groupDirectory: this.membership?.transport.endpointManifest?.directory,
|
|
8236
9387
|
acceptsRequests: this.membership?.acceptsRequests ?? false,
|
|
8237
|
-
color: this.color
|
|
9388
|
+
color: this.color,
|
|
9389
|
+
...direct ? {
|
|
9390
|
+
externalRuntime: {
|
|
9391
|
+
runtimeId: direct.runtimeId,
|
|
9392
|
+
...direct.model ? { model: direct.model } : {},
|
|
9393
|
+
...direct.thoughtLevel ? { thoughtLevel: direct.thoughtLevel } : {},
|
|
9394
|
+
...direct.mode ? { mode: direct.mode } : {}
|
|
9395
|
+
}
|
|
9396
|
+
} : {}
|
|
8238
9397
|
};
|
|
8239
9398
|
}
|
|
8240
9399
|
async restoreLeaderControl(ctx, entry) {
|
|
@@ -8394,13 +9553,13 @@ var SwarmController = class {
|
|
|
8394
9553
|
await attempt("Could not clear the failed leader footer", () => this.clearStatus(ctx));
|
|
8395
9554
|
await attempt("Could not clear the failed leader roster", () => this.clearRosterStatus(ctx));
|
|
8396
9555
|
if (this.isCurrent(ctx)) this.preserveDeferredFollowUps(ctx, entry);
|
|
8397
|
-
const directory = entry.groupDirectory ?? (group ?
|
|
9556
|
+
const directory = entry.groupDirectory ?? (group ? join16(this.deps.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), group.id) : void 0);
|
|
8398
9557
|
if (!directory) return;
|
|
8399
9558
|
await attempt("Could not remove the dead predecessor lead record after pre-commit failure", async () => {
|
|
8400
9559
|
try {
|
|
8401
|
-
const raw = JSON.parse(await
|
|
9560
|
+
const raw = JSON.parse(await readFile7(join16(directory, "lead.json"), "utf8"));
|
|
8402
9561
|
if (raw.sessionId === entry.previousSessionId || raw.sessionId === ctx.sessionManager.getSessionId()) {
|
|
8403
|
-
await
|
|
9562
|
+
await rm11(join16(directory, "lead.json"), { force: true });
|
|
8404
9563
|
}
|
|
8405
9564
|
} catch (error) {
|
|
8406
9565
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -8408,7 +9567,7 @@ var SwarmController = class {
|
|
|
8408
9567
|
});
|
|
8409
9568
|
}
|
|
8410
9569
|
async validateWorkerOwnership(ctx, previousSessionId) {
|
|
8411
|
-
const directory =
|
|
9570
|
+
const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
|
|
8412
9571
|
let entries;
|
|
8413
9572
|
try {
|
|
8414
9573
|
entries = await readdir4(directory, { withFileTypes: true });
|
|
@@ -8436,7 +9595,7 @@ var SwarmController = class {
|
|
|
8436
9595
|
if (previousSessionId.length === 0) throw new Error("The previous leader session id is empty.");
|
|
8437
9596
|
}
|
|
8438
9597
|
async rebindWorkerLineages(ctx, previousSessionId, nextSessionId = ctx.sessionManager.getSessionId()) {
|
|
8439
|
-
const directory =
|
|
9598
|
+
const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
|
|
8440
9599
|
let entries;
|
|
8441
9600
|
try {
|
|
8442
9601
|
entries = await readdir4(directory, { withFileTypes: true });
|
|
@@ -8576,6 +9735,7 @@ var SwarmController = class {
|
|
|
8576
9735
|
}
|
|
8577
9736
|
async agentStarted(ctx) {
|
|
8578
9737
|
if (!this.isCurrent(ctx)) return;
|
|
9738
|
+
this.cacheWarmingPolicy.resetWaitWindow();
|
|
8579
9739
|
await this.leaderRuntime.agentStarted(ctx);
|
|
8580
9740
|
}
|
|
8581
9741
|
async agentSettled(ctx, aborted = false) {
|
|
@@ -8973,6 +10133,13 @@ var SwarmController = class {
|
|
|
8973
10133
|
await this.resourceLeases.releaseMany(childMeta.leases).catch(() => void 0);
|
|
8974
10134
|
childMeta.leases = [];
|
|
8975
10135
|
}
|
|
10136
|
+
if (childMeta?.role === "implementer" && this.effectiveReviewPolicy(ctx.cwd) === "required" && !this.verdictStore.hasPassingVerdict(childMeta.taskId)) {
|
|
10137
|
+
this.notify(
|
|
10138
|
+
ctx,
|
|
10139
|
+
`[Swarm Governance] Shutting down implementer for task "${childMeta.taskId}" before any independent reviewer "pass" verdict was recorded.`,
|
|
10140
|
+
"warning"
|
|
10141
|
+
);
|
|
10142
|
+
}
|
|
8976
10143
|
}
|
|
8977
10144
|
return { message, acknowledgement };
|
|
8978
10145
|
}
|
|
@@ -8990,6 +10157,19 @@ var SwarmController = class {
|
|
|
8990
10157
|
await this.settings.flush();
|
|
8991
10158
|
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
8992
10159
|
const launchSettings = this.settings.get().settings;
|
|
10160
|
+
const isWorkerReplacement = input.recyclingLaunch !== void 0 && input.recyclingLaunch.generation > 1;
|
|
10161
|
+
if (!isWorkerReplacement && this.leaderSnapshot(ctx).isLead) {
|
|
10162
|
+
const requestedRole = input.role ?? "implementer";
|
|
10163
|
+
const missionGate = checkMissionSpawnGate({
|
|
10164
|
+
mission: this.activeMission,
|
|
10165
|
+
role: requestedRole,
|
|
10166
|
+
settings: launchSettings.missionCountdown,
|
|
10167
|
+
busToolName: this.isExternalDirectLeadActive(ctx) ? "swarm_bus" : "session_bus"
|
|
10168
|
+
});
|
|
10169
|
+
if (!missionGate.allowed) {
|
|
10170
|
+
throw new Error(missionGate.reason ?? "Mission countdown gate rejected spawn");
|
|
10171
|
+
}
|
|
10172
|
+
}
|
|
8993
10173
|
const recyclingLaunch = input.recyclingLaunch ?? (input.contextRecycling ? {
|
|
8994
10174
|
lineageId: this.deps.randomId("lineage"),
|
|
8995
10175
|
generation: 1,
|
|
@@ -9474,7 +10654,7 @@ var SwarmController = class {
|
|
|
9474
10654
|
this.successorLaunches.set(key, task);
|
|
9475
10655
|
}
|
|
9476
10656
|
async recoverProjectHandoffs(ctx) {
|
|
9477
|
-
const directory =
|
|
10657
|
+
const directory = resolve13(ctx.cwd, ".pi", "agent-swarm", "lineages");
|
|
9478
10658
|
const entries = await readdir4(directory, { withFileTypes: true }).catch((error) => {
|
|
9479
10659
|
if (error.code === "ENOENT") return [];
|
|
9480
10660
|
throw error;
|
|
@@ -9502,7 +10682,7 @@ var SwarmController = class {
|
|
|
9502
10682
|
continue;
|
|
9503
10683
|
}
|
|
9504
10684
|
const expectedPath = workerLineagePaths(ctx.cwd, entry.name, lineage.currentGeneration).handoffPath;
|
|
9505
|
-
const complete = await
|
|
10685
|
+
const complete = await readFile7(expectedPath, "utf8").then((markdown) => hasRequiredHandoffSections(markdown)).catch(() => false);
|
|
9506
10686
|
if (!complete) continue;
|
|
9507
10687
|
try {
|
|
9508
10688
|
await updateWorkerLineage(
|
|
@@ -9537,21 +10717,21 @@ var SwarmController = class {
|
|
|
9537
10717
|
async spawnSuccessor(ctx, message) {
|
|
9538
10718
|
const projectRoot = message.fromCwd;
|
|
9539
10719
|
if (!projectRoot) throw new Error("Handoff sender did not provide its project cwd");
|
|
9540
|
-
const handoffPath =
|
|
9541
|
-
const storagePrefix = `${
|
|
10720
|
+
const handoffPath = resolve13(message.text);
|
|
10721
|
+
const storagePrefix = `${resolve13(projectRoot, ".pi", "agent-swarm", "lineages")}${sep3}`;
|
|
9542
10722
|
if (!handoffPath.startsWith(storagePrefix) || basename7(dirname7(handoffPath)) !== "generations") {
|
|
9543
10723
|
throw new Error("Handoff path is outside the sender's project lineage storage");
|
|
9544
10724
|
}
|
|
9545
10725
|
const lineageId = basename7(dirname7(dirname7(handoffPath)));
|
|
9546
10726
|
const lineage = await readWorkerLineage(projectRoot, lineageId);
|
|
9547
10727
|
if (!this.isCurrent(ctx)) throw staleError();
|
|
9548
|
-
if (lineage.leaderSessionId !== ctx.sessionManager.getSessionId() ||
|
|
10728
|
+
if (lineage.leaderSessionId !== ctx.sessionManager.getSessionId() || resolve13(lineage.currentHandoffPath ?? "") !== handoffPath || lineage.state !== "handoff_ready" || !lineage.nextAction) {
|
|
9549
10729
|
throw new Error("Handoff lineage is not ready for this leader");
|
|
9550
10730
|
}
|
|
9551
10731
|
if (lineage.replacementCount >= lineage.policy.maxReplacements) {
|
|
9552
10732
|
throw new Error("Handoff replacement budget is exhausted");
|
|
9553
10733
|
}
|
|
9554
|
-
await
|
|
10734
|
+
await readFile7(handoffPath, "utf8");
|
|
9555
10735
|
const nextGeneration = lineage.currentGeneration + 1;
|
|
9556
10736
|
const replacementCount = lineage.replacementCount + 1;
|
|
9557
10737
|
await updateWorkerLineage(
|
|
@@ -9708,6 +10888,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9708
10888
|
return false;
|
|
9709
10889
|
}
|
|
9710
10890
|
const shouldTrigger = resolvedTrigger ?? this.resolveTriggerTurn(message);
|
|
10891
|
+
let governanceSuffix = "";
|
|
9711
10892
|
if (message.mode === "reply" && this.activeContext) {
|
|
9712
10893
|
if (message.text.includes("[SWARM_SIGNAL:QUOTA_EXHAUSTED]")) {
|
|
9713
10894
|
const senderMeta = this.childRecords.get(message.fromSessionId);
|
|
@@ -9752,9 +10933,54 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9752
10933
|
source: message.fromSessionId,
|
|
9753
10934
|
score: parsedVerdict.score
|
|
9754
10935
|
});
|
|
10936
|
+
if (parsedVerdict.verdict === "pass") {
|
|
10937
|
+
this.pendingReviewTasks.delete(replyTaskId);
|
|
10938
|
+
} else if (parsedVerdict.verdict === "fail") {
|
|
10939
|
+
const consecutiveFails = this.verdictStore.consecutiveFailsForTask(replyTaskId);
|
|
10940
|
+
if (consecutiveFails >= MAX_CONSECUTIVE_REVIEWER_FAILS) {
|
|
10941
|
+
this.recordLedger(this.activeContext.cwd, {
|
|
10942
|
+
event: "run_escalated",
|
|
10943
|
+
task_id: replyTaskId,
|
|
10944
|
+
role: "lead",
|
|
10945
|
+
profile: replyProfile,
|
|
10946
|
+
engine: replyEngine,
|
|
10947
|
+
model: replyModel,
|
|
10948
|
+
reason: "reviewer_consecutive_failures",
|
|
10949
|
+
budget_left: { consecutiveFails }
|
|
10950
|
+
});
|
|
10951
|
+
governanceSuffix = formatReviewerEscalationNotice({
|
|
10952
|
+
taskId: replyTaskId,
|
|
10953
|
+
consecutiveFails,
|
|
10954
|
+
blockingIssues: parsedVerdict.blocking_issues
|
|
10955
|
+
});
|
|
10956
|
+
}
|
|
10957
|
+
}
|
|
9755
10958
|
} catch {
|
|
9756
10959
|
}
|
|
9757
10960
|
}
|
|
10961
|
+
} else if (childRecord?.role === "implementer") {
|
|
10962
|
+
if (!this.verdictStore.hasPassingVerdict(replyTaskId)) {
|
|
10963
|
+
this.pendingReviewTasks.set(replyTaskId, {
|
|
10964
|
+
implementerSessionId: message.fromSessionId,
|
|
10965
|
+
implementerName: sender,
|
|
10966
|
+
implementerModel: replyModel
|
|
10967
|
+
});
|
|
10968
|
+
const reviewPolicy = this.effectiveReviewPolicy(this.activeContext.cwd);
|
|
10969
|
+
if (reviewPolicy === "suggest" || reviewPolicy === "required") {
|
|
10970
|
+
const catalog = buildModelCatalog(this.activeContext, this.externalRuntimes, this.quotaSeenByModel);
|
|
10971
|
+
const suggestedReviewerModels = suggestCrossFamilyReviewerModels(
|
|
10972
|
+
replyModel,
|
|
10973
|
+
catalog.entries.map((entry) => ({ ref: entry.modelRef, sawQuota: entry.sawQuota }))
|
|
10974
|
+
);
|
|
10975
|
+
governanceSuffix = formatReviewGovernanceReminder({
|
|
10976
|
+
policy: reviewPolicy,
|
|
10977
|
+
taskId: replyTaskId,
|
|
10978
|
+
implementerName: sender,
|
|
10979
|
+
implementerModel: replyModel,
|
|
10980
|
+
suggestedReviewerModels
|
|
10981
|
+
});
|
|
10982
|
+
}
|
|
10983
|
+
}
|
|
9758
10984
|
}
|
|
9759
10985
|
if (childRecord) {
|
|
9760
10986
|
this.recordLedger(this.activeContext.cwd, {
|
|
@@ -9771,10 +10997,33 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9771
10997
|
});
|
|
9772
10998
|
}
|
|
9773
10999
|
}
|
|
11000
|
+
const deliveredContent = `${content}${replyGuidance}${governanceSuffix}`;
|
|
11001
|
+
const wantsTrigger = allowTrigger && shouldTrigger && !this.leaderRuntime.shouldDeferFollowUp();
|
|
11002
|
+
const activeCtx = this.activeContext;
|
|
11003
|
+
if (wantsTrigger && activeCtx && this.isExternalDirectLeadActive(activeCtx) && this.activeDirectRuntime) {
|
|
11004
|
+
this.pi.sendMessage(
|
|
11005
|
+
{
|
|
11006
|
+
customType: SWARM_MESSAGE_TYPE,
|
|
11007
|
+
content: deliveredContent,
|
|
11008
|
+
display: true,
|
|
11009
|
+
details
|
|
11010
|
+
},
|
|
11011
|
+
{ deliverAs: "followUp", triggerTurn: false }
|
|
11012
|
+
);
|
|
11013
|
+
this.externalRuntime.deliverToDirect({
|
|
11014
|
+
runtimeId: this.activeDirectRuntime.runtimeId,
|
|
11015
|
+
sessionId: activeCtx.sessionManager.getSessionId(),
|
|
11016
|
+
prompt: deliveredContent,
|
|
11017
|
+
source: "swarm_message",
|
|
11018
|
+
messageId: message.id,
|
|
11019
|
+
fromSessionId: message.fromSessionId
|
|
11020
|
+
});
|
|
11021
|
+
return shouldTrigger;
|
|
11022
|
+
}
|
|
9774
11023
|
this.pi.sendMessage(
|
|
9775
11024
|
{
|
|
9776
11025
|
customType: SWARM_MESSAGE_TYPE,
|
|
9777
|
-
content:
|
|
11026
|
+
content: deliveredContent,
|
|
9778
11027
|
display: true,
|
|
9779
11028
|
details
|
|
9780
11029
|
},
|
|
@@ -9782,7 +11031,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9782
11031
|
deliverAs: "followUp",
|
|
9783
11032
|
// A replayed message must not start a turn while the restoring leader is still being
|
|
9784
11033
|
// configured; the successor kickoff starts it after setModel/setThinkingLevel.
|
|
9785
|
-
triggerTurn:
|
|
11034
|
+
triggerTurn: wantsTrigger
|
|
9786
11035
|
}
|
|
9787
11036
|
);
|
|
9788
11037
|
return shouldTrigger;
|
|
@@ -9936,7 +11185,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9936
11185
|
if (raw.includes("\0") || raw.trim().length === 0) {
|
|
9937
11186
|
throw new Error(`session_spawn contextFiles entry "${raw}" is invalid`);
|
|
9938
11187
|
}
|
|
9939
|
-
const target =
|
|
11188
|
+
const target = resolve13(cwd, raw.trim());
|
|
9940
11189
|
let canonical;
|
|
9941
11190
|
try {
|
|
9942
11191
|
canonical = await this.deps.realpath(target);
|
|
@@ -9961,7 +11210,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9961
11210
|
if (raw.includes("\0") || raw.trim().length === 0) {
|
|
9962
11211
|
throw new Error(`session_spawn readableDirs entry "${raw}" is invalid`);
|
|
9963
11212
|
}
|
|
9964
|
-
const target =
|
|
11213
|
+
const target = resolve13(cwd, raw.trim());
|
|
9965
11214
|
let canonical;
|
|
9966
11215
|
try {
|
|
9967
11216
|
canonical = await this.deps.realpath(target);
|
|
@@ -9979,7 +11228,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9979
11228
|
return validated;
|
|
9980
11229
|
}
|
|
9981
11230
|
async resolveSpawnCwd(ctx, value) {
|
|
9982
|
-
const requested = value?.trim() ?
|
|
11231
|
+
const requested = value?.trim() ? resolve13(ctx.cwd, value) : ctx.cwd;
|
|
9983
11232
|
const canonical = await this.deps.realpath(requested);
|
|
9984
11233
|
if (canonical.includes("\0") || Buffer.byteLength(canonical) > 4096) {
|
|
9985
11234
|
throw new Error("Pi Agent Swarm child cwd is invalid or too large");
|
|
@@ -9994,6 +11243,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
9994
11243
|
}
|
|
9995
11244
|
async cleanupActive(reloading) {
|
|
9996
11245
|
this.generation += 1;
|
|
11246
|
+
this.stopMissionTimers();
|
|
9997
11247
|
this.stopExternalTurnSubscription();
|
|
9998
11248
|
this.externalAutoNameMessages.length = 0;
|
|
9999
11249
|
this.controller.abort();
|
|
@@ -10022,7 +11272,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
10022
11272
|
membership?.group.secret.fill(0);
|
|
10023
11273
|
}
|
|
10024
11274
|
if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
|
|
10025
|
-
await
|
|
11275
|
+
await rm11(join16(directory, "lead.json"), { force: true }).catch(() => void 0);
|
|
10026
11276
|
}
|
|
10027
11277
|
this.leadSessionId = void 0;
|
|
10028
11278
|
this.leadRefreshEpoch += 1;
|
|
@@ -10079,7 +11329,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
10079
11329
|
}
|
|
10080
11330
|
leadPath() {
|
|
10081
11331
|
const directory = this.membership?.transport.endpointManifest?.directory;
|
|
10082
|
-
return directory ?
|
|
11332
|
+
return directory ? join16(directory, "lead.json") : void 0;
|
|
10083
11333
|
}
|
|
10084
11334
|
async republishCommittedLead() {
|
|
10085
11335
|
const ctx = this.activeContext;
|
|
@@ -10100,7 +11350,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
10100
11350
|
const path2 = this.leadPath();
|
|
10101
11351
|
if (!path2) return this.applyObservedLead(void 0, epoch);
|
|
10102
11352
|
try {
|
|
10103
|
-
const raw = JSON.parse(await
|
|
11353
|
+
const raw = JSON.parse(await readFile7(path2, "utf8"));
|
|
10104
11354
|
const next = typeof raw.sessionId === "string" ? raw.sessionId : void 0;
|
|
10105
11355
|
return this.applyObservedLead(next, epoch);
|
|
10106
11356
|
} catch {
|
|
@@ -10149,6 +11399,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
10149
11399
|
ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
|
|
10150
11400
|
} catch {
|
|
10151
11401
|
}
|
|
11402
|
+
this.renderMissionStatus(ctx);
|
|
10152
11403
|
}
|
|
10153
11404
|
/** Resolve a peer by name or session id from the current snapshot. */
|
|
10154
11405
|
async resolvePeer(target, signal) {
|
|
@@ -10174,7 +11425,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
10174
11425
|
`, { encoding: "utf8", flag: "wx" });
|
|
10175
11426
|
await rename5(temporary, path2);
|
|
10176
11427
|
} finally {
|
|
10177
|
-
await
|
|
11428
|
+
await rm11(temporary, { force: true }).catch(() => void 0);
|
|
10178
11429
|
}
|
|
10179
11430
|
this.assertCurrentContext(ctx);
|
|
10180
11431
|
if (target.sessionId !== this.committedLeadSessionId) {
|
|
@@ -10514,7 +11765,9 @@ function isRecord6(value) {
|
|
|
10514
11765
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
10515
11766
|
import { Type } from "typebox";
|
|
10516
11767
|
var DIRECTIONS = ["right", "down", "left", "up"];
|
|
10517
|
-
var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff", "catalog", "fanout"];
|
|
11768
|
+
var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff", "catalog", "fanout", "mission"];
|
|
11769
|
+
var MISSION_ACTIONS = ["start", "complete", "status"];
|
|
11770
|
+
var MISSION_OUTCOMES = ["achieved", "with_residuals"];
|
|
10518
11771
|
var SEND_MODES = ["notify", "request"];
|
|
10519
11772
|
var ROLES = ["implementer", "researcher", "reviewer"];
|
|
10520
11773
|
var MAX_LISTED_PEERS = 64;
|
|
@@ -10661,7 +11914,54 @@ var busSchema = Type.Object(
|
|
|
10661
11914
|
)
|
|
10662
11915
|
),
|
|
10663
11916
|
deadlineMs: Type.Optional(Type.Integer({ minimum: 1e3, maximum: 36e5 })),
|
|
10664
|
-
allowPartial: Type.Optional(Type.Boolean())
|
|
11917
|
+
allowPartial: Type.Optional(Type.Boolean()),
|
|
11918
|
+
missionAction: Type.Optional(
|
|
11919
|
+
StringEnum(MISSION_ACTIONS, {
|
|
11920
|
+
description: 'Sub-action for action="mission": "start" (establish first-principles requirement + time estimate), "complete" (close round, achieved or with_residuals), or "status".'
|
|
11921
|
+
})
|
|
11922
|
+
),
|
|
11923
|
+
firstPrinciples: Type.Optional(
|
|
11924
|
+
Type.String({
|
|
11925
|
+
description: 'First-principles core requirement for this swarm round (the essential problem to solve, stripped of intermediate hacks). Required for missionAction="start".',
|
|
11926
|
+
maxLength: 4096
|
|
11927
|
+
})
|
|
11928
|
+
),
|
|
11929
|
+
acceptanceCriteria: Type.Optional(
|
|
11930
|
+
Type.String({
|
|
11931
|
+
description: 'Objective completion criteria for this round. Required for missionAction="start".',
|
|
11932
|
+
maxLength: 4096
|
|
11933
|
+
})
|
|
11934
|
+
),
|
|
11935
|
+
constraints: Type.Optional(
|
|
11936
|
+
Type.String({
|
|
11937
|
+
description: 'Optional hard constraints or non-goals for missionAction="start".',
|
|
11938
|
+
maxLength: 4096
|
|
11939
|
+
})
|
|
11940
|
+
),
|
|
11941
|
+
estimatedMinutes: Type.Optional(
|
|
11942
|
+
Type.Number({
|
|
11943
|
+
description: 'Model self-assessed time budget in minutes for this round (clamped to configured bounds). Required for missionAction="start".',
|
|
11944
|
+
minimum: 0.01,
|
|
11945
|
+
maximum: 480
|
|
11946
|
+
})
|
|
11947
|
+
),
|
|
11948
|
+
summary: Type.Optional(
|
|
11949
|
+
Type.String({
|
|
11950
|
+
description: 'Completion summary for missionAction="complete" (what was achieved and current state).',
|
|
11951
|
+
maxLength: 8192
|
|
11952
|
+
})
|
|
11953
|
+
),
|
|
11954
|
+
outcome: Type.Optional(
|
|
11955
|
+
StringEnum(MISSION_OUTCOMES, {
|
|
11956
|
+
description: 'Completion outcome for missionAction="complete": "achieved" or "with_residuals" (explicitly acceptable on timeout convergence).'
|
|
11957
|
+
})
|
|
11958
|
+
),
|
|
11959
|
+
residuals: Type.Optional(
|
|
11960
|
+
Type.Array(Type.String({ minLength: 1, maxLength: 1024 }), {
|
|
11961
|
+
description: "Optional list of remaining open items, residuals, or unresolved contradictions recorded when completing with_residuals.",
|
|
11962
|
+
maxItems: 32
|
|
11963
|
+
})
|
|
11964
|
+
)
|
|
10665
11965
|
},
|
|
10666
11966
|
{ additionalProperties: false }
|
|
10667
11967
|
);
|
|
@@ -10673,9 +11973,11 @@ function registerSwarmTools(pi, controller) {
|
|
|
10673
11973
|
promptSnippet: "Start a collaborating Pi session in an external terminal window",
|
|
10674
11974
|
promptGuidelines: [
|
|
10675
11975
|
"Use session_spawn only when the user explicitly asks to open or start another Pi session.",
|
|
11976
|
+
`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
11977
|
"Do not claim the child is ready until session_spawn returns authenticated readiness metadata.",
|
|
10677
11978
|
"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."
|
|
11979
|
+
"Use contextRecycling only with explicit user authorization for bounded automatic worker replacement; the threshold is soft and never interrupts a healthy turn.",
|
|
11980
|
+
'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
11981
|
],
|
|
10680
11982
|
parameters: spawnSchema,
|
|
10681
11983
|
executionMode: "sequential",
|
|
@@ -10714,6 +12016,33 @@ function registerSwarmTools(pi, controller) {
|
|
|
10714
12016
|
parameters: busSchema,
|
|
10715
12017
|
executionMode: "sequential",
|
|
10716
12018
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
12019
|
+
if (params.action === "mission") {
|
|
12020
|
+
assertAbsent(params.targetSessionId, "targetSessionId", "mission");
|
|
12021
|
+
assertAbsent(params.message, "message", "mission");
|
|
12022
|
+
assertAbsent(params.mode, "mode", "mission");
|
|
12023
|
+
assertAbsent(params.replyTo, "replyTo", "mission");
|
|
12024
|
+
assertAbsent(params.taskStatus, "taskStatus", "mission");
|
|
12025
|
+
assertAbsent(params.handoff, "handoff", "mission");
|
|
12026
|
+
assertAbsent(params.branches, "branches", "mission");
|
|
12027
|
+
if (!controller.manageMission) throw new Error("session_bus mission is unavailable");
|
|
12028
|
+
if (!params.missionAction) {
|
|
12029
|
+
throw new Error('session_bus missionAction ("start" | "complete" | "status") is required for action mission');
|
|
12030
|
+
}
|
|
12031
|
+
const result2 = await controller.manageMission(ctx, {
|
|
12032
|
+
missionAction: params.missionAction,
|
|
12033
|
+
...params.firstPrinciples !== void 0 ? { firstPrinciples: params.firstPrinciples } : {},
|
|
12034
|
+
...params.acceptanceCriteria !== void 0 ? { acceptanceCriteria: params.acceptanceCriteria } : {},
|
|
12035
|
+
...params.constraints !== void 0 ? { constraints: params.constraints } : {},
|
|
12036
|
+
...params.estimatedMinutes !== void 0 ? { estimatedMinutes: params.estimatedMinutes } : {},
|
|
12037
|
+
...params.summary !== void 0 ? { summary: params.summary } : {},
|
|
12038
|
+
...params.outcome !== void 0 ? { outcome: params.outcome } : {},
|
|
12039
|
+
...params.residuals !== void 0 ? { residuals: params.residuals } : {}
|
|
12040
|
+
});
|
|
12041
|
+
return {
|
|
12042
|
+
content: [{ type: "text", text: result2.message }],
|
|
12043
|
+
details: result2
|
|
12044
|
+
};
|
|
12045
|
+
}
|
|
10717
12046
|
if (params.action === "catalog") {
|
|
10718
12047
|
assertAbsent(params.targetSessionId, "targetSessionId", "catalog");
|
|
10719
12048
|
assertAbsent(params.message, "message", "catalog");
|
|
@@ -10975,6 +12304,9 @@ function createPiSwarmExtension(dependencies = {}) {
|
|
|
10975
12304
|
pi.on("agent_settled", async (event, ctx) => {
|
|
10976
12305
|
await controller.agentSettled(ctx, event.aborted);
|
|
10977
12306
|
});
|
|
12307
|
+
pi.on("cache_warming_decision", (event, ctx) => {
|
|
12308
|
+
return controller.decideCacheWarming(event, ctx);
|
|
12309
|
+
});
|
|
10978
12310
|
pi.on("session_info_changed", async (event, ctx) => {
|
|
10979
12311
|
await controller.noteSessionInfoChanged(event.name, ctx);
|
|
10980
12312
|
});
|