pi-agent-swarm 0.3.0 → 0.5.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 +44 -6
- package/dist/chunks/{menu-RH6GY6U4.ts → menu-NLK5I2DA.ts} +15 -2
- package/dist/chunks/menu-NLK5I2DA.ts.map +7 -0
- package/dist/index.ts +7755 -924
- package/dist/index.ts.map +4 -4
- package/package.json +4 -4
- package/src/auto-name.ts +137 -28
- package/src/budget.ts +268 -0
- package/src/context-recycling.ts +712 -0
- package/src/external-runtime.ts +374 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +115 -0
- package/src/lead-mcp-bridge.ts +516 -0
- package/src/leader-handoff-bridge.ts +155 -0
- package/src/leader-recycling.ts +752 -0
- package/src/leader-runtime.ts +1098 -0
- package/src/leader-session-runtime.ts +71 -0
- package/src/ledger.ts +351 -0
- package/src/menu.ts +16 -2
- package/src/model-catalog.ts +213 -0
- package/src/org.ts +242 -0
- package/src/pi-agent-swarm.ts +55 -2
- package/src/profile-probe.ts +143 -0
- package/src/profiles.ts +621 -0
- package/src/protocol.ts +14 -3
- package/src/reload-handoff.ts +3 -0
- package/src/resource-lease.ts +250 -0
- package/src/reviewer.ts +191 -0
- package/src/settings.ts +335 -10
- package/src/swarm-controller.ts +2207 -89
- package/src/tools.ts +244 -7
- package/src/transport.ts +17 -0
- package/src/worktree.ts +86 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +0 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-agent-swarm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Window-manager-native agent swarm for the Pi Coding Agent — every agent runs as a real terminal window under a tiling window manager.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -43,9 +43,9 @@
|
|
|
43
43
|
"typebox": "*"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@earendil-works/pi-ai": "1.0
|
|
47
|
-
"@earendil-works/pi-coding-agent": "1.0
|
|
48
|
-
"@earendil-works/pi-tui": "1.0
|
|
46
|
+
"@earendil-works/pi-ai": "1.4.0",
|
|
47
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
48
|
+
"@earendil-works/pi-tui": "1.4.0",
|
|
49
49
|
"@types/node": "26.6.4",
|
|
50
50
|
"esbuild": "0.28.2",
|
|
51
51
|
"typebox": "1.3.34",
|
package/src/auto-name.ts
CHANGED
|
@@ -13,15 +13,46 @@ export const AUTO_NAME_MAX_MESSAGE_CHARS = 500;
|
|
|
13
13
|
export const AUTO_NAME_MAX_CONTEXT_CHARS = 2_000;
|
|
14
14
|
/** Wall-clock budget for the one-shot title completion. */
|
|
15
15
|
export const AUTO_NAME_TIMEOUT_MS = 120_000;
|
|
16
|
+
/** Output token cap for non-reasoning models to keep title completions compact and skip proxy tool injection. */
|
|
17
|
+
export const AUTO_NAME_NON_REASONING_MAX_TOKENS = 128;
|
|
16
18
|
|
|
17
19
|
/** Maximum title-completion attempts per session before auto-naming gives up. */
|
|
18
20
|
export const AUTO_NAME_MAX_ATTEMPTS = 3;
|
|
19
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Documented, versioned, extension-neutral event channel on `pi.events` for
|
|
24
|
+
* extensions that drive an external agent turn without emitting Pi `turn_end`.
|
|
25
|
+
*/
|
|
26
|
+
export const AUTO_NAME_EXTERNAL_TURN_EVENT = "pi-agent-swarm:external-turn:v1";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Minimum accumulated user characters needed for a completed external agent
|
|
30
|
+
* run (`completedRun: true`) to trigger auto-naming before the 3-turn gate.
|
|
31
|
+
*/
|
|
32
|
+
export const AUTO_NAME_EXTERNAL_MIN_CHARS = 20;
|
|
33
|
+
|
|
34
|
+
export interface ExternalTurnEventV1 {
|
|
35
|
+
userText: string;
|
|
36
|
+
completedRun: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** System instruction that suppresses tool calls and enforces structured title tags. */
|
|
40
|
+
export const AUTO_NAME_SYSTEM_PROMPT = [
|
|
41
|
+
"You generate short session titles from user messages.",
|
|
42
|
+
"Do not call any tools, do not inspect context or status, and do not explain your answer.",
|
|
43
|
+
"Respond with only <title>SHORT TITLE</title>.",
|
|
44
|
+
].join("\n");
|
|
45
|
+
|
|
20
46
|
// Matches exactly what sessionStart generates: `MANAGER-` plus the first 8
|
|
21
47
|
// characters of the session id. Session ids are not guaranteed to be hex (UUIDs
|
|
22
48
|
// can put a hyphen inside the first 8 characters), so accept any non-space run.
|
|
23
49
|
const DEFAULT_MANAGER_NAME_PATTERN = /^MANAGER-\S{8}$/u;
|
|
24
50
|
const AUTO_NAME_MODEL_PATTERN = /^[^\s/]+\/[^\s/]+$/u;
|
|
51
|
+
const TITLE_TAG_PATTERN = /<title\b[^>]*>([\s\S]*?)<\/title>/giu;
|
|
52
|
+
const PAIRED_XML_BLOCK_PATTERN = /<([a-z][a-z0-9_-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>/giu;
|
|
53
|
+
const BARE_XML_TAG_LINE_PATTERN = /^<\/?[a-z][a-z0-9_-]*(?:\s[^>]*)?\/?>$/iu;
|
|
54
|
+
const PROXY_STATUS_LINE_PATTERN = /^(?:(?:[\p{So}\p{Sk}\p{Cf}]|\ufe0f|\u200d)+\s*)\[[^\]]+\]/u;
|
|
55
|
+
const ACP_MARKER_PATTERN = /\[ACP\]/iu;
|
|
25
56
|
|
|
26
57
|
/** The default name assigned to human-started sessions before auto-naming kicks in. */
|
|
27
58
|
export function isDefaultManagerName(name: string | undefined): boolean {
|
|
@@ -33,30 +64,56 @@ export function isAutoNameModel(value: string): boolean {
|
|
|
33
64
|
return AUTO_NAME_MODEL_PATTERN.test(value);
|
|
34
65
|
}
|
|
35
66
|
|
|
67
|
+
/** Parse and sanitize an untrusted `pi-agent-swarm:external-turn:v1` event payload. */
|
|
68
|
+
export function parseExternalTurnEvent(payload: unknown): ExternalTurnEventV1 | undefined {
|
|
69
|
+
if (!isRecord(payload) || typeof payload.userText !== "string") return undefined;
|
|
70
|
+
const text = safeTerminalLine(payload.userText);
|
|
71
|
+
if (!text) return undefined;
|
|
72
|
+
const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
|
|
73
|
+
return {
|
|
74
|
+
userText: clipped,
|
|
75
|
+
completedRun: payload.completedRun === true,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
36
79
|
/**
|
|
37
|
-
* Turn raw model output into a `MAN-<title>` session name.
|
|
38
|
-
*
|
|
39
|
-
*
|
|
80
|
+
* Turn raw model output into a `MAN-<title>` session name. Prefers the last
|
|
81
|
+
* `<title>...</title>` element so proxy-injected status preambles cannot
|
|
82
|
+
* corrupt the name; falls back to stripping paired XML blocks and proxy status
|
|
83
|
+
* noise and keeping the first usable line. Truncates to
|
|
84
|
+
* AUTO_NAME_MAX_TITLE_CHARS code points and returns undefined when nothing
|
|
40
85
|
* usable remains. 24 CJK characters stay well under the 200-byte name budget.
|
|
41
86
|
*/
|
|
42
87
|
export function toAutoName(raw: string | undefined): string | undefined {
|
|
43
88
|
if (!raw) return undefined;
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
.trim();
|
|
48
|
-
if (!line) return undefined;
|
|
49
|
-
const title = [...line].slice(0, AUTO_NAME_MAX_TITLE_CHARS).join("");
|
|
89
|
+
const candidate = extractTaggedTitle(raw) ?? extractFallbackTitle(raw);
|
|
90
|
+
if (!candidate) return undefined;
|
|
91
|
+
const title = [...candidate].slice(0, AUTO_NAME_MAX_TITLE_CHARS).join("");
|
|
50
92
|
return `${AUTO_NAME_PREFIX}${title}`;
|
|
51
93
|
}
|
|
52
94
|
|
|
53
95
|
/**
|
|
54
96
|
* Collect the first AUTO_NAME_TURN_THRESHOLD user messages from the current
|
|
55
|
-
* branch
|
|
97
|
+
* branch plus any buffered extension-neutral external-turn messages, each
|
|
98
|
+
* clipped to AUTO_NAME_MAX_MESSAGE_CHARS and capped in total.
|
|
56
99
|
*/
|
|
57
|
-
export function collectAutoNameMessages(ctx: ExtensionContext): string[] {
|
|
100
|
+
export function collectAutoNameMessages(ctx: ExtensionContext, externalMessages: readonly string[] = []): string[] {
|
|
58
101
|
const messages: string[] = [];
|
|
102
|
+
const seen = new Set<string>();
|
|
59
103
|
let total = 0;
|
|
104
|
+
|
|
105
|
+
const pushMessage = (rawText: string): boolean => {
|
|
106
|
+
if (messages.length >= AUTO_NAME_TURN_THRESHOLD || total >= AUTO_NAME_MAX_CONTEXT_CHARS) return false;
|
|
107
|
+
const text = safeTerminalLine(rawText);
|
|
108
|
+
if (!text) return true;
|
|
109
|
+
const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
|
|
110
|
+
if (seen.has(clipped)) return true;
|
|
111
|
+
seen.add(clipped);
|
|
112
|
+
messages.push(clipped);
|
|
113
|
+
total += clipped.length;
|
|
114
|
+
return true;
|
|
115
|
+
};
|
|
116
|
+
|
|
60
117
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
61
118
|
if (messages.length >= AUTO_NAME_TURN_THRESHOLD || total >= AUTO_NAME_MAX_CONTEXT_CHARS) break;
|
|
62
119
|
if (entry.type !== "message") continue;
|
|
@@ -64,25 +121,27 @@ export function collectAutoNameMessages(ctx: ExtensionContext): string[] {
|
|
|
64
121
|
if (!isRecord(message) || message.role !== "user") continue;
|
|
65
122
|
const content = (message as { content?: unknown }).content;
|
|
66
123
|
if (typeof content !== "string" && !Array.isArray(content)) continue;
|
|
67
|
-
|
|
68
|
-
if (!text) continue;
|
|
69
|
-
const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
|
|
70
|
-
messages.push(clipped);
|
|
71
|
-
total += clipped.length;
|
|
124
|
+
if (!pushMessage(contentText(content as Parameters<typeof contentText>[0]))) break;
|
|
72
125
|
}
|
|
126
|
+
|
|
127
|
+
for (const external of externalMessages) {
|
|
128
|
+
if (!pushMessage(external)) break;
|
|
129
|
+
}
|
|
130
|
+
|
|
73
131
|
return messages;
|
|
74
132
|
}
|
|
75
133
|
|
|
76
|
-
/** Prompt asking the model for a
|
|
134
|
+
/** Prompt asking the model for a short session title wrapped in `<title>...</title>`. */
|
|
77
135
|
export function buildAutoNamePrompt(messages: readonly string[]): string {
|
|
78
136
|
return [
|
|
79
137
|
"Summarize the user's goal in this conversation as a short session title.",
|
|
80
138
|
"",
|
|
81
139
|
"Rules:",
|
|
82
|
-
"-
|
|
140
|
+
"- Do not call any tools.",
|
|
141
|
+
"- Reply with only <title>TITLE</title>: no quotes, no prefix, no trailing punctuation, no explanation.",
|
|
83
142
|
"- Use the same language as the user messages.",
|
|
84
|
-
`- Keep
|
|
85
|
-
|
|
143
|
+
`- Keep TITLE under ${AUTO_NAME_MAX_TITLE_CHARS} characters.`,
|
|
144
|
+
"- Name the task or topic, for example <title>修复登录页样式</title> or <title>Add payments API retry</title>.",
|
|
86
145
|
"",
|
|
87
146
|
"User messages:",
|
|
88
147
|
...messages.map((message, index) => `${index + 1}. ${message}`),
|
|
@@ -107,10 +166,17 @@ export async function completeSessionTitle(
|
|
|
107
166
|
prompt: string,
|
|
108
167
|
signal?: AbortSignal,
|
|
109
168
|
): Promise<string> {
|
|
169
|
+
// Non-reasoning models can safely cap output tokens (keeping the call cheap and
|
|
170
|
+
// allowing HTTP proxies to treat it as a title completion). Reasoning models
|
|
171
|
+
// keep the model default budget so thinking tokens never starve the title text.
|
|
172
|
+
const options = model.reasoning ? { signal } : { signal, maxTokens: AUTO_NAME_NON_REASONING_MAX_TOKENS };
|
|
110
173
|
const message: AssistantMessage = await ctx.modelRegistry.complete(
|
|
111
174
|
model,
|
|
112
|
-
{
|
|
113
|
-
|
|
175
|
+
{
|
|
176
|
+
systemPrompt: AUTO_NAME_SYSTEM_PROMPT,
|
|
177
|
+
messages: [{ role: "user", content: prompt, timestamp: Date.now() }],
|
|
178
|
+
},
|
|
179
|
+
options,
|
|
114
180
|
);
|
|
115
181
|
return contentText(message.content);
|
|
116
182
|
}
|
|
@@ -118,10 +184,11 @@ export async function completeSessionTitle(
|
|
|
118
184
|
/**
|
|
119
185
|
* Per-session state machine for auto-name attempts. The controller feeds
|
|
120
186
|
* completed turns and external name changes in; the namer fires on the
|
|
121
|
-
* AUTO_NAME_TURN_THRESHOLD-th turn
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
187
|
+
* AUTO_NAME_TURN_THRESHOLD-th turn (or earlier when an external run already
|
|
188
|
+
* carries enough semantic text) while the session still carries its default
|
|
189
|
+
* manager name and the user has not taken over naming. A failed attempt is
|
|
190
|
+
* retried on later turns, up to AUTO_NAME_MAX_ATTEMPTS attempts, because local
|
|
191
|
+
* single-threaded models can queue or drop one request.
|
|
125
192
|
*/
|
|
126
193
|
export class AutoNamer {
|
|
127
194
|
private turnsSeen = 0;
|
|
@@ -150,10 +217,10 @@ export class AutoNamer {
|
|
|
150
217
|
* naming the session no longer carries the default name, so later turns
|
|
151
218
|
* permanently settle via the userNamed path.
|
|
152
219
|
*/
|
|
153
|
-
noteTurn(currentName: string | undefined, enabled: boolean): boolean {
|
|
220
|
+
noteTurn(currentName: string | undefined, enabled: boolean, readyNow = false): boolean {
|
|
154
221
|
if (this.userNamed) return false;
|
|
155
222
|
this.turnsSeen += 1;
|
|
156
|
-
if (this.turnsSeen < AUTO_NAME_TURN_THRESHOLD) return false;
|
|
223
|
+
if (!readyNow && this.turnsSeen < AUTO_NAME_TURN_THRESHOLD) return false;
|
|
157
224
|
if (currentName !== undefined && !isDefaultManagerName(currentName)) {
|
|
158
225
|
this.userNamed = true;
|
|
159
226
|
return false;
|
|
@@ -164,6 +231,48 @@ export class AutoNamer {
|
|
|
164
231
|
}
|
|
165
232
|
}
|
|
166
233
|
|
|
234
|
+
function extractTaggedTitle(raw: string): string | undefined {
|
|
235
|
+
let lastValid: string | undefined;
|
|
236
|
+
for (const match of raw.matchAll(TITLE_TAG_PATTERN)) {
|
|
237
|
+
const cleaned = cleanTitleCandidate(match[1] ?? "");
|
|
238
|
+
if (cleaned) lastValid = cleaned;
|
|
239
|
+
}
|
|
240
|
+
return lastValid;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function extractFallbackTitle(raw: string): string | undefined {
|
|
244
|
+
let stripped = raw;
|
|
245
|
+
for (let pass = 0; pass < 4; pass += 1) {
|
|
246
|
+
const next = stripped.replace(PAIRED_XML_BLOCK_PATTERN, "\n");
|
|
247
|
+
if (next === stripped) break;
|
|
248
|
+
stripped = next;
|
|
249
|
+
}
|
|
250
|
+
for (const rawLine of stripped.split(/\r?\n/u)) {
|
|
251
|
+
const sanitized = safeTerminalLine(rawLine);
|
|
252
|
+
if (!sanitized) continue;
|
|
253
|
+
if (BARE_XML_TAG_LINE_PATTERN.test(sanitized)) continue;
|
|
254
|
+
if (isProxyOrToolNoise(sanitized)) continue;
|
|
255
|
+
const cleaned = cleanTitleCandidate(sanitized);
|
|
256
|
+
if (cleaned) return cleaned;
|
|
257
|
+
}
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function cleanTitleCandidate(raw: string): string | undefined {
|
|
262
|
+
const line = safeTerminalLine(raw)
|
|
263
|
+
.replace(/^[\s"'`“”‘’#>*_~-]+/u, "")
|
|
264
|
+
.replace(/[\s"'`“”‘’.,;:!?。,;:!?…·#>*_~-]+$/u, "")
|
|
265
|
+
.replace(/^MAN-/iu, "")
|
|
266
|
+
.trim();
|
|
267
|
+
if (!line) return undefined;
|
|
268
|
+
if (isProxyOrToolNoise(line)) return undefined;
|
|
269
|
+
return line;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function isProxyOrToolNoise(line: string): boolean {
|
|
273
|
+
return PROXY_STATUS_LINE_PATTERN.test(line) || ACP_MARKER_PATTERN.test(line);
|
|
274
|
+
}
|
|
275
|
+
|
|
167
276
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
168
277
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
169
278
|
}
|
package/src/budget.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import type { SwarmEngineKind, SwarmLedgerUsage } from "./ledger.js";
|
|
2
|
+
import type { ProfileBudgetTier } from "./profiles.js";
|
|
3
|
+
|
|
4
|
+
export interface BudgetTierLimits {
|
|
5
|
+
maxIterations: number;
|
|
6
|
+
maxDurationMs: number;
|
|
7
|
+
maxTokens: number;
|
|
8
|
+
maxCostUsd: number;
|
|
9
|
+
maxRepeatedFailures: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SwarmBudgetSettings {
|
|
13
|
+
maxChildren: number;
|
|
14
|
+
standard: BudgetTierLimits;
|
|
15
|
+
heavy: BudgetTierLimits;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_STANDARD_BUDGET: Readonly<BudgetTierLimits> = Object.freeze({
|
|
19
|
+
maxIterations: 12,
|
|
20
|
+
maxDurationMs: 15 * 60 * 1000,
|
|
21
|
+
maxTokens: 400_000,
|
|
22
|
+
maxCostUsd: 5,
|
|
23
|
+
maxRepeatedFailures: 2,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_HEAVY_BUDGET: Readonly<BudgetTierLimits> = Object.freeze({
|
|
27
|
+
maxIterations: 30,
|
|
28
|
+
maxDurationMs: 60 * 60 * 1000,
|
|
29
|
+
maxTokens: 1_500_000,
|
|
30
|
+
maxCostUsd: 20,
|
|
31
|
+
maxRepeatedFailures: 2,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_SWARM_BUDGET_SETTINGS: Readonly<SwarmBudgetSettings> = Object.freeze({
|
|
35
|
+
maxChildren: 4,
|
|
36
|
+
standard: DEFAULT_STANDARD_BUDGET,
|
|
37
|
+
heavy: DEFAULT_HEAVY_BUDGET,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
export interface TaskBudgetSnapshot {
|
|
41
|
+
taskId: string;
|
|
42
|
+
tier: ProfileBudgetTier;
|
|
43
|
+
iterations: number;
|
|
44
|
+
elapsedMs: number;
|
|
45
|
+
totalTokens: number;
|
|
46
|
+
costUsd: number;
|
|
47
|
+
byEngine: Record<SwarmEngineKind, { tokens: number; costUsd: number; turns: number }>;
|
|
48
|
+
repeatedFailureClass?: string;
|
|
49
|
+
repeatedFailureCount: number;
|
|
50
|
+
sawQuotaModels: string[];
|
|
51
|
+
budgetLeft: {
|
|
52
|
+
iterations: number;
|
|
53
|
+
durationMs: number;
|
|
54
|
+
tokens: number;
|
|
55
|
+
costUsd: number;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type BudgetCheckOutcome =
|
|
60
|
+
| { status: "ok"; snapshot: TaskBudgetSnapshot }
|
|
61
|
+
| {
|
|
62
|
+
status: "escalate";
|
|
63
|
+
reason:
|
|
64
|
+
| "max_iterations_exceeded"
|
|
65
|
+
| "max_duration_exceeded"
|
|
66
|
+
| "max_tokens_exceeded"
|
|
67
|
+
| "max_cost_exceeded"
|
|
68
|
+
| "repeated_failure_stop";
|
|
69
|
+
detail: string;
|
|
70
|
+
snapshot: TaskBudgetSnapshot;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export interface CrossModelHandoffRecommendation {
|
|
74
|
+
taskId: string;
|
|
75
|
+
failedModel: string;
|
|
76
|
+
reason: "quota_exhausted" | "repeated_failure" | "stalled";
|
|
77
|
+
avoidModels: string[];
|
|
78
|
+
candidateModels: string[];
|
|
79
|
+
handoffRequired: true;
|
|
80
|
+
note: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface InternalTaskBudget {
|
|
84
|
+
taskId: string;
|
|
85
|
+
tier: ProfileBudgetTier;
|
|
86
|
+
startedAt: number;
|
|
87
|
+
iterations: number;
|
|
88
|
+
totalTokens: number;
|
|
89
|
+
costUsd: number;
|
|
90
|
+
byEngine: Record<SwarmEngineKind, { tokens: number; costUsd: number; turns: number }>;
|
|
91
|
+
lastFailureClass?: string;
|
|
92
|
+
repeatedFailureCount: number;
|
|
93
|
+
sawQuotaModels: Set<string>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Dual-layer unified budget tracker (Pi native + agy ACP PromptResult.usage).
|
|
98
|
+
*
|
|
99
|
+
* Hard discipline (inherited from contextRecycling):
|
|
100
|
+
* - NEVER aborts a healthy in-flight turn mid-stream; callers check `evaluate()` at turn boundaries
|
|
101
|
+
* and escalate to a human gate when any limit or repeated-failure stop rule is hit.
|
|
102
|
+
*/
|
|
103
|
+
export class SwarmBudgetTracker {
|
|
104
|
+
private readonly tasks = new Map<string, InternalTaskBudget>();
|
|
105
|
+
|
|
106
|
+
constructor(private readonly now: () => number = Date.now) {}
|
|
107
|
+
|
|
108
|
+
startTask(taskId: string, tier: ProfileBudgetTier = "standard"): void {
|
|
109
|
+
if (this.tasks.has(taskId)) return;
|
|
110
|
+
this.tasks.set(taskId, {
|
|
111
|
+
taskId,
|
|
112
|
+
tier,
|
|
113
|
+
startedAt: this.now(),
|
|
114
|
+
iterations: 0,
|
|
115
|
+
totalTokens: 0,
|
|
116
|
+
costUsd: 0,
|
|
117
|
+
byEngine: {
|
|
118
|
+
pi: { tokens: 0, costUsd: 0, turns: 0 },
|
|
119
|
+
agy: { tokens: 0, costUsd: 0, turns: 0 },
|
|
120
|
+
},
|
|
121
|
+
repeatedFailureCount: 0,
|
|
122
|
+
sawQuotaModels: new Set(),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
recordTurn(params: {
|
|
127
|
+
taskId: string;
|
|
128
|
+
tier?: ProfileBudgetTier;
|
|
129
|
+
engine: SwarmEngineKind;
|
|
130
|
+
model: string;
|
|
131
|
+
usage?: SwarmLedgerUsage;
|
|
132
|
+
failureClass?: string;
|
|
133
|
+
sawQuota?: boolean;
|
|
134
|
+
}): void {
|
|
135
|
+
let entry = this.tasks.get(params.taskId);
|
|
136
|
+
if (!entry) {
|
|
137
|
+
this.startTask(params.taskId, params.tier ?? "standard");
|
|
138
|
+
entry = this.tasks.get(params.taskId);
|
|
139
|
+
}
|
|
140
|
+
if (!entry) return;
|
|
141
|
+
entry.iterations += 1;
|
|
142
|
+
const tokens =
|
|
143
|
+
params.usage?.totalTokens ??
|
|
144
|
+
(params.usage?.inputTokens !== undefined || params.usage?.outputTokens !== undefined
|
|
145
|
+
? (params.usage.inputTokens ?? 0) + (params.usage.outputTokens ?? 0)
|
|
146
|
+
: 0);
|
|
147
|
+
const costUsd = params.usage?.costUsd ?? 0;
|
|
148
|
+
|
|
149
|
+
entry.totalTokens += Math.max(0, tokens);
|
|
150
|
+
entry.costUsd += Math.max(0, costUsd);
|
|
151
|
+
entry.byEngine[params.engine].tokens += Math.max(0, tokens);
|
|
152
|
+
entry.byEngine[params.engine].costUsd += Math.max(0, costUsd);
|
|
153
|
+
entry.byEngine[params.engine].turns += 1;
|
|
154
|
+
|
|
155
|
+
if (params.sawQuota) {
|
|
156
|
+
entry.sawQuotaModels.add(params.model);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (params.failureClass) {
|
|
160
|
+
if (entry.lastFailureClass === params.failureClass) {
|
|
161
|
+
entry.repeatedFailureCount += 1;
|
|
162
|
+
} else {
|
|
163
|
+
entry.lastFailureClass = params.failureClass;
|
|
164
|
+
entry.repeatedFailureCount = 1;
|
|
165
|
+
}
|
|
166
|
+
} else {
|
|
167
|
+
entry.lastFailureClass = undefined;
|
|
168
|
+
entry.repeatedFailureCount = 0;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
evaluate(taskId: string, settings: SwarmBudgetSettings): BudgetCheckOutcome {
|
|
173
|
+
const entry = this.tasks.get(taskId);
|
|
174
|
+
if (!entry) {
|
|
175
|
+
this.startTask(taskId, "standard");
|
|
176
|
+
return this.evaluate(taskId, settings);
|
|
177
|
+
}
|
|
178
|
+
const limits = entry.tier === "heavy" ? settings.heavy : settings.standard;
|
|
179
|
+
const elapsedMs = Math.max(0, this.now() - entry.startedAt);
|
|
180
|
+
const snapshot: TaskBudgetSnapshot = {
|
|
181
|
+
taskId: entry.taskId,
|
|
182
|
+
tier: entry.tier,
|
|
183
|
+
iterations: entry.iterations,
|
|
184
|
+
elapsedMs,
|
|
185
|
+
totalTokens: entry.totalTokens,
|
|
186
|
+
costUsd: Number(entry.costUsd.toFixed(6)),
|
|
187
|
+
byEngine: {
|
|
188
|
+
pi: { ...entry.byEngine.pi },
|
|
189
|
+
agy: { ...entry.byEngine.agy },
|
|
190
|
+
},
|
|
191
|
+
...(entry.lastFailureClass ? { repeatedFailureClass: entry.lastFailureClass } : {}),
|
|
192
|
+
repeatedFailureCount: entry.repeatedFailureCount,
|
|
193
|
+
sawQuotaModels: [...entry.sawQuotaModels],
|
|
194
|
+
budgetLeft: {
|
|
195
|
+
iterations: Math.max(0, limits.maxIterations - entry.iterations),
|
|
196
|
+
durationMs: Math.max(0, limits.maxDurationMs - elapsedMs),
|
|
197
|
+
tokens: Math.max(0, limits.maxTokens - entry.totalTokens),
|
|
198
|
+
costUsd: Math.max(0, Number((limits.maxCostUsd - entry.costUsd).toFixed(6))),
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
if (entry.repeatedFailureCount >= limits.maxRepeatedFailures) {
|
|
203
|
+
return {
|
|
204
|
+
status: "escalate",
|
|
205
|
+
reason: "repeated_failure_stop",
|
|
206
|
+
detail: `Task ${taskId} hit repeated failure "${entry.lastFailureClass}" ${entry.repeatedFailureCount} times (limit ${limits.maxRepeatedFailures}).`,
|
|
207
|
+
snapshot,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
if (entry.iterations >= limits.maxIterations) {
|
|
211
|
+
return {
|
|
212
|
+
status: "escalate",
|
|
213
|
+
reason: "max_iterations_exceeded",
|
|
214
|
+
detail: `Task ${taskId} reached ${entry.iterations}/${limits.maxIterations} iterations (${entry.tier} tier).`,
|
|
215
|
+
snapshot,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
if (elapsedMs >= limits.maxDurationMs) {
|
|
219
|
+
return {
|
|
220
|
+
status: "escalate",
|
|
221
|
+
reason: "max_duration_exceeded",
|
|
222
|
+
detail: `Task ${taskId} exceeded max duration (${elapsedMs}ms >= ${limits.maxDurationMs}ms, ${entry.tier} tier).`,
|
|
223
|
+
snapshot,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
if (entry.totalTokens >= limits.maxTokens) {
|
|
227
|
+
return {
|
|
228
|
+
status: "escalate",
|
|
229
|
+
reason: "max_tokens_exceeded",
|
|
230
|
+
detail: `Task ${taskId} exceeded token budget (${entry.totalTokens}/${limits.maxTokens}, ${entry.tier} tier).`,
|
|
231
|
+
snapshot,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
if (entry.costUsd >= limits.maxCostUsd) {
|
|
235
|
+
return {
|
|
236
|
+
status: "escalate",
|
|
237
|
+
reason: "max_cost_exceeded",
|
|
238
|
+
detail: `Task ${taskId} exceeded cost budget ($${entry.costUsd.toFixed(4)}/$${limits.maxCostUsd}, ${entry.tier} tier).`,
|
|
239
|
+
snapshot,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return { status: "ok", snapshot };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
recommendCrossModelHandoff(params: {
|
|
246
|
+
taskId: string;
|
|
247
|
+
failedModel: string;
|
|
248
|
+
reason: "quota_exhausted" | "repeated_failure" | "stalled";
|
|
249
|
+
availableConcreteModels: readonly string[];
|
|
250
|
+
}): CrossModelHandoffRecommendation {
|
|
251
|
+
const entry = this.tasks.get(params.taskId);
|
|
252
|
+
const avoid = new Set<string>([params.failedModel, ...(entry?.sawQuotaModels ?? [])]);
|
|
253
|
+
const candidates = params.availableConcreteModels.filter((ref) => !avoid.has(ref));
|
|
254
|
+
return {
|
|
255
|
+
taskId: params.taskId,
|
|
256
|
+
failedModel: params.failedModel,
|
|
257
|
+
reason: params.reason,
|
|
258
|
+
avoidModels: [...avoid],
|
|
259
|
+
candidateModels: candidates,
|
|
260
|
+
handoffRequired: true,
|
|
261
|
+
note: "Single worker engine binding prohibits mid-window engine toggles. Request a structured handoff from the worker, then spawn a fresh successor with a Lead-selected concrete model from candidateModels.",
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
clear(): void {
|
|
266
|
+
this.tasks.clear();
|
|
267
|
+
}
|
|
268
|
+
}
|