-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathloop.ts
More file actions
453 lines (393 loc) · 13.3 KB
/
loop.ts
File metadata and controls
453 lines (393 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/**
* Loop Extension
*
* Provides a /loop command that starts a follow-up loop with a breakout condition.
* The loop keeps sending a prompt on turn end until the agent calls the
* signal_loop_success tool.
*/
import { Type } from "@sinclair/typebox";
import { complete, type Api, type Model, type UserMessage } from "@mariozechner/pi-ai";
import type { ExtensionAPI, ExtensionContext, SessionSwitchEvent } from "@mariozechner/pi-coding-agent";
import { compact } from "@mariozechner/pi-coding-agent";
import { Container, type SelectItem, SelectList, Text } from "@mariozechner/pi-tui";
import { DynamicBorder } from "@mariozechner/pi-coding-agent";
type LoopMode = "tests" | "custom" | "self";
type LoopStateData = {
active: boolean;
mode?: LoopMode;
condition?: string;
prompt?: string;
summary?: string;
loopCount?: number;
};
const LOOP_PRESETS = [
{ value: "tests", label: "Until tests pass", description: "" },
{ value: "custom", label: "Until custom condition", description: "" },
{ value: "self", label: "Self driven (agent decides)", description: "" },
] as const;
const LOOP_STATE_ENTRY = "loop-state";
const HAIKU_MODEL_ID = "claude-haiku-4-5";
const SUMMARY_SYSTEM_PROMPT = `You summarize loop breakout conditions for a status widget.
Return a concise phrase (max 6 words) that says when the loop should stop.
Use plain text only, no quotes, no punctuation, no prefix.
Form should be "breaks when ...", "loops until ...", "stops on ...", "runs until ...", or similar.
Use the best form that makes sense for the loop condition.
`;
function buildPrompt(mode: LoopMode, condition?: string): string {
switch (mode) {
case "tests":
return (
"Run all tests. If they are passing, call the signal_loop_success tool. " +
"Otherwise continue until the tests pass."
);
case "custom": {
const customCondition = condition?.trim() || "the custom condition is satisfied";
return (
`Continue until the following condition is satisfied: ${customCondition}. ` +
"When it is satisfied, call the signal_loop_success tool."
);
}
case "self":
return "Continue until you are done. When finished, call the signal_loop_success tool.";
}
}
function summarizeCondition(mode: LoopMode, condition?: string): string {
switch (mode) {
case "tests":
return "tests pass";
case "custom": {
const summary = condition?.trim() || "custom condition";
return summary.length > 48 ? `${summary.slice(0, 45)}...` : summary;
}
case "self":
return "done";
}
}
function getConditionText(mode: LoopMode, condition?: string): string {
switch (mode) {
case "tests":
return "tests pass";
case "custom":
return condition?.trim() || "custom condition";
case "self":
return "you are done";
}
}
async function selectSummaryModel(
ctx: ExtensionContext,
): Promise<{ model: Model<Api>; apiKey?: string; headers?: Record<string, string> } | null> {
if (!ctx.model) return null;
if (ctx.model.provider === "anthropic") {
const haikuModel = ctx.modelRegistry.find("anthropic", HAIKU_MODEL_ID);
if (haikuModel) {
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(haikuModel);
if (auth.ok) {
return { model: haikuModel, apiKey: auth.apiKey, headers: auth.headers };
}
}
}
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
if (!auth.ok) return null;
return { model: ctx.model, apiKey: auth.apiKey, headers: auth.headers };
}
async function summarizeBreakoutCondition(
ctx: ExtensionContext,
mode: LoopMode,
condition?: string,
): Promise<string> {
const fallback = summarizeCondition(mode, condition);
const selection = await selectSummaryModel(ctx);
if (!selection) return fallback;
const conditionText = getConditionText(mode, condition);
const userMessage: UserMessage = {
role: "user",
content: [{ type: "text", text: conditionText }],
timestamp: Date.now(),
};
const response = await complete(
selection.model,
{ systemPrompt: SUMMARY_SYSTEM_PROMPT, messages: [userMessage] },
{ apiKey: selection.apiKey, headers: selection.headers },
);
if (response.stopReason === "aborted" || response.stopReason === "error") {
return fallback;
}
const summary = response.content
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text)
.join(" ")
.replace(/\s+/g, " ")
.trim();
if (!summary) return fallback;
return summary.length > 60 ? `${summary.slice(0, 57)}...` : summary;
}
function getCompactionInstructions(mode: LoopMode, condition?: string): string {
const conditionText = getConditionText(mode, condition);
return `Loop active. Breakout condition: ${conditionText}. Preserve this loop state and breakout condition in the summary.`;
}
function updateStatus(ctx: ExtensionContext, state: LoopStateData): void {
if (!ctx.hasUI) return;
if (!state.active || !state.mode) {
ctx.ui.setWidget("loop", undefined);
return;
}
const loopCount = state.loopCount ?? 0;
const turnText = `(turn ${loopCount})`;
const summary = state.summary?.trim();
const text = summary
? `Loop active: ${summary} ${turnText}`
: `Loop active ${turnText}`;
ctx.ui.setWidget("loop", [ctx.ui.theme.fg("accent", text)]);
}
async function loadState(ctx: ExtensionContext): Promise<LoopStateData> {
const entries = ctx.sessionManager.getEntries();
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i] as { type: string; customType?: string; data?: LoopStateData };
if (entry.type === "custom" && entry.customType === LOOP_STATE_ENTRY && entry.data) {
return entry.data;
}
}
return { active: false };
}
export default function loopExtension(pi: ExtensionAPI): void {
let loopState: LoopStateData = { active: false };
function persistState(state: LoopStateData): void {
pi.appendEntry(LOOP_STATE_ENTRY, state);
}
function setLoopState(state: LoopStateData, ctx: ExtensionContext): void {
loopState = state;
persistState(state);
updateStatus(ctx, state);
}
function clearLoopState(ctx: ExtensionContext): void {
const cleared: LoopStateData = { active: false };
loopState = cleared;
persistState(cleared);
updateStatus(ctx, cleared);
}
function breakLoop(ctx: ExtensionContext): void {
clearLoopState(ctx);
ctx.ui.notify("Loop ended", "info");
}
function wasLastAssistantAborted(messages: Array<{ role?: string; stopReason?: string }>): boolean {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (message?.role === "assistant") {
return message.stopReason === "aborted";
}
}
return false;
}
function triggerLoopPrompt(ctx: ExtensionContext): void {
if (!loopState.active || !loopState.mode || !loopState.prompt) return;
if (ctx.hasPendingMessages()) return;
const loopCount = (loopState.loopCount ?? 0) + 1;
loopState = { ...loopState, loopCount };
persistState(loopState);
updateStatus(ctx, loopState);
pi.sendMessage({
customType: "loop",
content: loopState.prompt,
display: true
}, {
deliverAs: "followUp",
triggerTurn: true
});
}
async function showLoopSelector(ctx: ExtensionContext): Promise<LoopStateData | null> {
const items: SelectItem[] = LOOP_PRESETS.map((preset) => ({
value: preset.value,
label: preset.label,
description: preset.description,
}));
const selection = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
const container = new Container();
container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
container.addChild(new Text(theme.fg("accent", theme.bold("Select a loop preset"))));
const selectList = new SelectList(items, Math.min(items.length, 10), {
selectedPrefix: (text) => theme.fg("accent", text),
selectedText: (text) => theme.fg("accent", text),
description: (text) => theme.fg("muted", text),
scrollInfo: (text) => theme.fg("dim", text),
noMatch: (text) => theme.fg("warning", text),
});
selectList.onSelect = (item) => done(item.value);
selectList.onCancel = () => done(null);
container.addChild(selectList);
container.addChild(new Text(theme.fg("dim", "Press enter to confirm or esc to cancel")));
container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
return {
render(width: number) {
return container.render(width);
},
invalidate() {
container.invalidate();
},
handleInput(data: string) {
selectList.handleInput(data);
tui.requestRender();
},
};
});
if (!selection) return null;
switch (selection) {
case "tests":
return { active: true, mode: "tests", prompt: buildPrompt("tests") };
case "self":
return { active: true, mode: "self", prompt: buildPrompt("self") };
case "custom": {
const condition = await ctx.ui.editor("Enter loop breakout condition:", "");
if (!condition?.trim()) return null;
return {
active: true,
mode: "custom",
condition: condition.trim(),
prompt: buildPrompt("custom", condition.trim()),
};
}
default:
return null;
}
}
function parseArgs(args: string | undefined): LoopStateData | null {
if (!args?.trim()) return null;
const parts = args.trim().split(/\s+/);
const mode = parts[0]?.toLowerCase();
switch (mode) {
case "tests":
return { active: true, mode: "tests", prompt: buildPrompt("tests") };
case "self":
return { active: true, mode: "self", prompt: buildPrompt("self") };
case "custom": {
const condition = parts.slice(1).join(" ").trim();
if (!condition) return null;
return {
active: true,
mode: "custom",
condition,
prompt: buildPrompt("custom", condition),
};
}
default:
return null;
}
}
pi.registerTool({
name: "signal_loop_success",
label: "Signal Loop Success",
description: "Stop the active loop when the breakout condition is satisfied. Only call this tool when explicitly instructed to do so by the user, tool or system prompt.",
parameters: Type.Object({}),
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
if (!loopState.active) {
return {
content: [{ type: "text", text: "No active loop is running." }],
details: { active: false },
};
}
clearLoopState(ctx);
return {
content: [{ type: "text", text: "Loop ended." }],
details: { active: false },
};
},
});
pi.registerCommand("loop", {
description: "Start a follow-up loop until a breakout condition is met",
handler: async (args, ctx) => {
let nextState = parseArgs(args);
if (!nextState) {
if (!ctx.hasUI) {
ctx.ui.notify("Usage: /loop tests | /loop custom <condition> | /loop self", "warning");
return;
}
nextState = await showLoopSelector(ctx);
}
if (!nextState) {
ctx.ui.notify("Loop cancelled", "info");
return;
}
if (loopState.active) {
const confirm = ctx.hasUI
? await ctx.ui.confirm("Replace active loop?", "A loop is already active. Replace it?")
: true;
if (!confirm) {
ctx.ui.notify("Loop unchanged", "info");
return;
}
}
const summarizedState: LoopStateData = { ...nextState, summary: undefined, loopCount: 0 };
setLoopState(summarizedState, ctx);
ctx.ui.notify("Loop active", "info");
triggerLoopPrompt(ctx);
const mode = nextState.mode!;
const condition = nextState.condition;
void (async () => {
const summary = await summarizeBreakoutCondition(ctx, mode, condition);
if (!loopState.active || loopState.mode !== mode || loopState.condition !== condition) return;
loopState = { ...loopState, summary };
persistState(loopState);
updateStatus(ctx, loopState);
})();
},
});
pi.on("agent_end", async (event, ctx) => {
if (!loopState.active) return;
if (ctx.hasUI && wasLastAssistantAborted(event.messages)) {
const confirm = await ctx.ui.confirm(
"Break active loop?",
"Operation aborted. Break out of the loop?",
);
if (confirm) {
breakLoop(ctx);
return;
}
}
triggerLoopPrompt(ctx);
});
pi.on("session_before_compact", async (event, ctx) => {
if (!loopState.active || !loopState.mode || !ctx.model) return;
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
if (!auth.ok) return;
const instructionParts = [event.customInstructions, getCompactionInstructions(loopState.mode, loopState.condition)]
.filter(Boolean)
.join("\n\n");
try {
const compaction = await compact(
event.preparation,
ctx.model,
auth.apiKey ?? "",
auth.headers,
instructionParts,
event.signal,
);
return { compaction };
} catch (error) {
if (ctx.hasUI) {
const message = error instanceof Error ? error.message : String(error);
ctx.ui.notify(`Loop compaction failed: ${message}`, "warning");
}
return;
}
});
async function restoreLoopState(ctx: ExtensionContext): Promise<void> {
loopState = await loadState(ctx);
updateStatus(ctx, loopState);
if (loopState.active && loopState.mode && !loopState.summary) {
const mode = loopState.mode;
const condition = loopState.condition;
void (async () => {
const summary = await summarizeBreakoutCondition(ctx, mode, condition);
if (!loopState.active || loopState.mode !== mode || loopState.condition !== condition) return;
loopState = { ...loopState, summary };
persistState(loopState);
updateStatus(ctx, loopState);
})();
}
}
pi.on("session_start", async (_event, ctx) => {
await restoreLoopState(ctx);
});
pi.on("session_switch", async (_event: SessionSwitchEvent, ctx) => {
await restoreLoopState(ctx);
});
}