pi-agent-swarm 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/chunks/{chunk-77JHO3GV.ts → chunk-CV4VP4UE.ts} +9 -1
- package/dist/chunks/{chunk-77JHO3GV.ts.map → chunk-CV4VP4UE.ts.map} +1 -1
- package/dist/chunks/{menu-NLK5I2DA.ts → menu-A2TQAWN6.ts} +2 -2
- package/dist/index.ts +1941 -162
- package/dist/index.ts.map +4 -4
- package/package.json +1 -1
- package/src/cache-warming.ts +147 -0
- package/src/external-runtime.ts +244 -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 +179 -12
- package/src/leader-session-runtime.ts +23 -0
- package/src/ledger.ts +28 -1
- package/src/mission-badge.ts +331 -0
- package/src/mission.ts +281 -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 +254 -1
- package/src/swarm-controller.ts +822 -7
- package/src/tools.ts +103 -1
- /package/dist/chunks/{menu-NLK5I2DA.ts.map → menu-A2TQAWN6.ts.map} +0 -0
package/package.json
CHANGED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { CacheWarmingSettings } from "./settings.js";
|
|
2
|
+
|
|
3
|
+
export interface CacheWarmingModelLike {
|
|
4
|
+
provider?: string;
|
|
5
|
+
id?: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
promptCache?: {
|
|
8
|
+
short?: number;
|
|
9
|
+
long?: number;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface CacheWarmingDecisionInput {
|
|
14
|
+
/** Pi's own default decision ("warm" | "stop"). */
|
|
15
|
+
defaultAction: "warm" | "stop";
|
|
16
|
+
/** Current native model attached to the Pi session. */
|
|
17
|
+
model: CacheWarmingModelLike | undefined;
|
|
18
|
+
/** Whether this session is the swarm lead. */
|
|
19
|
+
isLead: boolean;
|
|
20
|
+
/** Whether an external direct runtime (e.g. /agy on) currently owns the leader loop. */
|
|
21
|
+
externalDirectActive: boolean;
|
|
22
|
+
/** Count of active in-flight workers / pending kickoff replies the lead is waiting on. */
|
|
23
|
+
inFlightWorkerCount: number;
|
|
24
|
+
/** User/built-in cache warming settings. */
|
|
25
|
+
settings: CacheWarmingSettings;
|
|
26
|
+
/** Current epoch timestamp in ms. */
|
|
27
|
+
now: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type CacheModelTier = "local_infinite" | "deepseek_long" | "cloud_short" | "unknown";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Classifies a native model's prompt-cache retention profile.
|
|
34
|
+
* Matches Pi core & famous-anime-cache-countdown semantics:
|
|
35
|
+
* - Loopback / RFC1918 private hosts have process-memory KV cache (no time TTL -> never warm).
|
|
36
|
+
* - DeepSeek cloud cache survives 12h+ -> no short-window keepalive needed.
|
|
37
|
+
* - Models declaring `promptCache.short <= 600` or known short-window cloud providers -> warmable.
|
|
38
|
+
*/
|
|
39
|
+
export function classifyModelCacheTier(model: CacheWarmingModelLike | undefined | null): CacheModelTier {
|
|
40
|
+
if (!model) return "unknown";
|
|
41
|
+
if (isLocalHostedModel(model)) return "local_infinite";
|
|
42
|
+
if (isDeepSeekModel(model)) return "deepseek_long";
|
|
43
|
+
const shortSec = model.promptCache?.short;
|
|
44
|
+
if (typeof shortSec === "number" && shortSec > 0) {
|
|
45
|
+
return shortSec <= 3600 ? "cloud_short" : "deepseek_long";
|
|
46
|
+
}
|
|
47
|
+
const provider = (model.provider ?? "").toLowerCase();
|
|
48
|
+
const id = (model.id ?? "").toLowerCase();
|
|
49
|
+
if (
|
|
50
|
+
provider.includes("anthropic") ||
|
|
51
|
+
provider.includes("kimi") ||
|
|
52
|
+
provider.includes("moonshot") ||
|
|
53
|
+
id.includes("claude") ||
|
|
54
|
+
id.startsWith("k3") ||
|
|
55
|
+
id.includes("kimi")
|
|
56
|
+
) {
|
|
57
|
+
return "cloud_short";
|
|
58
|
+
}
|
|
59
|
+
return "unknown";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function isDeepSeekModel(model: CacheWarmingModelLike | undefined | null): boolean {
|
|
63
|
+
const provider = (model?.provider ?? "").toLowerCase();
|
|
64
|
+
const id = (model?.id ?? "").toLowerCase();
|
|
65
|
+
return provider === "deepseek" || provider.includes("deepseek") || id.startsWith("deepseek");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isLocalHostedModel(model: CacheWarmingModelLike | undefined | null): boolean {
|
|
69
|
+
if (!model?.baseUrl) return false;
|
|
70
|
+
let host: string;
|
|
71
|
+
try {
|
|
72
|
+
host = new URL(model.baseUrl).hostname.toLowerCase();
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
if (host === "localhost" || host.endsWith(".localhost") || host === "::1" || host === "[::1]" || host === "0.0.0.0") {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
const ipv4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/u.exec(host);
|
|
80
|
+
if (!ipv4) return false;
|
|
81
|
+
const a = Number(ipv4[1]);
|
|
82
|
+
const b = Number(ipv4[2]);
|
|
83
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface CacheWarmingEvaluation {
|
|
87
|
+
action: "warm" | "stop";
|
|
88
|
+
tier: CacheModelTier;
|
|
89
|
+
reason: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Stateful bounded policy for Pi's `cache_warming_decision` hook.
|
|
94
|
+
* Extends native Leader prompt-cache lifetime while waiting on active workers,
|
|
95
|
+
* while strictly skipping local/DeepSeek/external-direct sessions and enforcing
|
|
96
|
+
* hard wait-duration and refresh-count caps.
|
|
97
|
+
*/
|
|
98
|
+
export class SwarmCacheWarmingPolicy {
|
|
99
|
+
private waitStartedAt: number | undefined;
|
|
100
|
+
private refreshesInWait = 0;
|
|
101
|
+
|
|
102
|
+
/** Reset wait window counters when a real native turn starts or session resets. */
|
|
103
|
+
resetWaitWindow(): void {
|
|
104
|
+
this.waitStartedAt = undefined;
|
|
105
|
+
this.refreshesInWait = 0;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
evaluate(input: CacheWarmingDecisionInput): CacheWarmingEvaluation {
|
|
109
|
+
const tier = classifyModelCacheTier(input.model);
|
|
110
|
+
|
|
111
|
+
if (input.externalDirectActive) {
|
|
112
|
+
this.resetWaitWindow();
|
|
113
|
+
return { action: "stop", tier, reason: "external_direct_runtime_active" };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (tier === "local_infinite") {
|
|
117
|
+
this.resetWaitWindow();
|
|
118
|
+
return { action: "stop", tier, reason: "local_model_infinite_kv" };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (tier === "deepseek_long") {
|
|
122
|
+
this.resetWaitWindow();
|
|
123
|
+
return { action: "stop", tier, reason: "deepseek_long_retention" };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!input.settings.enabled) {
|
|
127
|
+
return { action: input.defaultAction, tier, reason: "swarm_cache_warming_disabled" };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (!input.isLead || input.inFlightWorkerCount <= 0) {
|
|
131
|
+
this.resetWaitWindow();
|
|
132
|
+
return { action: input.defaultAction, tier, reason: "no_inflight_workers" };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
this.waitStartedAt ??= input.now;
|
|
136
|
+
const elapsedMs = Math.max(0, input.now - this.waitStartedAt);
|
|
137
|
+
if (elapsedMs >= input.settings.maxWaitDurationMs) {
|
|
138
|
+
return { action: "stop", tier, reason: "wait_duration_cap_reached" };
|
|
139
|
+
}
|
|
140
|
+
if (this.refreshesInWait >= input.settings.maxRefreshesPerWait) {
|
|
141
|
+
return { action: "stop", tier, reason: "refresh_count_cap_reached" };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
this.refreshesInWait += 1;
|
|
145
|
+
return { action: "warm", tier, reason: "lead_waiting_for_active_workers" };
|
|
146
|
+
}
|
|
147
|
+
}
|
package/src/external-runtime.ts
CHANGED
|
@@ -78,8 +78,96 @@ export type ExternalRuntimeEventPayload =
|
|
|
78
78
|
type: "shutdown";
|
|
79
79
|
runtimeId: string;
|
|
80
80
|
sessionId: string;
|
|
81
|
+
}
|
|
82
|
+
| {
|
|
83
|
+
type: "direct_state";
|
|
84
|
+
runtimeId: string;
|
|
85
|
+
sessionId?: string;
|
|
86
|
+
active: boolean;
|
|
87
|
+
model?: string;
|
|
88
|
+
thoughtLevel?: string;
|
|
89
|
+
mode?: string;
|
|
90
|
+
busy?: boolean;
|
|
91
|
+
pendingCount?: number;
|
|
92
|
+
}
|
|
93
|
+
| {
|
|
94
|
+
type: "direct_deliver";
|
|
95
|
+
runtimeId: string;
|
|
96
|
+
sessionId: string;
|
|
97
|
+
prompt: string;
|
|
98
|
+
source: "swarm_message" | "leader_advisory" | "leader_kickoff";
|
|
99
|
+
messageId?: string;
|
|
100
|
+
fromSessionId?: string;
|
|
101
|
+
replaceTag?: string;
|
|
102
|
+
}
|
|
103
|
+
| {
|
|
104
|
+
type: "direct_clear_queue";
|
|
105
|
+
runtimeId: string;
|
|
106
|
+
sessionId: string;
|
|
107
|
+
replaceTag?: string;
|
|
108
|
+
}
|
|
109
|
+
| {
|
|
110
|
+
type: "direct_restore";
|
|
111
|
+
requestId: string;
|
|
112
|
+
runtimeId: string;
|
|
113
|
+
sessionId: string;
|
|
114
|
+
model?: string;
|
|
115
|
+
thoughtLevel?: string;
|
|
116
|
+
mode?: string;
|
|
117
|
+
handoffPrompt: string;
|
|
118
|
+
}
|
|
119
|
+
| {
|
|
120
|
+
type: "context_usage";
|
|
121
|
+
runtimeId: string;
|
|
122
|
+
sessionId?: string;
|
|
123
|
+
tokens: number | null;
|
|
124
|
+
contextWindow: number;
|
|
125
|
+
completedTurns: number;
|
|
126
|
+
compactionCount?: number;
|
|
127
|
+
idleMs?: number;
|
|
128
|
+
model?: string;
|
|
129
|
+
usage?: SwarmLedgerUsage & {
|
|
130
|
+
cachedReadTokens?: number;
|
|
131
|
+
cachedWriteTokens?: number;
|
|
132
|
+
thoughtTokens?: number;
|
|
133
|
+
};
|
|
134
|
+
settled?: boolean;
|
|
135
|
+
aborted?: boolean;
|
|
136
|
+
pendingCount?: number;
|
|
81
137
|
};
|
|
82
138
|
|
|
139
|
+
export interface ExternalDirectState {
|
|
140
|
+
runtimeId: string;
|
|
141
|
+
sessionId?: string;
|
|
142
|
+
active: boolean;
|
|
143
|
+
model?: string;
|
|
144
|
+
thoughtLevel?: string;
|
|
145
|
+
mode?: string;
|
|
146
|
+
busy?: boolean;
|
|
147
|
+
pendingCount?: number;
|
|
148
|
+
updatedAt: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface ExternalContextUsageReport {
|
|
152
|
+
runtimeId: string;
|
|
153
|
+
sessionId?: string;
|
|
154
|
+
tokens: number | null;
|
|
155
|
+
contextWindow: number;
|
|
156
|
+
completedTurns: number;
|
|
157
|
+
compactionCount: number;
|
|
158
|
+
idleMs?: number;
|
|
159
|
+
model?: string;
|
|
160
|
+
usage?: SwarmLedgerUsage & {
|
|
161
|
+
cachedReadTokens?: number;
|
|
162
|
+
cachedWriteTokens?: number;
|
|
163
|
+
thoughtTokens?: number;
|
|
164
|
+
};
|
|
165
|
+
settled: boolean;
|
|
166
|
+
aborted: boolean;
|
|
167
|
+
pendingCount?: number;
|
|
168
|
+
updatedAt: number;
|
|
169
|
+
}
|
|
170
|
+
|
|
83
171
|
export interface ExternalTurnResult {
|
|
84
172
|
ok: boolean;
|
|
85
173
|
text: string;
|
|
@@ -106,6 +194,8 @@ export class ExternalRuntimeHost {
|
|
|
106
194
|
private readonly pi: ExtensionAPI,
|
|
107
195
|
private readonly handlers: {
|
|
108
196
|
onSnapshot: (snapshot: ExternalRuntimeSnapshot) => void;
|
|
197
|
+
onDirectState?: (state: ExternalDirectState) => void;
|
|
198
|
+
onContextUsage?: (report: ExternalContextUsageReport) => void;
|
|
109
199
|
now: () => number;
|
|
110
200
|
randomId: (prefix: string) => string;
|
|
111
201
|
},
|
|
@@ -271,6 +361,87 @@ export class ExternalRuntimeHost {
|
|
|
271
361
|
});
|
|
272
362
|
}
|
|
273
363
|
|
|
364
|
+
deliverToDirect(params: {
|
|
365
|
+
runtimeId: string;
|
|
366
|
+
sessionId: string;
|
|
367
|
+
prompt: string;
|
|
368
|
+
source: "swarm_message" | "leader_advisory" | "leader_kickoff";
|
|
369
|
+
messageId?: string;
|
|
370
|
+
fromSessionId?: string;
|
|
371
|
+
replaceTag?: string;
|
|
372
|
+
}): void {
|
|
373
|
+
this.emit({
|
|
374
|
+
type: "direct_deliver",
|
|
375
|
+
runtimeId: params.runtimeId,
|
|
376
|
+
sessionId: params.sessionId,
|
|
377
|
+
prompt: params.prompt,
|
|
378
|
+
source: params.source,
|
|
379
|
+
...(params.messageId ? { messageId: params.messageId } : {}),
|
|
380
|
+
...(params.fromSessionId ? { fromSessionId: params.fromSessionId } : {}),
|
|
381
|
+
...(params.replaceTag ? { replaceTag: params.replaceTag } : {}),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
clearDirectQueue(params: { runtimeId: string; sessionId: string; replaceTag?: string }): void {
|
|
386
|
+
this.emit({
|
|
387
|
+
type: "direct_clear_queue",
|
|
388
|
+
runtimeId: params.runtimeId,
|
|
389
|
+
sessionId: params.sessionId,
|
|
390
|
+
...(params.replaceTag ? { replaceTag: params.replaceTag } : {}),
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
restoreDirect(
|
|
395
|
+
params: {
|
|
396
|
+
runtimeId: string;
|
|
397
|
+
sessionId: string;
|
|
398
|
+
model?: string;
|
|
399
|
+
thoughtLevel?: string;
|
|
400
|
+
mode?: string;
|
|
401
|
+
handoffPrompt: string;
|
|
402
|
+
timeoutMs?: number;
|
|
403
|
+
},
|
|
404
|
+
signal?: AbortSignal,
|
|
405
|
+
): Promise<{ actualModel?: string }> {
|
|
406
|
+
const requestId = this.handlers.randomId("extrestore");
|
|
407
|
+
const timeoutMs = params.timeoutMs ?? 60_000;
|
|
408
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
409
|
+
if (signal?.aborted) {
|
|
410
|
+
rejectPromise(new Error("External runtime direct restore aborted"));
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const waiter: PendingWaiter<{ actualModel?: string }> = {
|
|
414
|
+
resolve: resolvePromise,
|
|
415
|
+
reject: rejectPromise,
|
|
416
|
+
};
|
|
417
|
+
waiter.timer = setTimeout(() => {
|
|
418
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
419
|
+
this.clearWaiter(waiter);
|
|
420
|
+
rejectPromise(new Error(`External runtime "${params.runtimeId}" did not restore within ${timeoutMs}ms`));
|
|
421
|
+
}, timeoutMs);
|
|
422
|
+
if (signal) {
|
|
423
|
+
const onAbort = () => {
|
|
424
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
425
|
+
this.clearWaiter(waiter);
|
|
426
|
+
rejectPromise(new Error("External runtime direct restore aborted"));
|
|
427
|
+
};
|
|
428
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
429
|
+
waiter.cleanupAbort = () => signal.removeEventListener("abort", onAbort);
|
|
430
|
+
}
|
|
431
|
+
this.readyWaiters.set(requestId, waiter);
|
|
432
|
+
this.emit({
|
|
433
|
+
type: "direct_restore",
|
|
434
|
+
requestId,
|
|
435
|
+
runtimeId: params.runtimeId,
|
|
436
|
+
sessionId: params.sessionId,
|
|
437
|
+
...(params.model ? { model: params.model } : {}),
|
|
438
|
+
...(params.thoughtLevel ? { thoughtLevel: params.thoughtLevel } : {}),
|
|
439
|
+
...(params.mode ? { mode: params.mode } : {}),
|
|
440
|
+
handoffPrompt: params.handoffPrompt,
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
274
445
|
private emit(payload: ExternalRuntimeEventPayload): void {
|
|
275
446
|
if (typeof this.pi.events?.emit === "function") {
|
|
276
447
|
this.pi.events.emit(EXTERNAL_RUNTIME_EVENT, payload);
|
|
@@ -308,6 +479,79 @@ export class ExternalRuntimeHost {
|
|
|
308
479
|
return;
|
|
309
480
|
}
|
|
310
481
|
|
|
482
|
+
if (type === "direct_state" && typeof msg.runtimeId === "string" && typeof msg.active === "boolean") {
|
|
483
|
+
this.handlers.onDirectState?.({
|
|
484
|
+
runtimeId: msg.runtimeId,
|
|
485
|
+
...(typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {}),
|
|
486
|
+
active: msg.active,
|
|
487
|
+
...(typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {}),
|
|
488
|
+
...(typeof msg.thoughtLevel === "string" && msg.thoughtLevel.length > 0
|
|
489
|
+
? { thoughtLevel: msg.thoughtLevel }
|
|
490
|
+
: {}),
|
|
491
|
+
...(typeof msg.mode === "string" && msg.mode.length > 0 ? { mode: msg.mode } : {}),
|
|
492
|
+
...(typeof msg.busy === "boolean" ? { busy: msg.busy } : {}),
|
|
493
|
+
...(typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0
|
|
494
|
+
? { pendingCount: msg.pendingCount }
|
|
495
|
+
: {}),
|
|
496
|
+
updatedAt: this.handlers.now(),
|
|
497
|
+
});
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (type === "context_usage" && typeof msg.runtimeId === "string") {
|
|
502
|
+
const contextWindow =
|
|
503
|
+
typeof msg.contextWindow === "number" && Number.isFinite(msg.contextWindow) && msg.contextWindow > 0
|
|
504
|
+
? msg.contextWindow
|
|
505
|
+
: 1_048_576;
|
|
506
|
+
const tokens =
|
|
507
|
+
typeof msg.tokens === "number" && Number.isFinite(msg.tokens) && msg.tokens >= 0 ? msg.tokens : null;
|
|
508
|
+
const completedTurns =
|
|
509
|
+
typeof msg.completedTurns === "number" && Number.isInteger(msg.completedTurns) && msg.completedTurns >= 0
|
|
510
|
+
? msg.completedTurns
|
|
511
|
+
: 0;
|
|
512
|
+
const compactionCount =
|
|
513
|
+
typeof msg.compactionCount === "number" && Number.isInteger(msg.compactionCount) && msg.compactionCount >= 0
|
|
514
|
+
? msg.compactionCount
|
|
515
|
+
: 0;
|
|
516
|
+
const rawUsage =
|
|
517
|
+
msg.usage && typeof msg.usage === "object" && !Array.isArray(msg.usage)
|
|
518
|
+
? (msg.usage as Record<string, unknown>)
|
|
519
|
+
: undefined;
|
|
520
|
+
const usage = rawUsage
|
|
521
|
+
? {
|
|
522
|
+
...(typeof rawUsage.inputTokens === "number" ? { inputTokens: rawUsage.inputTokens } : {}),
|
|
523
|
+
...(typeof rawUsage.outputTokens === "number" ? { outputTokens: rawUsage.outputTokens } : {}),
|
|
524
|
+
...(typeof rawUsage.totalTokens === "number" ? { totalTokens: rawUsage.totalTokens } : {}),
|
|
525
|
+
...(typeof rawUsage.costUsd === "number" ? { costUsd: rawUsage.costUsd } : {}),
|
|
526
|
+
...(typeof rawUsage.cachedReadTokens === "number" ? { cachedReadTokens: rawUsage.cachedReadTokens } : {}),
|
|
527
|
+
...(typeof rawUsage.cachedWriteTokens === "number"
|
|
528
|
+
? { cachedWriteTokens: rawUsage.cachedWriteTokens }
|
|
529
|
+
: {}),
|
|
530
|
+
...(typeof rawUsage.thoughtTokens === "number" ? { thoughtTokens: rawUsage.thoughtTokens } : {}),
|
|
531
|
+
}
|
|
532
|
+
: undefined;
|
|
533
|
+
this.handlers.onContextUsage?.({
|
|
534
|
+
runtimeId: msg.runtimeId,
|
|
535
|
+
...(typeof msg.sessionId === "string" ? { sessionId: msg.sessionId } : {}),
|
|
536
|
+
tokens,
|
|
537
|
+
contextWindow,
|
|
538
|
+
completedTurns,
|
|
539
|
+
compactionCount,
|
|
540
|
+
...(typeof msg.idleMs === "number" && Number.isFinite(msg.idleMs) && msg.idleMs >= 0
|
|
541
|
+
? { idleMs: msg.idleMs }
|
|
542
|
+
: {}),
|
|
543
|
+
...(typeof msg.model === "string" && msg.model.length > 0 ? { model: msg.model } : {}),
|
|
544
|
+
...(usage ? { usage } : {}),
|
|
545
|
+
settled: msg.settled === true,
|
|
546
|
+
aborted: msg.aborted === true,
|
|
547
|
+
...(typeof msg.pendingCount === "number" && Number.isInteger(msg.pendingCount) && msg.pendingCount >= 0
|
|
548
|
+
? { pendingCount: msg.pendingCount }
|
|
549
|
+
: {}),
|
|
550
|
+
updatedAt: this.handlers.now(),
|
|
551
|
+
});
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
|
|
311
555
|
if (type === "ready" && typeof msg.requestId === "string") {
|
|
312
556
|
const waiter = this.readyWaiters.get(msg.requestId);
|
|
313
557
|
if (!waiter) return;
|
package/src/lead-mcp-bridge.ts
CHANGED
|
@@ -75,6 +75,19 @@ export interface LeadMcpBridgeActions {
|
|
|
75
75
|
},
|
|
76
76
|
) => Promise<unknown>;
|
|
77
77
|
shutdownPeer: (ctx: ExtensionContext, targetSessionId: string) => Promise<unknown>;
|
|
78
|
+
mission?: (
|
|
79
|
+
ctx: ExtensionContext,
|
|
80
|
+
input: {
|
|
81
|
+
missionAction: "start" | "complete" | "status";
|
|
82
|
+
firstPrinciples?: string;
|
|
83
|
+
acceptanceCriteria?: string;
|
|
84
|
+
constraints?: string;
|
|
85
|
+
estimatedMinutes?: number;
|
|
86
|
+
summary?: string;
|
|
87
|
+
outcome?: "achieved" | "with_residuals";
|
|
88
|
+
residuals?: string[];
|
|
89
|
+
},
|
|
90
|
+
) => Promise<unknown>;
|
|
78
91
|
publishLeaderHandoff: (ctx: ExtensionContext, handoff: LeaderHandoffContent) => Promise<unknown>;
|
|
79
92
|
}
|
|
80
93
|
|
|
@@ -130,16 +143,25 @@ const LEAD_MCP_TOOLS = [
|
|
|
130
143
|
},
|
|
131
144
|
{
|
|
132
145
|
name: "swarm_bus",
|
|
133
|
-
description:
|
|
146
|
+
description:
|
|
147
|
+
'List live swarm sessions, manage the mandatory first-principles mission countdown (action="mission"), send a notify/request/reply message, or request graceful peer shutdown.',
|
|
134
148
|
inputSchema: {
|
|
135
149
|
type: "object",
|
|
136
150
|
properties: {
|
|
137
|
-
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog"] },
|
|
151
|
+
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog", "mission"] },
|
|
138
152
|
targetSessionId: { type: "string" },
|
|
139
153
|
message: { type: "string" },
|
|
140
154
|
mode: { type: "string", enum: ["notify", "request"] },
|
|
141
155
|
replyTo: { type: "string" },
|
|
142
156
|
taskStatus: { type: "string", enum: ["working", "completed"] },
|
|
157
|
+
missionAction: { type: "string", enum: ["start", "complete", "status"] },
|
|
158
|
+
firstPrinciples: { type: "string" },
|
|
159
|
+
acceptanceCriteria: { type: "string" },
|
|
160
|
+
constraints: { type: "string" },
|
|
161
|
+
estimatedMinutes: { type: "number" },
|
|
162
|
+
summary: { type: "string" },
|
|
163
|
+
outcome: { type: "string", enum: ["achieved", "with_residuals"] },
|
|
164
|
+
residuals: { type: "array", items: { type: "string" } },
|
|
143
165
|
},
|
|
144
166
|
required: ["action"],
|
|
145
167
|
additionalProperties: false,
|
|
@@ -481,6 +503,25 @@ export class LeadMcpBridge {
|
|
|
481
503
|
const action = typeof args.action === "string" ? args.action : "";
|
|
482
504
|
if (action === "catalog") return this.actions.catalog(ctx);
|
|
483
505
|
if (action === "list") return this.actions.snapshot();
|
|
506
|
+
if (action === "mission") {
|
|
507
|
+
if (!this.actions.mission) throw new Error("swarm_bus mission is unavailable");
|
|
508
|
+
const missionAction = args.missionAction;
|
|
509
|
+
if (missionAction !== "start" && missionAction !== "complete" && missionAction !== "status") {
|
|
510
|
+
throw new Error('swarm_bus mission requires missionAction ("start" | "complete" | "status")');
|
|
511
|
+
}
|
|
512
|
+
return this.actions.mission(ctx, {
|
|
513
|
+
missionAction,
|
|
514
|
+
...(typeof args.firstPrinciples === "string" ? { firstPrinciples: args.firstPrinciples } : {}),
|
|
515
|
+
...(typeof args.acceptanceCriteria === "string" ? { acceptanceCriteria: args.acceptanceCriteria } : {}),
|
|
516
|
+
...(typeof args.constraints === "string" ? { constraints: args.constraints } : {}),
|
|
517
|
+
...(typeof args.estimatedMinutes === "number" ? { estimatedMinutes: args.estimatedMinutes } : {}),
|
|
518
|
+
...(typeof args.summary === "string" ? { summary: args.summary } : {}),
|
|
519
|
+
...(args.outcome === "achieved" || args.outcome === "with_residuals" ? { outcome: args.outcome } : {}),
|
|
520
|
+
...(Array.isArray(args.residuals)
|
|
521
|
+
? { residuals: args.residuals.filter((r): r is string => typeof r === "string") }
|
|
522
|
+
: {}),
|
|
523
|
+
});
|
|
524
|
+
}
|
|
484
525
|
if (action === "shutdown") {
|
|
485
526
|
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
486
527
|
throw new Error("swarm_bus shutdown requires targetSessionId");
|
|
@@ -19,6 +19,12 @@ export interface LeaderHandoffBridgeInput {
|
|
|
19
19
|
color?: string;
|
|
20
20
|
model?: string;
|
|
21
21
|
thinkingLevel?: string;
|
|
22
|
+
externalRuntime?: {
|
|
23
|
+
runtimeId: string;
|
|
24
|
+
model?: string;
|
|
25
|
+
thoughtLevel?: string;
|
|
26
|
+
mode?: string;
|
|
27
|
+
};
|
|
22
28
|
invite?: string;
|
|
23
29
|
groupDirectory?: string;
|
|
24
30
|
acceptsRequests: boolean;
|
package/src/leader-recycling.ts
CHANGED
|
@@ -33,6 +33,7 @@ export interface LeaderRecyclingPolicy {
|
|
|
33
33
|
softContextPercent: number;
|
|
34
34
|
softContextTokens: number;
|
|
35
35
|
highWaterPercent: number;
|
|
36
|
+
highWaterTokens?: number;
|
|
36
37
|
maxReplacements: number;
|
|
37
38
|
}
|
|
38
39
|
|
|
@@ -138,12 +139,13 @@ const LEADER_LINEAGE_TRANSITIONS: Record<LeaderLineageState, readonly LeaderLine
|
|
|
138
139
|
|
|
139
140
|
export function normalizeLeaderRecyclingPolicy(input: unknown = {}): LeaderRecyclingPolicy {
|
|
140
141
|
const value = record(input, "leader recycling policy");
|
|
141
|
-
const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "maxReplacements"];
|
|
142
|
+
const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "highWaterTokens", "maxReplacements"];
|
|
142
143
|
const unknown = Object.keys(value).find((key) => !allowed.includes(key));
|
|
143
144
|
if (unknown) throw new Error(`Pi Agent Swarm leader recycling policy has unknown field ${unknown}`);
|
|
144
145
|
const softContextPercent = value.softContextPercent ?? DEFAULT_LEADER_SOFT_CONTEXT_PERCENT;
|
|
145
146
|
const softContextTokens = value.softContextTokens ?? DEFAULT_LEADER_SOFT_CONTEXT_TOKENS;
|
|
146
147
|
const highWaterPercent = value.highWaterPercent ?? DEFAULT_LEADER_HIGH_WATER_PERCENT;
|
|
148
|
+
const highWaterTokens = value.highWaterTokens;
|
|
147
149
|
const maxReplacements = value.maxReplacements ?? DEFAULT_LEADER_RECYCLING_POLICY.maxReplacements;
|
|
148
150
|
for (const [key, percentage] of [
|
|
149
151
|
["softContextPercent", softContextPercent],
|
|
@@ -156,6 +158,12 @@ export function normalizeLeaderRecyclingPolicy(input: unknown = {}): LeaderRecyc
|
|
|
156
158
|
if (typeof softContextTokens !== "number" || !Number.isFinite(softContextTokens) || softContextTokens <= 0) {
|
|
157
159
|
throw new Error("Pi Agent Swarm leader recycling softContextTokens must be greater than 0");
|
|
158
160
|
}
|
|
161
|
+
if (
|
|
162
|
+
highWaterTokens !== undefined &&
|
|
163
|
+
(typeof highWaterTokens !== "number" || !Number.isFinite(highWaterTokens) || highWaterTokens <= 0)
|
|
164
|
+
) {
|
|
165
|
+
throw new Error("Pi Agent Swarm leader recycling highWaterTokens must be greater than 0");
|
|
166
|
+
}
|
|
159
167
|
if (
|
|
160
168
|
!Number.isInteger(maxReplacements) ||
|
|
161
169
|
(maxReplacements as number) < 0 ||
|
|
@@ -167,6 +175,7 @@ export function normalizeLeaderRecyclingPolicy(input: unknown = {}): LeaderRecyc
|
|
|
167
175
|
softContextPercent: softContextPercent as number,
|
|
168
176
|
softContextTokens,
|
|
169
177
|
highWaterPercent: highWaterPercent as number,
|
|
178
|
+
...(highWaterTokens !== undefined ? { highWaterTokens } : {}),
|
|
170
179
|
maxReplacements: maxReplacements as number,
|
|
171
180
|
};
|
|
172
181
|
}
|
|
@@ -185,7 +194,8 @@ export function shouldAnalyzeLeaderBranch(
|
|
|
185
194
|
if (
|
|
186
195
|
percent >= policy.softContextPercent ||
|
|
187
196
|
percent >= policy.highWaterPercent ||
|
|
188
|
-
tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP)
|
|
197
|
+
tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP) ||
|
|
198
|
+
(policy.highWaterTokens !== undefined && tokens >= Math.min(policy.highWaterTokens, window * 0.85))
|
|
189
199
|
) {
|
|
190
200
|
return true;
|
|
191
201
|
}
|
|
@@ -328,7 +338,10 @@ export function evaluateLeaderRecyclingGate(
|
|
|
328
338
|
}
|
|
329
339
|
if (snapshot.compactionCount >= 1) signals.push("compaction_detected");
|
|
330
340
|
|
|
331
|
-
const highWater =
|
|
341
|
+
const highWater =
|
|
342
|
+
known !== undefined &&
|
|
343
|
+
(known.percent >= policy.highWaterPercent ||
|
|
344
|
+
(policy.highWaterTokens !== undefined && known.tokens >= Math.min(policy.highWaterTokens, known.window * 0.85)));
|
|
332
345
|
const reason = [...signals];
|
|
333
346
|
if (highWater) reason.push("high_water_context");
|
|
334
347
|
if (known === undefined) reason.push("context_tokens_unknown");
|