pi-agent-swarm 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agent-swarm",
3
- "version": "0.4.0",
3
+ "version": "0.6.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",
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. Strips terminal
38
- * controls, quotes, and markdown noise, keeps the first line, truncates to
39
- * AUTO_NAME_MAX_TITLE_CHARS code points, and returns undefined when nothing
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 line = safeTerminalLine(raw)
45
- .replace(/^[\s"'`“”‘’#>*_~-]+/u, "")
46
- .replace(/[\s"'`“”‘’.,;:!?。,;:!?…·#>*_~-]+$/u, "")
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, each clipped to AUTO_NAME_MAX_MESSAGE_CHARS and capped in total.
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
- const text = safeTerminalLine(contentText(content as Parameters<typeof contentText>[0]));
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 bare, short session title in the user's language. */
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
- "- Reply with only the title: no quotes, no prefix, no trailing punctuation.",
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 it under ${AUTO_NAME_MAX_TITLE_CHARS} characters.`,
85
- '- Name the task or topic, for example "修复登录页样式" or "Add payments API retry".',
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
- { messages: [{ role: "user", content: prompt, timestamp: Date.now() }] },
113
- { signal },
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 while the session still carries its
122
- * default manager name and the user has not taken over naming. A failed
123
- * attempt is retried on later turns, up to AUTO_NAME_MAX_ATTEMPTS attempts,
124
- * because local single-threaded models can queue or drop one request.
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
+ }
@@ -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
+ }