killeros 1.4.8 → 1.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/CHANGELOG.md +21 -4
- package/Killeros.ts +25 -2542
- package/README.md +23 -8
- package/killeros/commands.ts +164 -0
- package/killeros/concise.ts +23 -0
- package/killeros/display.ts +39 -0
- package/killeros/errors.ts +6 -0
- package/killeros/footer.ts +209 -0
- package/killeros/goals.ts +720 -0
- package/killeros/hooks.ts +219 -0
- package/killeros/init.ts +470 -0
- package/killeros/personal-instructions.ts +66 -0
- package/killeros/question.ts +468 -0
- package/killeros/runtime.ts +61 -0
- package/killeros/shell-ui.ts +270 -0
- package/killeros/subagent-lifecycle.ts +532 -0
- package/killeros/subagent-process.ts +601 -0
- package/killeros/subagent-ui.ts +227 -0
- package/killeros/subagents.ts +1917 -0
- package/killeros/variants.ts +136 -0
- package/package.json +7 -6
- package/subagent-lifecycle.ts +1 -506
- package/subagent-process.ts +1 -595
- package/subagent-ui.ts +1 -227
- package/subagents.ts +1 -1556
package/Killeros.ts
CHANGED
|
@@ -1,2554 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
} from "
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
decodeKittyPrintable,
|
|
20
|
-
Editor,
|
|
21
|
-
Key,
|
|
22
|
-
Markdown,
|
|
23
|
-
matchesKey,
|
|
24
|
-
SelectList,
|
|
25
|
-
Text,
|
|
26
|
-
truncateToWidth,
|
|
27
|
-
visibleWidth,
|
|
28
|
-
wrapTextWithAnsi,
|
|
29
|
-
type AutocompleteItem,
|
|
30
|
-
type EditorTheme,
|
|
31
|
-
type TUI,
|
|
32
|
-
} from "@earendil-works/pi-tui";
|
|
33
|
-
import { Type } from "typebox";
|
|
34
|
-
import { registerSubagentTool } from "./subagents.ts";
|
|
35
|
-
|
|
36
|
-
const COMMAND_BLUE_RGB = "120;169;255";
|
|
37
|
-
const FOOTER_REFRESH_INTERVAL_MS = 1_000;
|
|
38
|
-
const COMPACT_HEADER_MAX_WIDTH = 52;
|
|
39
|
-
|
|
40
|
-
const commandBlue = (text: string): string => `\x1B[38;2;${COMMAND_BLUE_RGB}m${text}\x1B[39m`;
|
|
41
|
-
|
|
42
|
-
function readPackageVersion(path: string | URL): string | undefined {
|
|
43
|
-
try {
|
|
44
|
-
const value = JSON.parse(readFileSync(path, "utf8")) as { version?: unknown };
|
|
45
|
-
return typeof value.version === "string" ? value.version : undefined;
|
|
46
|
-
} catch {
|
|
47
|
-
return undefined;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const KILLEROS_VERSION = readPackageVersion(new URL("./package.json", import.meta.url));
|
|
52
|
-
|
|
53
|
-
const STARTUP_TIPS = [
|
|
54
|
-
"Press Shift+Enter to insert a line break without sending.",
|
|
55
|
-
"Run /variants to tune the model's reasoning depth.",
|
|
56
|
-
"Type / to browse every command available in this session.",
|
|
57
|
-
] as const;
|
|
58
|
-
|
|
59
|
-
function resolveGitBranch(cwd: string): string | undefined {
|
|
60
|
-
try {
|
|
61
|
-
const branch = execFileSync("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], {
|
|
62
|
-
encoding: "utf8",
|
|
63
|
-
maxBuffer: 64 * 1024,
|
|
64
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
65
|
-
timeout: 500,
|
|
66
|
-
windowsHide: true,
|
|
67
|
-
}).trim();
|
|
68
|
-
if (!branch) return undefined;
|
|
69
|
-
return branch === "HEAD" ? "detached" : branch;
|
|
70
|
-
} catch {
|
|
71
|
-
return undefined;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function shuffledTips(): string[] {
|
|
76
|
-
const tips = [...STARTUP_TIPS];
|
|
77
|
-
for (let index = tips.length - 1; index > 0; index -= 1) {
|
|
78
|
-
const swapIndex = Math.floor(Math.random() * (index + 1));
|
|
79
|
-
[tips[index], tips[swapIndex]] = [tips[swapIndex]!, tips[index]!];
|
|
80
|
-
}
|
|
81
|
-
return tips;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function formatCwd(cwd: string): string {
|
|
85
|
-
const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
86
|
-
if (!home) return cwd;
|
|
87
|
-
const normalizedHome = home.replace(/[\\/]+$/, "");
|
|
88
|
-
const normalizedCwd = cwd.replace(/[\\/]+$/, "");
|
|
89
|
-
if (normalizedCwd === normalizedHome) return "~";
|
|
90
|
-
const separator = normalizedCwd.slice(normalizedHome.length, normalizedHome.length + 1);
|
|
91
|
-
return normalizedCwd.startsWith(normalizedHome) && (separator === "/" || separator === "\\")
|
|
92
|
-
? `~${normalizedCwd.slice(normalizedHome.length)}`
|
|
93
|
-
: cwd;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function padRight(text: string, width: number): string {
|
|
97
|
-
if (width <= 0) return "";
|
|
98
|
-
const clipped = truncateToWidth(text, width, "");
|
|
99
|
-
return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function compactBoxLine(content: string, width: number, theme: Theme): string {
|
|
103
|
-
if (width < 4) return truncateToWidth(content, width, "");
|
|
104
|
-
return `${theme.fg("dim", "│")} ${padRight(content, width - 4)} ${theme.fg("dim", "│")}`;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
class PiStartupHeader {
|
|
108
|
-
private readonly pi: ExtensionAPI;
|
|
109
|
-
private readonly ctx: ExtensionContext;
|
|
110
|
-
private readonly branch: string | undefined;
|
|
111
|
-
private readonly tip: string;
|
|
112
|
-
|
|
113
|
-
constructor(pi: ExtensionAPI, ctx: ExtensionContext, tip: string) {
|
|
114
|
-
this.pi = pi;
|
|
115
|
-
this.ctx = ctx;
|
|
116
|
-
this.branch = resolveGitBranch(ctx.cwd);
|
|
117
|
-
this.tip = tip;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
private tipLines(width: number, theme: Theme): string[] {
|
|
121
|
-
const indent = " ";
|
|
122
|
-
const text = `${theme.fg("text", theme.bold("Tip:"))}${theme.fg("dim", ` ${this.tip}`)}`;
|
|
123
|
-
return wrapTextWithAnsi(text, width - indent.length)
|
|
124
|
-
.map((line) => padRight(`${indent}${line}`, width));
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
render(width: number): string[] {
|
|
128
|
-
if (width <= 0) return [];
|
|
129
|
-
const theme = this.ctx.ui.theme;
|
|
130
|
-
if (width < 28) return [truncateToWidth(theme.fg("text", theme.bold("KillerOS")), width, "")];
|
|
131
|
-
|
|
132
|
-
const panelWidth = Math.min(width, COMPACT_HEADER_MAX_WIDTH);
|
|
133
|
-
const innerWidth = panelWidth - 4;
|
|
134
|
-
const version = KILLEROS_VERSION ? theme.fg("dim", ` (v${KILLEROS_VERSION})`) : "";
|
|
135
|
-
const identity = `${theme.fg("dim", "›")} ${theme.fg("text", theme.bold("KillerOS"))}${version}`;
|
|
136
|
-
const thinkingLevel = this.pi.getThinkingLevel() as ThinkingLevel;
|
|
137
|
-
const reasoning = this.ctx.model?.reasoning === false
|
|
138
|
-
? theme.fg("thinkingOff", "no reasoning")
|
|
139
|
-
: theme.fg(LEVEL_COLORS[thinkingLevel], thinkingLevel);
|
|
140
|
-
const agent = `${formatModel(this.ctx.model, theme)}${theme.fg("dim", " · ")}${reasoning}`;
|
|
141
|
-
const directory = formatCwd(this.ctx.cwd);
|
|
142
|
-
const repository = this.branch
|
|
143
|
-
? `${directory} ${theme.fg("dim", `· ${this.branch}`)}`
|
|
144
|
-
: directory;
|
|
145
|
-
const modelCommand = commandBlue("/model");
|
|
146
|
-
const agentWidth = Math.max(0, innerWidth - visibleWidth(modelCommand) - 1);
|
|
147
|
-
const agentCommand = `${truncateToWidth(agent, agentWidth, "…")} ${modelCommand}`;
|
|
148
|
-
const border = (left: string, right: string): string => theme.fg("dim", `${left}${"─".repeat(panelWidth - 2)}${right}`);
|
|
149
|
-
const lines = [
|
|
150
|
-
border("╭", "╮"),
|
|
151
|
-
compactBoxLine(identity, panelWidth, theme),
|
|
152
|
-
compactBoxLine("", panelWidth, theme),
|
|
153
|
-
compactBoxLine(agentCommand, panelWidth, theme),
|
|
154
|
-
compactBoxLine(repository, panelWidth, theme),
|
|
155
|
-
border("╰", "╯"),
|
|
156
|
-
" ".repeat(panelWidth),
|
|
157
|
-
...this.tipLines(panelWidth, theme),
|
|
158
|
-
];
|
|
159
|
-
return lines;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
invalidate(): void {}
|
|
163
|
-
dispose(): void {}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const ANSI_REGEX = /\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
|
|
167
|
-
|
|
168
|
-
function stripAnsi(text: string): string {
|
|
169
|
-
return text.replace(ANSI_REGEX, "").trim();
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function isBorderLine(line: string): boolean {
|
|
173
|
-
const unstyled = stripAnsi(line);
|
|
174
|
-
return /^[─━═]+$/.test(unstyled) || /^───\s*[↓↑]/.test(unstyled) || /^─{3,}/.test(unstyled);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
class PiCodeEditor extends CustomEditor {
|
|
178
|
-
private readonly appKeybindings: KeybindingsManager;
|
|
179
|
-
|
|
180
|
-
constructor(tui: TUI, theme: EditorTheme, appKeybindings: KeybindingsManager) {
|
|
181
|
-
super(tui, theme, appKeybindings);
|
|
182
|
-
this.appKeybindings = appKeybindings;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
override handleInput(data: string): void {
|
|
186
|
-
const isShiftEnter = data === "\x1B[13;2u"
|
|
187
|
-
|| data === "\x1B[13;2~"
|
|
188
|
-
|| data === "\x1B[27;2;13~"
|
|
189
|
-
|| data === "\x1B\r"
|
|
190
|
-
|| data === "\x1B\n"
|
|
191
|
-
|| this.appKeybindings.matches(data, "tui.input.newLine");
|
|
192
|
-
if (isShiftEnter) {
|
|
193
|
-
this.insertTextAtCursor("\n");
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
super.handleInput(data);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
override render(width: number): string[] {
|
|
200
|
-
if (width < 4) return super.render(width);
|
|
201
|
-
const innerWidth = width - 2;
|
|
202
|
-
const lines = super.render(innerWidth);
|
|
203
|
-
if (lines.length < 2) return lines.map((line) => truncateToWidth(line, width, ""));
|
|
204
|
-
|
|
205
|
-
const gray = (text: string): string => `\x1B[90m${text}\x1B[39m`;
|
|
206
|
-
let bottomBorderIndex = -1;
|
|
207
|
-
for (let index = lines.length - 1; index >= 1; index -= 1) {
|
|
208
|
-
if (isBorderLine(lines[index] ?? "")) {
|
|
209
|
-
bottomBorderIndex = index;
|
|
210
|
-
break;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
if (bottomBorderIndex < 0) bottomBorderIndex = lines.length - 1;
|
|
214
|
-
|
|
215
|
-
const framed: string[] = [];
|
|
216
|
-
const top = stripAnsi(lines[0] ?? "");
|
|
217
|
-
const isScrolledHeader = top.includes("↑");
|
|
218
|
-
if (isScrolledHeader) {
|
|
219
|
-
const count = top.match(/↑\s*(\d+)/)?.[1] ?? "";
|
|
220
|
-
const indicator = `${gray("─── ↑ ")}${count}${gray(" more ")}${gray("─".repeat(Math.max(0, width - 12 - count.length)))}`;
|
|
221
|
-
framed.push(truncateToWidth(indicator, width, ""));
|
|
222
|
-
} else {
|
|
223
|
-
framed.push(gray("─".repeat(width)));
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
for (let index = 1; index < bottomBorderIndex; index += 1) {
|
|
227
|
-
const prefix = index === 1 && !isScrolledHeader ? gray("❯ ") : " ";
|
|
228
|
-
framed.push(`${prefix}${padRight(lines[index] ?? "", innerWidth)}`);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const bottom = stripAnsi(lines[bottomBorderIndex] ?? "");
|
|
232
|
-
if (bottom.includes("↓")) {
|
|
233
|
-
const count = bottom.match(/↓\s*(\d+)/)?.[1] ?? "";
|
|
234
|
-
const indicator = `${gray("─── ↓ ")}${count}${gray(" more ")}${gray("─".repeat(Math.max(0, width - 12 - count.length)))}`;
|
|
235
|
-
framed.push(truncateToWidth(indicator, width, ""));
|
|
236
|
-
} else {
|
|
237
|
-
framed.push(gray("─".repeat(width)));
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
for (let index = bottomBorderIndex + 1; index < lines.length; index += 1) {
|
|
241
|
-
framed.push(` ${padRight(lines[index] ?? "", innerWidth)}`);
|
|
242
|
-
}
|
|
243
|
-
return framed.map((line) => truncateToWidth(line, width, ""));
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
function reportError(ctx: ExtensionContext, area: string, error: unknown): void {
|
|
248
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
249
|
-
ctx.ui.notify(`${area}: ${message}`, "error");
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
const ACTIVITY_WORDS = ["Brewing", "Pondering", "Tinkering", "Wrangling", "Noodling", "Cooking"] as const;
|
|
253
|
-
|
|
254
|
-
function registerShellUi(pi: ExtensionAPI): void {
|
|
255
|
-
let activeHeader: PiStartupHeader | undefined;
|
|
256
|
-
let activityWordIndex = 0;
|
|
257
|
-
let tipDeck: string[] = [];
|
|
258
|
-
const nextStartupTip = (): string => {
|
|
259
|
-
if (tipDeck.length === 0) tipDeck = shuffledTips();
|
|
260
|
-
return tipDeck.pop() ?? STARTUP_TIPS[0];
|
|
261
|
-
};
|
|
262
|
-
|
|
263
|
-
pi.on("session_start", (_event, ctx) => {
|
|
264
|
-
if (ctx.mode !== "tui") return;
|
|
265
|
-
try {
|
|
266
|
-
ctx.ui.setTheme("killeros");
|
|
267
|
-
const startupTip = nextStartupTip();
|
|
268
|
-
ctx.ui.setHeader(() => {
|
|
269
|
-
activeHeader?.dispose();
|
|
270
|
-
activeHeader = new PiStartupHeader(pi, ctx, startupTip);
|
|
271
|
-
return activeHeader;
|
|
272
|
-
});
|
|
273
|
-
ctx.ui.setWorkingIndicator({
|
|
274
|
-
frames: [
|
|
275
|
-
ctx.ui.theme.fg("dim", "✻"),
|
|
276
|
-
ctx.ui.theme.fg("muted", "✻"),
|
|
277
|
-
ctx.ui.theme.fg("accent", "✻"),
|
|
278
|
-
ctx.ui.theme.fg("muted", "✻"),
|
|
279
|
-
],
|
|
280
|
-
intervalMs: 180,
|
|
281
|
-
});
|
|
282
|
-
ctx.ui.setHiddenThinkingLabel("└ Thinking…");
|
|
283
|
-
ctx.ui.setEditorComponent((tui, theme, keybindings) => new PiCodeEditor(tui, theme, keybindings));
|
|
284
|
-
} catch (error) {
|
|
285
|
-
reportError(ctx, "Killeros UI failed to initialize", error);
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
pi.on("agent_start", (_event, ctx) => {
|
|
290
|
-
if (ctx.mode !== "tui") return;
|
|
291
|
-
ctx.ui.setWorkingMessage(`${ACTIVITY_WORDS[activityWordIndex]}…`);
|
|
292
|
-
activityWordIndex = (activityWordIndex + 1) % ACTIVITY_WORDS.length;
|
|
293
|
-
});
|
|
294
|
-
|
|
295
|
-
pi.on("agent_end", (_event, ctx) => {
|
|
296
|
-
if (ctx.mode === "tui") ctx.ui.setWorkingMessage();
|
|
297
|
-
});
|
|
298
|
-
|
|
299
|
-
pi.on("session_shutdown", () => {
|
|
300
|
-
activeHeader?.dispose();
|
|
301
|
-
activeHeader = undefined;
|
|
302
|
-
activityWordIndex = 0;
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
export const CONCISE_SYSTEM_PROMPT = `
|
|
307
|
-
# Concise output rules
|
|
308
|
-
1. Start with the answer or next action; omit conversational preambles.
|
|
309
|
-
2. Use numbered steps only when order matters, with one bounded action per step.
|
|
310
|
-
3. Finish the primary task before mentioning optional follow-up work.
|
|
311
|
-
4. State failures directly and include the recovery action.
|
|
312
|
-
5. Keep lists focused; group long inventories under clear headings.
|
|
313
|
-
6. Do not invent time estimates, completion claims, or facts.
|
|
314
|
-
7. Preserve exact code, commands, paths, quoted text, warnings, and user-requested formats.
|
|
315
|
-
8. Omit recap sections and generic closing pleasantries.
|
|
316
|
-
`.trim();
|
|
317
|
-
|
|
318
|
-
export function isConcisedEnabled(): boolean {
|
|
319
|
-
return true;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
function registerConcisePrompt(pi: ExtensionAPI): void {
|
|
323
|
-
pi.on("before_agent_start", (event) => ({
|
|
324
|
-
systemPrompt: `${event.systemPrompt}\n\n${CONCISE_SYSTEM_PROMPT}`,
|
|
325
|
-
}));
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
const INIT_READ_ONLY_TOOLS = new Set(["read", "ls", "find", "grep"]);
|
|
329
|
-
|
|
330
|
-
interface InitWorkflowState {
|
|
331
|
-
active: boolean;
|
|
332
|
-
targetPath?: string;
|
|
333
|
-
writeAttempted: boolean;
|
|
334
|
-
writeSucceeded: boolean;
|
|
335
|
-
writeToolCallId?: string;
|
|
336
|
-
settle?: (writeSucceeded: boolean) => void;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
function resetInitState(state: InitWorkflowState): void {
|
|
340
|
-
state.active = false;
|
|
341
|
-
state.targetPath = undefined;
|
|
342
|
-
state.writeAttempted = false;
|
|
343
|
-
state.writeSucceeded = false;
|
|
344
|
-
state.writeToolCallId = undefined;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
const GOAL_ENTRY_TYPE = "killeros-goal";
|
|
348
|
-
const GOAL_CONTINUATION_TYPE = "killeros-goal-continuation";
|
|
349
|
-
const GOAL_OBJECTIVE_LIMIT = 4_000;
|
|
350
|
-
const GOAL_VERSION = 1;
|
|
351
|
-
|
|
352
|
-
type GoalStatus = "active" | "paused" | "blocked" | "complete";
|
|
353
|
-
type GoalEntryEvent = "set" | "replace" | "edit" | "turn" | "pause" | "resume" | "blocked" | "complete" | "error" | "clear" | "checkpoint";
|
|
354
|
-
|
|
355
|
-
interface GoalState {
|
|
356
|
-
version: 1;
|
|
357
|
-
revision: number;
|
|
358
|
-
objective: string;
|
|
359
|
-
status: GoalStatus;
|
|
360
|
-
createdAt: number;
|
|
361
|
-
updatedAt: number;
|
|
362
|
-
activeMilliseconds: number;
|
|
363
|
-
activeStartedAt?: number;
|
|
364
|
-
turns: number;
|
|
365
|
-
blockedAuditStartTurn: number;
|
|
366
|
-
baselineTokens: number;
|
|
367
|
-
result?: string;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
interface GoalEntryData {
|
|
371
|
-
version: 1;
|
|
372
|
-
event: GoalEntryEvent;
|
|
373
|
-
state: GoalState | null;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
interface GoalRuntime {
|
|
377
|
-
state?: GoalState;
|
|
378
|
-
continuationScheduled: boolean;
|
|
379
|
-
continuationHeld: boolean;
|
|
380
|
-
goalTurnInFlight: boolean;
|
|
381
|
-
agentEndObserved: boolean;
|
|
382
|
-
persistenceRetryNeeded: boolean;
|
|
383
|
-
lastStopReason?: string;
|
|
384
|
-
lastError?: string;
|
|
385
|
-
requestRender?: () => void;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
const GoalUpdateParams = Type.Object({
|
|
389
|
-
status: Type.Union([Type.Literal("complete"), Type.Literal("blocked")], {
|
|
390
|
-
description: "Mark the active goal complete or blocked",
|
|
391
|
-
}),
|
|
392
|
-
evidence: Type.String({
|
|
393
|
-
minLength: 1,
|
|
394
|
-
maxLength: 2_000,
|
|
395
|
-
description: "Concise evidence that the objective is complete, or the repeated blocker and attempted workarounds",
|
|
396
|
-
}),
|
|
397
|
-
});
|
|
398
|
-
|
|
399
|
-
interface GoalUpdateDetails {
|
|
400
|
-
status: "complete" | "blocked";
|
|
401
|
-
evidence: string;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
function isGoalStatus(value: unknown): value is GoalStatus {
|
|
405
|
-
return value === "active" || value === "paused" || value === "blocked" || value === "complete";
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
function finiteNonNegative(value: unknown): value is number {
|
|
409
|
-
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
function parseGoalState(value: unknown): GoalState | undefined {
|
|
413
|
-
if (!value || typeof value !== "object") return undefined;
|
|
414
|
-
const candidate = value as Partial<GoalState>;
|
|
415
|
-
if (candidate.version !== GOAL_VERSION
|
|
416
|
-
|| !Number.isInteger(candidate.revision) || (candidate.revision ?? 0) < 1
|
|
417
|
-
|| typeof candidate.objective !== "string" || !candidate.objective.trim()
|
|
418
|
-
|| [...candidate.objective].length > GOAL_OBJECTIVE_LIMIT
|
|
419
|
-
|| !isGoalStatus(candidate.status)
|
|
420
|
-
|| !finiteNonNegative(candidate.createdAt)
|
|
421
|
-
|| !finiteNonNegative(candidate.updatedAt)
|
|
422
|
-
|| !finiteNonNegative(candidate.activeMilliseconds)
|
|
423
|
-
|| !Number.isInteger(candidate.turns) || (candidate.turns ?? -1) < 0
|
|
424
|
-
|| candidate.blockedAuditStartTurn !== undefined
|
|
425
|
-
&& (!Number.isInteger(candidate.blockedAuditStartTurn) || candidate.blockedAuditStartTurn < 0 || candidate.blockedAuditStartTurn > candidate.turns!)
|
|
426
|
-
|| !finiteNonNegative(candidate.baselineTokens)
|
|
427
|
-
|| candidate.activeStartedAt !== undefined && !finiteNonNegative(candidate.activeStartedAt)
|
|
428
|
-
|| candidate.result !== undefined && typeof candidate.result !== "string") {
|
|
429
|
-
return undefined;
|
|
430
|
-
}
|
|
431
|
-
return {
|
|
432
|
-
version: GOAL_VERSION,
|
|
433
|
-
revision: candidate.revision!,
|
|
434
|
-
objective: candidate.objective.trim(),
|
|
435
|
-
status: candidate.status,
|
|
436
|
-
createdAt: candidate.createdAt,
|
|
437
|
-
updatedAt: candidate.updatedAt,
|
|
438
|
-
activeMilliseconds: candidate.activeMilliseconds,
|
|
439
|
-
activeStartedAt: candidate.activeStartedAt,
|
|
440
|
-
turns: candidate.turns!,
|
|
441
|
-
blockedAuditStartTurn: candidate.blockedAuditStartTurn ?? 0,
|
|
442
|
-
baselineTokens: candidate.baselineTokens,
|
|
443
|
-
result: candidate.result,
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
function goalBranchEntries(ctx: ExtensionContext): ReturnType<ExtensionContext["sessionManager"]["getEntries"]> {
|
|
448
|
-
try {
|
|
449
|
-
return ctx.sessionManager.getBranch();
|
|
450
|
-
} catch {
|
|
451
|
-
return [];
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
function restoreGoalState(ctx: ExtensionContext): GoalState | undefined {
|
|
456
|
-
const entries = goalBranchEntries(ctx);
|
|
457
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
458
|
-
const entry = entries[index];
|
|
459
|
-
if (entry?.type !== "custom" || entry.customType !== GOAL_ENTRY_TYPE) continue;
|
|
460
|
-
const data = entry.data as Partial<GoalEntryData> | undefined;
|
|
461
|
-
if (!data || data.version !== GOAL_VERSION) return undefined;
|
|
462
|
-
if (data.state === null) return undefined;
|
|
463
|
-
const restored = parseGoalState(data.state);
|
|
464
|
-
if (!restored) return undefined;
|
|
465
|
-
return restored.status === "active"
|
|
466
|
-
? { ...restored, activeStartedAt: Date.now() }
|
|
467
|
-
: { ...restored, activeStartedAt: undefined };
|
|
468
|
-
}
|
|
469
|
-
return undefined;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
function goalElapsedMilliseconds(state: GoalState, now = Date.now()): number {
|
|
473
|
-
const activeInterval = state.status === "active" && state.activeStartedAt !== undefined
|
|
474
|
-
? Math.max(0, now - state.activeStartedAt)
|
|
475
|
-
: 0;
|
|
476
|
-
return state.activeMilliseconds + activeInterval;
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
function stopGoalClock(state: GoalState, now: number): GoalState {
|
|
480
|
-
if (state.status !== "active" || state.activeStartedAt === undefined) return state;
|
|
481
|
-
return {
|
|
482
|
-
...state,
|
|
483
|
-
activeMilliseconds: state.activeMilliseconds + Math.max(0, now - state.activeStartedAt),
|
|
484
|
-
activeStartedAt: undefined,
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function sumGoalTokens(ctx: ExtensionContext): number {
|
|
489
|
-
let total = 0;
|
|
490
|
-
for (const entry of goalBranchEntries(ctx)) {
|
|
491
|
-
if (entry.type === "message" && (entry.message.role === "assistant" || entry.message.role === "toolResult")) {
|
|
492
|
-
total += entry.message.usage?.totalTokens ?? 0;
|
|
493
|
-
} else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
|
|
494
|
-
total += entry.usage.totalTokens;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
return total;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
function persistGoalState(
|
|
501
|
-
pi: ExtensionAPI,
|
|
502
|
-
runtime: GoalRuntime,
|
|
503
|
-
event: GoalEntryEvent,
|
|
504
|
-
state: GoalState | undefined,
|
|
505
|
-
): void {
|
|
506
|
-
const data: GoalEntryData = { version: GOAL_VERSION, event, state: state ?? null };
|
|
507
|
-
pi.appendEntry(GOAL_ENTRY_TYPE, data);
|
|
508
|
-
runtime.state = state;
|
|
509
|
-
runtime.persistenceRetryNeeded = false;
|
|
510
|
-
runtime.requestRender?.();
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
function transitionGoal(
|
|
514
|
-
pi: ExtensionAPI,
|
|
515
|
-
runtime: GoalRuntime,
|
|
516
|
-
event: GoalEntryEvent,
|
|
517
|
-
status: GoalStatus,
|
|
518
|
-
result?: string,
|
|
519
|
-
resetBlockedAudit = false,
|
|
520
|
-
): GoalState {
|
|
521
|
-
const current = runtime.state;
|
|
522
|
-
if (!current) throw new Error("No goal is set");
|
|
523
|
-
const now = Date.now();
|
|
524
|
-
const stopped = stopGoalClock(current, now);
|
|
525
|
-
const next: GoalState = {
|
|
526
|
-
...stopped,
|
|
527
|
-
revision: stopped.revision + 1,
|
|
528
|
-
status,
|
|
529
|
-
updatedAt: now,
|
|
530
|
-
activeStartedAt: status === "active" ? now : undefined,
|
|
531
|
-
blockedAuditStartTurn: resetBlockedAudit ? stopped.turns : stopped.blockedAuditStartTurn,
|
|
532
|
-
result,
|
|
533
|
-
};
|
|
534
|
-
persistGoalState(pi, runtime, event, next);
|
|
535
|
-
if (status !== "active") runtime.continuationScheduled = false;
|
|
536
|
-
return next;
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
function goalStatusLabel(status: GoalStatus): string {
|
|
540
|
-
return `${status.charAt(0).toLocaleUpperCase()}${status.slice(1)}`;
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
function goalStatusSummary(state: GoalState, ctx: ExtensionContext): string {
|
|
544
|
-
const usedTokens = Math.max(0, sumGoalTokens(ctx) - state.baselineTokens);
|
|
545
|
-
const lines = [
|
|
546
|
-
`Goal ${goalStatusLabel(state.status).toLocaleLowerCase()} · ${state.turns} turn${state.turns === 1 ? "" : "s"} · ${formatTime(goalElapsedMilliseconds(state))} · ${formatTokens(usedTokens)} tokens`,
|
|
547
|
-
state.objective,
|
|
548
|
-
];
|
|
549
|
-
if (state.result) lines.push(state.result);
|
|
550
|
-
return lines.join("\n");
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
function pauseGoalAfterFailure(
|
|
554
|
-
pi: ExtensionAPI,
|
|
555
|
-
runtime: GoalRuntime,
|
|
556
|
-
ctx: ExtensionContext,
|
|
557
|
-
reason: string,
|
|
558
|
-
recoveryInstruction = "Run /goal resume after resolving the problem.",
|
|
559
|
-
): void {
|
|
560
|
-
if (runtime.state?.status !== "active") return;
|
|
561
|
-
try {
|
|
562
|
-
transitionGoal(pi, runtime, "error", "paused", reason);
|
|
563
|
-
} catch {
|
|
564
|
-
runtime.state = runtime.state ? { ...stopGoalClock(runtime.state, Date.now()), status: "paused", result: reason } : undefined;
|
|
565
|
-
runtime.persistenceRetryNeeded = true;
|
|
566
|
-
runtime.continuationScheduled = false;
|
|
567
|
-
runtime.requestRender?.();
|
|
568
|
-
}
|
|
569
|
-
ctx.ui.notify(`Goal paused: ${reason}\n${recoveryInstruction}`, "error");
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
function scheduleGoalContinuation(
|
|
573
|
-
pi: ExtensionAPI,
|
|
574
|
-
runtime: GoalRuntime,
|
|
575
|
-
initState: InitWorkflowState,
|
|
576
|
-
ctx: ExtensionContext,
|
|
577
|
-
): void {
|
|
578
|
-
if (!isGoalModeSupported(ctx)
|
|
579
|
-
|| !isSavedSession(ctx)
|
|
580
|
-
|| runtime.state?.status !== "active"
|
|
581
|
-
|| runtime.continuationScheduled
|
|
582
|
-
|| runtime.continuationHeld
|
|
583
|
-
|| initState.active
|
|
584
|
-
|| ctx.hasPendingMessages()) return;
|
|
585
|
-
const current = runtime.state;
|
|
586
|
-
const now = Date.now();
|
|
587
|
-
const next: GoalState = {
|
|
588
|
-
...current,
|
|
589
|
-
revision: current.revision + 1,
|
|
590
|
-
turns: current.turns + 1,
|
|
591
|
-
updatedAt: now,
|
|
592
|
-
activeStartedAt: current.activeStartedAt ?? now,
|
|
593
|
-
};
|
|
594
|
-
try {
|
|
595
|
-
persistGoalState(pi, runtime, "turn", next);
|
|
596
|
-
} catch (error) {
|
|
597
|
-
pauseGoalAfterFailure(pi, runtime, ctx, `continuation state could not be saved: ${error instanceof Error ? error.message : String(error)}`);
|
|
598
|
-
return;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
runtime.continuationScheduled = true;
|
|
602
|
-
runtime.goalTurnInFlight = true;
|
|
603
|
-
runtime.agentEndObserved = false;
|
|
604
|
-
runtime.lastStopReason = undefined;
|
|
605
|
-
runtime.lastError = undefined;
|
|
606
|
-
try {
|
|
607
|
-
pi.sendMessage({
|
|
608
|
-
customType: GOAL_CONTINUATION_TYPE,
|
|
609
|
-
content: goalContinuationMessage(next, ctx),
|
|
610
|
-
display: false,
|
|
611
|
-
}, { triggerTurn: true, deliverAs: "followUp" });
|
|
612
|
-
} catch (error) {
|
|
613
|
-
runtime.continuationScheduled = false;
|
|
614
|
-
runtime.goalTurnInFlight = false;
|
|
615
|
-
pauseGoalAfterFailure(pi, runtime, ctx, `continuation could not start: ${error instanceof Error ? error.message : String(error)}`);
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
function goalInstructions(state: GoalState, heading: string): string {
|
|
620
|
-
return [
|
|
621
|
-
`# ${heading}`,
|
|
622
|
-
`Status: active · Turn: ${state.turns}`,
|
|
623
|
-
"Objective:",
|
|
624
|
-
state.objective,
|
|
625
|
-
"",
|
|
626
|
-
"Continue making concrete progress toward this unchanged objective. Re-check repository state and prior results instead of repeating work.",
|
|
627
|
-
"Do not stop merely because one response is complete: KillerOS will start another goal turn while the goal remains active.",
|
|
628
|
-
"Before declaring completion, audit every part of the objective and verify the relevant results. Then call killeros_goal_update with status complete and concise evidence.",
|
|
629
|
-
"Call killeros_goal_update with status blocked only when the same external impasse has prevented progress for three consecutive goal turns; name the blocker and attempted workarounds.",
|
|
630
|
-
"Never use the goal tool to pause, resume, edit, replace, or clear the objective. Those transitions belong to the user.",
|
|
631
|
-
].join("\n");
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
function goalSystemPrompt(state: GoalState): string {
|
|
635
|
-
return goalInstructions(state, "Active KillerOS goal");
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
function goalContinuationMessage(state: GoalState, ctx: ExtensionContext): string {
|
|
639
|
-
const sections = [goalInstructions(state, "KillerOS long-running goal turn")];
|
|
640
|
-
if (ctx.isProjectTrusted()) {
|
|
641
|
-
const personal = resolvePersonalInstructions(ctx.cwd);
|
|
642
|
-
if (personal) {
|
|
643
|
-
sections.push(`<personal_instructions source=${JSON.stringify(personal.source)}>\n${personal.content}\n</personal_instructions>`);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
sections.push(CONCISE_SYSTEM_PROMPT);
|
|
647
|
-
return sections.join("\n\n");
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
function isGoalModeSupported(ctx: ExtensionContext): boolean {
|
|
651
|
-
return ctx.mode === "tui" || ctx.mode === "rpc";
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
function isSavedSession(ctx: ExtensionContext): boolean {
|
|
655
|
-
try {
|
|
656
|
-
return Boolean(ctx.sessionManager.getSessionFile());
|
|
657
|
-
} catch {
|
|
658
|
-
return false;
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
function validateGoalObjective(input: string): string | undefined {
|
|
663
|
-
const objective = input.trim();
|
|
664
|
-
if (!objective) return undefined;
|
|
665
|
-
return [...objective].length <= GOAL_OBJECTIVE_LIMIT ? objective : undefined;
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
function registerGoal(
|
|
669
|
-
pi: ExtensionAPI,
|
|
670
|
-
runtime: GoalRuntime,
|
|
671
|
-
initState: InitWorkflowState,
|
|
672
|
-
): void {
|
|
673
|
-
pi.registerEntryRenderer<GoalEntryData>(GOAL_ENTRY_TYPE, (entry, _options, theme) => {
|
|
674
|
-
const data = entry.data;
|
|
675
|
-
if (!data || data.version !== GOAL_VERSION || data.event === "turn" || data.event === "checkpoint") return undefined;
|
|
676
|
-
if (data.event === "clear" || data.state === null) return new Text(theme.fg("dim", "Goal cleared"), 0, 0);
|
|
677
|
-
const state = parseGoalState(data.state);
|
|
678
|
-
if (!state) return undefined;
|
|
679
|
-
const icon = state.status === "active" ? "✻" : state.status === "paused" ? "Ⅱ" : state.status === "blocked" ? "!" : "✓";
|
|
680
|
-
const color: ThemeColor = state.status === "active" ? "accent" : state.status === "paused" ? "warning" : state.status === "blocked" ? "error" : "success";
|
|
681
|
-
return new Text(`${theme.fg(color, `${icon} Goal ${state.status}`)}${theme.fg("dim", ` · ${state.objective}`)}`, 0, 0);
|
|
682
|
-
});
|
|
683
|
-
|
|
684
|
-
pi.registerTool<typeof GoalUpdateParams, GoalUpdateDetails>({
|
|
685
|
-
name: "killeros_goal_update",
|
|
686
|
-
label: "Goal update",
|
|
687
|
-
description: "Mark the active KillerOS long-running goal complete after verification, or blocked after the same impasse persists for three consecutive goal turns.",
|
|
688
|
-
parameters: GoalUpdateParams,
|
|
689
|
-
executionMode: "sequential",
|
|
690
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
691
|
-
if (!isGoalModeSupported(ctx)) throw new Error("KillerOS goals require TUI or RPC mode");
|
|
692
|
-
if (!isSavedSession(ctx)) throw new Error("KillerOS goals require a saved session");
|
|
693
|
-
const state = runtime.state;
|
|
694
|
-
if (!state || state.status !== "active") throw new Error("There is no active KillerOS goal to update");
|
|
695
|
-
const evidence = params.evidence.trim();
|
|
696
|
-
if (!evidence) throw new Error("Goal evidence must not be empty");
|
|
697
|
-
if (params.status === "blocked" && state.turns - state.blockedAuditStartTurn < 3) {
|
|
698
|
-
throw new Error("A goal cannot be marked blocked before three goal turns in the current audit; keep working and audit the same blocker again");
|
|
699
|
-
}
|
|
700
|
-
transitionGoal(pi, runtime, params.status, params.status, evidence);
|
|
701
|
-
return {
|
|
702
|
-
content: [{ type: "text", text: `Goal marked ${params.status}: ${evidence}` }],
|
|
703
|
-
details: { status: params.status, evidence },
|
|
704
|
-
};
|
|
705
|
-
},
|
|
706
|
-
renderCall(args, theme) {
|
|
707
|
-
return new Text(`${theme.fg("toolTitle", theme.bold("goal "))}${theme.fg("muted", args.status)}`, 0, 0);
|
|
708
|
-
},
|
|
709
|
-
renderResult(result, _options, theme) {
|
|
710
|
-
const details = result.details;
|
|
711
|
-
return new Text(details
|
|
712
|
-
? `${theme.fg(details.status === "complete" ? "success" : "warning", details.status === "complete" ? "✓ Complete" : "! Blocked")}${theme.fg("dim", ` · ${details.evidence}`)}`
|
|
713
|
-
: theme.fg("dim", "Goal updated"), 0, 0);
|
|
714
|
-
},
|
|
715
|
-
});
|
|
716
|
-
|
|
717
|
-
pi.on("session_start", (_event, ctx) => {
|
|
718
|
-
runtime.state = restoreGoalState(ctx);
|
|
719
|
-
runtime.continuationScheduled = false;
|
|
720
|
-
runtime.continuationHeld = false;
|
|
721
|
-
runtime.goalTurnInFlight = false;
|
|
722
|
-
runtime.agentEndObserved = false;
|
|
723
|
-
runtime.persistenceRetryNeeded = false;
|
|
724
|
-
runtime.lastStopReason = undefined;
|
|
725
|
-
runtime.lastError = undefined;
|
|
726
|
-
runtime.requestRender?.();
|
|
727
|
-
if (runtime.state?.status === "active") {
|
|
728
|
-
setImmediate(() => scheduleGoalContinuation(pi, runtime, initState, ctx));
|
|
729
|
-
}
|
|
730
|
-
});
|
|
731
|
-
|
|
732
|
-
pi.on("session_tree", (_event, ctx) => {
|
|
733
|
-
runtime.state = restoreGoalState(ctx);
|
|
734
|
-
runtime.continuationScheduled = false;
|
|
735
|
-
runtime.continuationHeld = false;
|
|
736
|
-
runtime.goalTurnInFlight = false;
|
|
737
|
-
runtime.agentEndObserved = false;
|
|
738
|
-
runtime.persistenceRetryNeeded = false;
|
|
739
|
-
runtime.lastStopReason = undefined;
|
|
740
|
-
runtime.lastError = undefined;
|
|
741
|
-
runtime.requestRender?.();
|
|
742
|
-
if (runtime.state?.status === "active") {
|
|
743
|
-
setImmediate(() => scheduleGoalContinuation(pi, runtime, initState, ctx));
|
|
744
|
-
}
|
|
745
|
-
});
|
|
746
|
-
|
|
747
|
-
pi.on("session_shutdown", (_event, ctx) => {
|
|
748
|
-
if (runtime.state?.status === "active") {
|
|
749
|
-
const now = Date.now();
|
|
750
|
-
const checkpoint: GoalState = {
|
|
751
|
-
...stopGoalClock(runtime.state, now),
|
|
752
|
-
revision: runtime.state.revision + 1,
|
|
753
|
-
updatedAt: now,
|
|
754
|
-
};
|
|
755
|
-
try {
|
|
756
|
-
persistGoalState(pi, runtime, "checkpoint", checkpoint);
|
|
757
|
-
} catch (error) {
|
|
758
|
-
reportError(ctx, "Goal state could not be checkpointed", error);
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
runtime.state = undefined;
|
|
762
|
-
runtime.continuationScheduled = false;
|
|
763
|
-
runtime.continuationHeld = false;
|
|
764
|
-
runtime.goalTurnInFlight = false;
|
|
765
|
-
runtime.agentEndObserved = false;
|
|
766
|
-
runtime.persistenceRetryNeeded = false;
|
|
767
|
-
runtime.lastStopReason = undefined;
|
|
768
|
-
runtime.lastError = undefined;
|
|
769
|
-
});
|
|
770
|
-
|
|
771
|
-
pi.on("before_agent_start", (event, ctx) => {
|
|
772
|
-
runtime.continuationScheduled = false;
|
|
773
|
-
const current = runtime.state;
|
|
774
|
-
if (!isGoalModeSupported(ctx) || !isSavedSession(ctx) || !current || current.status !== "active" || initState.active) return;
|
|
775
|
-
const now = Date.now();
|
|
776
|
-
const next: GoalState = {
|
|
777
|
-
...current,
|
|
778
|
-
revision: current.revision + 1,
|
|
779
|
-
turns: current.turns + 1,
|
|
780
|
-
updatedAt: now,
|
|
781
|
-
activeStartedAt: current.activeStartedAt ?? now,
|
|
782
|
-
};
|
|
783
|
-
try {
|
|
784
|
-
persistGoalState(pi, runtime, "turn", next);
|
|
785
|
-
} catch (error) {
|
|
786
|
-
pauseGoalAfterFailure(pi, runtime, ctx, `turn state could not be saved: ${error instanceof Error ? error.message : String(error)}`);
|
|
787
|
-
return;
|
|
788
|
-
}
|
|
789
|
-
runtime.goalTurnInFlight = true;
|
|
790
|
-
runtime.agentEndObserved = false;
|
|
791
|
-
runtime.lastStopReason = undefined;
|
|
792
|
-
runtime.lastError = undefined;
|
|
793
|
-
return { systemPrompt: `${event.systemPrompt}\n\n${goalSystemPrompt(next)}` };
|
|
794
|
-
});
|
|
795
|
-
|
|
796
|
-
pi.on("agent_end", (event) => {
|
|
797
|
-
if (!runtime.goalTurnInFlight) return;
|
|
798
|
-
const finalAssistant = [...event.messages].reverse().find((message) => message.role === "assistant");
|
|
799
|
-
runtime.agentEndObserved = finalAssistant !== undefined;
|
|
800
|
-
runtime.lastStopReason = finalAssistant?.stopReason;
|
|
801
|
-
runtime.lastError = finalAssistant?.errorMessage;
|
|
802
|
-
});
|
|
803
|
-
|
|
804
|
-
pi.registerCommand("goal", {
|
|
805
|
-
description: "Set or view the goal for a long-running task",
|
|
806
|
-
getArgumentCompletions: (prefix) => {
|
|
807
|
-
const normalized = prefix.trimStart().toLocaleLowerCase();
|
|
808
|
-
if (normalized.includes(" ")) return null;
|
|
809
|
-
const actions = [
|
|
810
|
-
{ value: "clear", description: "Remove the current goal" },
|
|
811
|
-
{ value: "edit", description: "Edit and reactivate the current goal" },
|
|
812
|
-
{ value: "pause", description: "Stop automatic continuation" },
|
|
813
|
-
{ value: "resume", description: "Resume automatic continuation" },
|
|
814
|
-
];
|
|
815
|
-
return actions
|
|
816
|
-
.filter((action) => action.value.startsWith(normalized))
|
|
817
|
-
.map((action) => ({ ...action, label: action.value }));
|
|
818
|
-
},
|
|
819
|
-
handler: async (args, ctx) => {
|
|
820
|
-
if (ctx.mode === "print" || ctx.mode === "json") {
|
|
821
|
-
ctx.ui.notify("/goal requires TUI or RPC mode", "error");
|
|
822
|
-
return;
|
|
823
|
-
}
|
|
824
|
-
if (!isSavedSession(ctx)) {
|
|
825
|
-
ctx.ui.notify("/goal requires a saved session", "error");
|
|
826
|
-
return;
|
|
827
|
-
}
|
|
828
|
-
const input = args.trim();
|
|
829
|
-
const control = input.toLocaleLowerCase();
|
|
830
|
-
const isControl = control === "clear" || control === "edit" || control === "pause" || control === "resume";
|
|
831
|
-
|
|
832
|
-
if (!input) {
|
|
833
|
-
if (!runtime.state) {
|
|
834
|
-
ctx.ui.notify("No goal is set. Use /goal <objective> to start a long-running task.", "info");
|
|
835
|
-
return;
|
|
836
|
-
}
|
|
837
|
-
ctx.ui.notify(goalStatusSummary(runtime.state, ctx), "info");
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
if (control === "clear") {
|
|
842
|
-
if (!runtime.state) {
|
|
843
|
-
ctx.ui.notify("No goal is set", "info");
|
|
844
|
-
return;
|
|
845
|
-
}
|
|
846
|
-
try {
|
|
847
|
-
persistGoalState(pi, runtime, "clear", undefined);
|
|
848
|
-
runtime.continuationScheduled = false;
|
|
849
|
-
ctx.ui.notify("Goal cleared", "info");
|
|
850
|
-
} catch (error) {
|
|
851
|
-
if (runtime.state?.status === "active") {
|
|
852
|
-
pauseGoalAfterFailure(
|
|
853
|
-
pi,
|
|
854
|
-
runtime,
|
|
855
|
-
ctx,
|
|
856
|
-
`the requested clear could not be saved: ${error instanceof Error ? error.message : String(error)}`,
|
|
857
|
-
"Automatic continuation is stopped. Retry /goal clear to remove the goal.",
|
|
858
|
-
);
|
|
859
|
-
} else {
|
|
860
|
-
reportError(ctx, "Goal could not be cleared", error);
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
if (control === "pause") {
|
|
867
|
-
if (!runtime.state) {
|
|
868
|
-
ctx.ui.notify("No goal is set", "info");
|
|
869
|
-
return;
|
|
870
|
-
}
|
|
871
|
-
if (runtime.state.status === "paused") {
|
|
872
|
-
if (!runtime.persistenceRetryNeeded) {
|
|
873
|
-
ctx.ui.notify("Goal is already paused", "info");
|
|
874
|
-
return;
|
|
875
|
-
}
|
|
876
|
-
const now = Date.now();
|
|
877
|
-
const checkpoint: GoalState = {
|
|
878
|
-
...runtime.state,
|
|
879
|
-
revision: runtime.state.revision + 1,
|
|
880
|
-
updatedAt: now,
|
|
881
|
-
};
|
|
882
|
-
try {
|
|
883
|
-
persistGoalState(pi, runtime, "pause", checkpoint);
|
|
884
|
-
ctx.ui.notify("Goal pause saved", "info");
|
|
885
|
-
} catch (error) {
|
|
886
|
-
reportError(ctx, "Goal pause still could not be saved", error);
|
|
887
|
-
}
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
if (runtime.state.status !== "active") {
|
|
891
|
-
ctx.ui.notify(`Goal is ${runtime.state.status}; only an active goal can be paused`, "warning");
|
|
892
|
-
return;
|
|
893
|
-
}
|
|
894
|
-
try {
|
|
895
|
-
transitionGoal(pi, runtime, "pause", "paused");
|
|
896
|
-
ctx.ui.notify("Goal paused. Run /goal resume to continue.", "info");
|
|
897
|
-
} catch (error) {
|
|
898
|
-
pauseGoalAfterFailure(
|
|
899
|
-
pi,
|
|
900
|
-
runtime,
|
|
901
|
-
ctx,
|
|
902
|
-
`the requested pause could not be saved: ${error instanceof Error ? error.message : String(error)}`,
|
|
903
|
-
"Automatic continuation is stopped. If session storage is still unavailable, retry /goal pause after it recovers.",
|
|
904
|
-
);
|
|
905
|
-
}
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
if (control === "resume") {
|
|
910
|
-
if (initState.active) {
|
|
911
|
-
ctx.ui.notify("Wait for /init to finish before resuming a goal", "error");
|
|
912
|
-
return;
|
|
913
|
-
}
|
|
914
|
-
if (!runtime.state) {
|
|
915
|
-
ctx.ui.notify("No goal is set", "info");
|
|
916
|
-
return;
|
|
917
|
-
}
|
|
918
|
-
if (runtime.state.status === "active") {
|
|
919
|
-
ctx.ui.notify("Goal is already active", "info");
|
|
920
|
-
return;
|
|
921
|
-
}
|
|
922
|
-
if (runtime.state.status === "complete") {
|
|
923
|
-
ctx.ui.notify("The goal is complete. Set a new objective or use /goal edit.", "info");
|
|
924
|
-
return;
|
|
925
|
-
}
|
|
926
|
-
try {
|
|
927
|
-
transitionGoal(pi, runtime, "resume", "active", undefined, true);
|
|
928
|
-
runtime.continuationScheduled = false;
|
|
929
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
930
|
-
ctx.ui.notify("Goal resumed", "info");
|
|
931
|
-
} catch (error) {
|
|
932
|
-
reportError(ctx, "Goal could not be resumed", error);
|
|
933
|
-
}
|
|
934
|
-
return;
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
if (control === "edit") {
|
|
938
|
-
if (initState.active) {
|
|
939
|
-
ctx.ui.notify("Wait for /init to finish before editing a goal", "error");
|
|
940
|
-
return;
|
|
941
|
-
}
|
|
942
|
-
if (!runtime.state) {
|
|
943
|
-
ctx.ui.notify("No goal is set", "info");
|
|
944
|
-
return;
|
|
945
|
-
}
|
|
946
|
-
if (ctx.mode !== "tui") {
|
|
947
|
-
ctx.ui.notify("/goal edit requires interactive TUI mode", "error");
|
|
948
|
-
return;
|
|
949
|
-
}
|
|
950
|
-
runtime.continuationHeld = true;
|
|
951
|
-
let waitError: unknown;
|
|
952
|
-
try {
|
|
953
|
-
await ctx.waitForIdle();
|
|
954
|
-
} catch (error) {
|
|
955
|
-
waitError = error;
|
|
956
|
-
} finally {
|
|
957
|
-
runtime.continuationHeld = false;
|
|
958
|
-
}
|
|
959
|
-
if (waitError) {
|
|
960
|
-
reportError(ctx, "Goal could not wait for the active turn", waitError);
|
|
961
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
962
|
-
return;
|
|
963
|
-
}
|
|
964
|
-
const edited = await ctx.ui.editor("Edit long-running goal", runtime.state.objective);
|
|
965
|
-
if (edited === undefined) {
|
|
966
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
967
|
-
return;
|
|
968
|
-
}
|
|
969
|
-
const objective = validateGoalObjective(edited);
|
|
970
|
-
if (!objective) {
|
|
971
|
-
ctx.ui.notify(edited.trim() ? "A goal objective may not exceed 4,000 characters" : "A goal objective may not be empty", "error");
|
|
972
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
const now = Date.now();
|
|
976
|
-
const current = stopGoalClock(runtime.state, now);
|
|
977
|
-
const next: GoalState = {
|
|
978
|
-
...current,
|
|
979
|
-
revision: current.revision + 1,
|
|
980
|
-
objective,
|
|
981
|
-
status: "active",
|
|
982
|
-
updatedAt: now,
|
|
983
|
-
activeStartedAt: now,
|
|
984
|
-
blockedAuditStartTurn: current.turns,
|
|
985
|
-
result: undefined,
|
|
986
|
-
};
|
|
987
|
-
try {
|
|
988
|
-
persistGoalState(pi, runtime, "edit", next);
|
|
989
|
-
runtime.continuationScheduled = false;
|
|
990
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
991
|
-
ctx.ui.notify("Goal updated and active", "info");
|
|
992
|
-
} catch (error) {
|
|
993
|
-
reportError(ctx, "Goal could not be edited", error);
|
|
994
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
995
|
-
}
|
|
996
|
-
return;
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
if (isControl) return;
|
|
1000
|
-
if (initState.active) {
|
|
1001
|
-
ctx.ui.notify("Wait for /init to finish before starting a goal", "error");
|
|
1002
|
-
return;
|
|
1003
|
-
}
|
|
1004
|
-
const objective = validateGoalObjective(input);
|
|
1005
|
-
if (!objective) {
|
|
1006
|
-
ctx.ui.notify(input ? "A goal objective may not exceed 4,000 characters" : "A goal objective may not be empty", "error");
|
|
1007
|
-
return;
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
const unfinished = runtime.state && runtime.state.status !== "complete";
|
|
1011
|
-
if (unfinished) {
|
|
1012
|
-
if (!ctx.hasUI) {
|
|
1013
|
-
ctx.ui.notify("Clear the current goal before replacing it outside TUI mode", "error");
|
|
1014
|
-
return;
|
|
1015
|
-
}
|
|
1016
|
-
const replace = await ctx.ui.confirm("Replace active goal", "Replace the current unfinished goal and discard its continuation state?");
|
|
1017
|
-
if (!replace) return;
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
runtime.continuationHeld = true;
|
|
1021
|
-
let waitError: unknown;
|
|
1022
|
-
try {
|
|
1023
|
-
await ctx.waitForIdle();
|
|
1024
|
-
} catch (error) {
|
|
1025
|
-
waitError = error;
|
|
1026
|
-
} finally {
|
|
1027
|
-
runtime.continuationHeld = false;
|
|
1028
|
-
}
|
|
1029
|
-
if (waitError) {
|
|
1030
|
-
reportError(ctx, "Goal could not wait for the active turn", waitError);
|
|
1031
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
1032
|
-
return;
|
|
1033
|
-
}
|
|
1034
|
-
const now = Date.now();
|
|
1035
|
-
const state: GoalState = {
|
|
1036
|
-
version: GOAL_VERSION,
|
|
1037
|
-
revision: 1,
|
|
1038
|
-
objective,
|
|
1039
|
-
status: "active",
|
|
1040
|
-
createdAt: now,
|
|
1041
|
-
updatedAt: now,
|
|
1042
|
-
activeMilliseconds: 0,
|
|
1043
|
-
activeStartedAt: now,
|
|
1044
|
-
turns: 0,
|
|
1045
|
-
blockedAuditStartTurn: 0,
|
|
1046
|
-
baselineTokens: sumGoalTokens(ctx),
|
|
1047
|
-
};
|
|
1048
|
-
try {
|
|
1049
|
-
persistGoalState(pi, runtime, unfinished ? "replace" : "set", state);
|
|
1050
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
1051
|
-
ctx.ui.notify("Goal active. KillerOS will continue until completion, a repeated blocker, or pause.", "info");
|
|
1052
|
-
} catch (error) {
|
|
1053
|
-
reportError(ctx, "Goal could not be started", error);
|
|
1054
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
1055
|
-
}
|
|
1056
|
-
},
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
function registerGoalSettlement(
|
|
1061
|
-
pi: ExtensionAPI,
|
|
1062
|
-
runtime: GoalRuntime,
|
|
1063
|
-
initState: InitWorkflowState,
|
|
1064
|
-
): void {
|
|
1065
|
-
pi.on("agent_settled", (_event, ctx) => {
|
|
1066
|
-
const wasGoalTurn = runtime.goalTurnInFlight;
|
|
1067
|
-
const agentEndObserved = runtime.agentEndObserved;
|
|
1068
|
-
runtime.goalTurnInFlight = false;
|
|
1069
|
-
runtime.agentEndObserved = false;
|
|
1070
|
-
runtime.continuationScheduled = false;
|
|
1071
|
-
if (!wasGoalTurn || runtime.state?.status !== "active" || initState.active) return;
|
|
1072
|
-
if (!agentEndObserved) {
|
|
1073
|
-
pauseGoalAfterFailure(pi, runtime, ctx, "the goal turn ended without an agent result");
|
|
1074
|
-
return;
|
|
1075
|
-
}
|
|
1076
|
-
if (runtime.lastStopReason === "error" || runtime.lastStopReason === "aborted") {
|
|
1077
|
-
const reason = runtime.lastError || (runtime.lastStopReason === "aborted" ? "the agent turn was aborted" : "the agent turn failed");
|
|
1078
|
-
runtime.lastStopReason = undefined;
|
|
1079
|
-
runtime.lastError = undefined;
|
|
1080
|
-
pauseGoalAfterFailure(pi, runtime, ctx, reason);
|
|
1081
|
-
return;
|
|
1082
|
-
}
|
|
1083
|
-
runtime.lastStopReason = undefined;
|
|
1084
|
-
runtime.lastError = undefined;
|
|
1085
|
-
scheduleGoalContinuation(pi, runtime, initState, ctx);
|
|
1086
|
-
});
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
const OptionSchema = Type.Object({
|
|
1090
|
-
label: Type.String({ minLength: 1, maxLength: 200, description: "Display label for the option" }),
|
|
1091
|
-
description: Type.Optional(Type.String({ maxLength: 500, description: "Optional detail shown for the selected option" })),
|
|
1092
|
-
preview: Type.Optional(Type.String({ maxLength: 8_000, description: "Optional markdown proposal preview shown for the selected option" })),
|
|
1093
|
-
});
|
|
1094
|
-
|
|
1095
|
-
const QuestionParams = Type.Object({
|
|
1096
|
-
question: Type.String({ minLength: 1, maxLength: 1_000, description: "The question to ask the user" }),
|
|
1097
|
-
options: Type.Array(OptionSchema, {
|
|
1098
|
-
minItems: 1,
|
|
1099
|
-
maxItems: 9,
|
|
1100
|
-
description: "Between 1 and 9 options for the user to choose from",
|
|
1101
|
-
}),
|
|
1102
|
-
});
|
|
1103
|
-
|
|
1104
|
-
interface DisplayOption {
|
|
1105
|
-
label: string;
|
|
1106
|
-
description?: string;
|
|
1107
|
-
preview?: string;
|
|
1108
|
-
originalIndex: number;
|
|
1109
|
-
isOther: boolean;
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
interface QuestionDetails {
|
|
1113
|
-
question: string;
|
|
1114
|
-
options: string[];
|
|
1115
|
-
answer: string | null;
|
|
1116
|
-
selectedIndex?: number;
|
|
1117
|
-
wasCustom?: boolean;
|
|
1118
|
-
cancelled?: boolean;
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
type QuestionSelection =
|
|
1122
|
-
| { kind: "selected"; answer: string; originalIndex: number }
|
|
1123
|
-
| { kind: "custom"; answer: string }
|
|
1124
|
-
| { kind: "cancelled" }
|
|
1125
|
-
| { kind: "aborted" };
|
|
1126
|
-
|
|
1127
|
-
const customInputHistory: string[] = [];
|
|
1128
|
-
|
|
1129
|
-
function rememberCustomInput(value: string): void {
|
|
1130
|
-
const existingIndex = customInputHistory.indexOf(value);
|
|
1131
|
-
if (existingIndex >= 0) customInputHistory.splice(existingIndex, 1);
|
|
1132
|
-
customInputHistory.push(value);
|
|
1133
|
-
if (customInputHistory.length > 100) customInputHistory.shift();
|
|
1134
|
-
}
|
|
1135
|
-
|
|
1136
|
-
function isPrintableInput(data: string): boolean {
|
|
1137
|
-
return data.length > 0 && !/[\u0000-\u001F\u007F-\u009F]/u.test(data);
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
1141
|
-
|
|
1142
|
-
function decodeQuestionFilterInput(data: string): string | undefined {
|
|
1143
|
-
const kittyPrintable = decodeKittyPrintable(data);
|
|
1144
|
-
if (kittyPrintable !== undefined) return isPrintableInput(kittyPrintable) ? kittyPrintable : undefined;
|
|
1145
|
-
|
|
1146
|
-
const pasteStart = "\x1B[200~";
|
|
1147
|
-
const pasteEnd = "\x1B[201~";
|
|
1148
|
-
const startIndex = data.indexOf(pasteStart);
|
|
1149
|
-
const endIndex = data.indexOf(pasteEnd, startIndex + pasteStart.length);
|
|
1150
|
-
if (startIndex >= 0 && endIndex >= 0) {
|
|
1151
|
-
return data
|
|
1152
|
-
.slice(startIndex + pasteStart.length, endIndex)
|
|
1153
|
-
.replace(/\r\n|\r|\n/gu, "")
|
|
1154
|
-
.replace(/\t/gu, " ")
|
|
1155
|
-
.replace(/[\u0000-\u001F\u007F-\u009F]/gu, "");
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
return isPrintableInput(data) ? data : undefined;
|
|
1159
|
-
}
|
|
1160
|
-
|
|
1161
|
-
function removeLastGrapheme(value: string): string {
|
|
1162
|
-
const segments = [...graphemeSegmenter.segment(value)];
|
|
1163
|
-
const last = segments.at(-1);
|
|
1164
|
-
return last ? value.slice(0, last.index) : "";
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
function registerQuestionTool(pi: ExtensionAPI): void {
|
|
1168
|
-
pi.registerTool<typeof QuestionParams, QuestionDetails>({
|
|
1169
|
-
name: "question",
|
|
1170
|
-
label: "Question",
|
|
1171
|
-
description: "Ask one interactive multiple-choice question. Provide 1-9 concise options. The user can filter options or type a custom answer.",
|
|
1172
|
-
promptSnippet: "Ask the user one multiple-choice question when a decision is required to proceed",
|
|
1173
|
-
promptGuidelines: [
|
|
1174
|
-
"Use question only when user input is required to choose between concrete alternatives; do not use question for rhetorical or optional follow-up prompts.",
|
|
1175
|
-
],
|
|
1176
|
-
parameters: QuestionParams,
|
|
1177
|
-
executionMode: "sequential",
|
|
1178
|
-
|
|
1179
|
-
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
1180
|
-
if (ctx.mode !== "tui") throw new Error("The question tool requires interactive TUI mode");
|
|
1181
|
-
if (signal?.aborted) throw new Error("Question cancelled before it opened");
|
|
1182
|
-
|
|
1183
|
-
const options: DisplayOption[] = [
|
|
1184
|
-
...params.options.map((option, index) => ({
|
|
1185
|
-
label: option.label,
|
|
1186
|
-
description: option.description,
|
|
1187
|
-
preview: option.preview,
|
|
1188
|
-
originalIndex: index + 1,
|
|
1189
|
-
isOther: false,
|
|
1190
|
-
})),
|
|
1191
|
-
{
|
|
1192
|
-
label: "Type a custom answer",
|
|
1193
|
-
originalIndex: params.options.length + 1,
|
|
1194
|
-
isOther: true,
|
|
1195
|
-
},
|
|
1196
|
-
];
|
|
1197
|
-
|
|
1198
|
-
let finishFromAbort: (() => void) | undefined;
|
|
1199
|
-
const resultPromise = ctx.ui.custom<QuestionSelection>((tui, theme, _keybindings, done) => {
|
|
1200
|
-
let optionIndex = 0;
|
|
1201
|
-
let editMode = false;
|
|
1202
|
-
let filterQuery = "";
|
|
1203
|
-
let cachedWidth: number | undefined;
|
|
1204
|
-
let cachedLines: string[] | undefined;
|
|
1205
|
-
let completed = false;
|
|
1206
|
-
|
|
1207
|
-
const finish = (selection: QuestionSelection): void => {
|
|
1208
|
-
if (completed) return;
|
|
1209
|
-
completed = true;
|
|
1210
|
-
done(selection);
|
|
1211
|
-
};
|
|
1212
|
-
finishFromAbort = () => finish({ kind: "aborted" });
|
|
1213
|
-
|
|
1214
|
-
const editorTheme: EditorTheme = {
|
|
1215
|
-
borderColor: (text) => theme.fg("accent", text),
|
|
1216
|
-
selectList: {
|
|
1217
|
-
selectedPrefix: (text) => theme.fg("accent", text),
|
|
1218
|
-
selectedText: (text) => theme.fg("accent", text),
|
|
1219
|
-
description: (text) => theme.fg("muted", text),
|
|
1220
|
-
scrollInfo: (text) => theme.fg("dim", text),
|
|
1221
|
-
noMatch: (text) => theme.fg("warning", text),
|
|
1222
|
-
},
|
|
1223
|
-
};
|
|
1224
|
-
const editor = new Editor(tui, editorTheme);
|
|
1225
|
-
customInputHistory.forEach((value) => editor.addToHistory(value));
|
|
1226
|
-
|
|
1227
|
-
const filteredOptions = (): DisplayOption[] => {
|
|
1228
|
-
const query = filterQuery.trim().toLocaleLowerCase();
|
|
1229
|
-
return options.filter((option) => option.isOther
|
|
1230
|
-
|| query.length === 0
|
|
1231
|
-
|| option.label.toLocaleLowerCase().includes(query)
|
|
1232
|
-
|| option.description?.toLocaleLowerCase().includes(query));
|
|
1233
|
-
};
|
|
1234
|
-
|
|
1235
|
-
const invalidate = (): void => {
|
|
1236
|
-
cachedWidth = undefined;
|
|
1237
|
-
cachedLines = undefined;
|
|
1238
|
-
editor.invalidate();
|
|
1239
|
-
};
|
|
1240
|
-
|
|
1241
|
-
const refresh = (): void => {
|
|
1242
|
-
invalidate();
|
|
1243
|
-
tui.requestRender();
|
|
1244
|
-
};
|
|
1245
|
-
|
|
1246
|
-
editor.onSubmit = (value) => {
|
|
1247
|
-
const answer = value.trim();
|
|
1248
|
-
if (answer) {
|
|
1249
|
-
rememberCustomInput(answer);
|
|
1250
|
-
finish({ kind: "custom", answer });
|
|
1251
|
-
return;
|
|
1252
|
-
}
|
|
1253
|
-
editMode = false;
|
|
1254
|
-
editor.setText("");
|
|
1255
|
-
refresh();
|
|
1256
|
-
};
|
|
1257
|
-
|
|
1258
|
-
const enterCustomMode = (): void => {
|
|
1259
|
-
editMode = true;
|
|
1260
|
-
refresh();
|
|
1261
|
-
};
|
|
1262
|
-
|
|
1263
|
-
const handleInput = (data: string): void => {
|
|
1264
|
-
if (editMode) {
|
|
1265
|
-
if (matchesKey(data, Key.escape)) {
|
|
1266
|
-
editMode = false;
|
|
1267
|
-
editor.setText("");
|
|
1268
|
-
refresh();
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
editor.handleInput(data);
|
|
1272
|
-
refresh();
|
|
1273
|
-
return;
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
const visibleOptions = filteredOptions();
|
|
1277
|
-
if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
|
|
1278
|
-
if (matchesKey(data, Key.up)) {
|
|
1279
|
-
optionIndex = Math.max(0, optionIndex - 1);
|
|
1280
|
-
refresh();
|
|
1281
|
-
return;
|
|
1282
|
-
}
|
|
1283
|
-
if (matchesKey(data, Key.down)) {
|
|
1284
|
-
optionIndex = Math.min(visibleOptions.length - 1, optionIndex + 1);
|
|
1285
|
-
refresh();
|
|
1286
|
-
return;
|
|
1287
|
-
}
|
|
1288
|
-
if (matchesKey(data, Key.enter)) {
|
|
1289
|
-
const selected = visibleOptions[optionIndex];
|
|
1290
|
-
if (!selected) return;
|
|
1291
|
-
if (selected.isOther) enterCustomMode();
|
|
1292
|
-
else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
|
|
1293
|
-
return;
|
|
1294
|
-
}
|
|
1295
|
-
if (matchesKey(data, Key.escape)) {
|
|
1296
|
-
if (filterQuery) {
|
|
1297
|
-
filterQuery = "";
|
|
1298
|
-
optionIndex = 0;
|
|
1299
|
-
refresh();
|
|
1300
|
-
} else {
|
|
1301
|
-
finish({ kind: "cancelled" });
|
|
1302
|
-
}
|
|
1303
|
-
return;
|
|
1304
|
-
}
|
|
1305
|
-
if (matchesKey(data, Key.backspace)) {
|
|
1306
|
-
if (filterQuery) {
|
|
1307
|
-
filterQuery = removeLastGrapheme(filterQuery);
|
|
1308
|
-
optionIndex = 0;
|
|
1309
|
-
refresh();
|
|
1310
|
-
}
|
|
1311
|
-
return;
|
|
1312
|
-
}
|
|
1313
|
-
const printableInput = decodeQuestionFilterInput(data);
|
|
1314
|
-
const isPasteInput = data.includes("\x1B[200~");
|
|
1315
|
-
if (!isPasteInput && printableInput && /^[1-9]$/.test(printableInput)) {
|
|
1316
|
-
const selected = visibleOptions[Number(printableInput) - 1];
|
|
1317
|
-
if (!selected) return;
|
|
1318
|
-
if (selected.isOther) enterCustomMode();
|
|
1319
|
-
else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
|
|
1320
|
-
return;
|
|
1321
|
-
}
|
|
1322
|
-
if (printableInput) {
|
|
1323
|
-
filterQuery += printableInput;
|
|
1324
|
-
optionIndex = 0;
|
|
1325
|
-
refresh();
|
|
1326
|
-
}
|
|
1327
|
-
};
|
|
1328
|
-
|
|
1329
|
-
const render = (width: number): string[] => {
|
|
1330
|
-
const renderWidth = Math.max(1, width);
|
|
1331
|
-
if (cachedLines && cachedWidth === renderWidth) return cachedLines;
|
|
1332
|
-
const lines: string[] = [];
|
|
1333
|
-
const addWrapped = (text: string): void => {
|
|
1334
|
-
lines.push(...wrapTextWithAnsi(text, renderWidth));
|
|
1335
|
-
};
|
|
1336
|
-
const addWrappedWithPrefix = (prefix: string, text: string): void => {
|
|
1337
|
-
const prefixWidth = visibleWidth(prefix);
|
|
1338
|
-
if (prefixWidth >= renderWidth) {
|
|
1339
|
-
addWrapped(prefix + text);
|
|
1340
|
-
return;
|
|
1341
|
-
}
|
|
1342
|
-
const wrapped = wrapTextWithAnsi(text, renderWidth - prefixWidth);
|
|
1343
|
-
const continuation = " ".repeat(prefixWidth);
|
|
1344
|
-
wrapped.forEach((line, index) => lines.push(`${index === 0 ? prefix : continuation}${line}`));
|
|
1345
|
-
};
|
|
1346
|
-
|
|
1347
|
-
lines.push(theme.fg("accent", "─".repeat(renderWidth)));
|
|
1348
|
-
addWrappedWithPrefix(" ", theme.fg("text", params.question));
|
|
1349
|
-
lines.push("");
|
|
1350
|
-
if (!editMode && filterQuery) {
|
|
1351
|
-
addWrappedWithPrefix(" ", `${theme.fg("muted", "Filter: ")}${theme.fg("accent", filterQuery)}`);
|
|
1352
|
-
lines.push("");
|
|
1353
|
-
}
|
|
1354
|
-
|
|
1355
|
-
const visibleOptions = filteredOptions();
|
|
1356
|
-
if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
|
|
1357
|
-
visibleOptions.forEach((option, index) => {
|
|
1358
|
-
const selected = index === optionIndex;
|
|
1359
|
-
const prefix = selected ? theme.fg("accent", "> ") : " ";
|
|
1360
|
-
const color: ThemeColor = selected ? "accent" : "text";
|
|
1361
|
-
addWrappedWithPrefix(prefix, theme.fg(color, `${index + 1}. ${option.label}`));
|
|
1362
|
-
if (selected && option.description) {
|
|
1363
|
-
addWrappedWithPrefix(" ", theme.fg("muted", option.description));
|
|
1364
|
-
}
|
|
1365
|
-
});
|
|
1366
|
-
|
|
1367
|
-
const selectedPreview = visibleOptions[optionIndex]?.preview;
|
|
1368
|
-
if (!editMode && selectedPreview) {
|
|
1369
|
-
const footerRows = 3;
|
|
1370
|
-
const previewChromeRows = 2;
|
|
1371
|
-
const availableRows = tui.terminal.rows - lines.length - footerRows;
|
|
1372
|
-
if (availableRows > previewChromeRows) {
|
|
1373
|
-
lines.push("");
|
|
1374
|
-
addWrappedWithPrefix(" ", theme.fg("accent", theme.bold("Proposal preview")));
|
|
1375
|
-
const markdownLines = new Markdown(
|
|
1376
|
-
selectedPreview,
|
|
1377
|
-
1,
|
|
1378
|
-
0,
|
|
1379
|
-
{
|
|
1380
|
-
heading: (text) => theme.fg("accent", theme.bold(text)),
|
|
1381
|
-
link: (text) => theme.fg("accent", text),
|
|
1382
|
-
linkUrl: (text) => theme.fg("dim", text),
|
|
1383
|
-
code: (text) => theme.fg("mdCode", text),
|
|
1384
|
-
codeBlock: (text) => theme.fg("mdCodeBlock", text),
|
|
1385
|
-
codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
|
|
1386
|
-
quote: (text) => theme.fg("mdQuote", text),
|
|
1387
|
-
quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
|
|
1388
|
-
hr: (text) => theme.fg("mdHr", text),
|
|
1389
|
-
listBullet: (text) => theme.fg("mdListBullet", text),
|
|
1390
|
-
bold: (text) => theme.bold(text),
|
|
1391
|
-
italic: (text) => theme.italic(text),
|
|
1392
|
-
strikethrough: (text) => theme.strikethrough(text),
|
|
1393
|
-
underline: (text) => theme.underline(text),
|
|
1394
|
-
},
|
|
1395
|
-
{ color: (text) => theme.fg("muted", text) },
|
|
1396
|
-
).render(renderWidth);
|
|
1397
|
-
const maxPreviewRows = Math.min(12, availableRows - previewChromeRows);
|
|
1398
|
-
if (markdownLines.length <= maxPreviewRows) {
|
|
1399
|
-
lines.push(...markdownLines);
|
|
1400
|
-
} else {
|
|
1401
|
-
const visiblePreviewRows = Math.max(0, maxPreviewRows - 1);
|
|
1402
|
-
lines.push(...markdownLines.slice(0, visiblePreviewRows));
|
|
1403
|
-
const hiddenRows = markdownLines.length - visiblePreviewRows;
|
|
1404
|
-
lines.push(theme.fg("dim", ` … ${hiddenRows} more line${hiddenRows === 1 ? "" : "s"}`));
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
if (editMode) {
|
|
1410
|
-
lines.push("");
|
|
1411
|
-
addWrappedWithPrefix(" ", theme.fg("muted", "Your answer:"));
|
|
1412
|
-
editor.render(Math.max(1, renderWidth - 2)).forEach((line) => lines.push(` ${line}`));
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
lines.push("");
|
|
1416
|
-
const hint = editMode
|
|
1417
|
-
? `Enter submit • Esc options${customInputHistory.length ? " • ↑↓ history" : ""}`
|
|
1418
|
-
: filterQuery
|
|
1419
|
-
? "1-9 select • ↑↓ navigate • Enter select • Esc clear filter"
|
|
1420
|
-
: "1-9 select • type to filter • ↑↓ navigate • Enter select • Esc cancel";
|
|
1421
|
-
addWrappedWithPrefix(" ", theme.fg("dim", hint));
|
|
1422
|
-
lines.push(theme.fg("accent", "─".repeat(renderWidth)));
|
|
1423
|
-
cachedWidth = renderWidth;
|
|
1424
|
-
cachedLines = lines.map((line) => truncateToWidth(line, renderWidth, ""));
|
|
1425
|
-
return cachedLines;
|
|
1426
|
-
};
|
|
1427
|
-
|
|
1428
|
-
let focused = false;
|
|
1429
|
-
return {
|
|
1430
|
-
get focused(): boolean { return focused; },
|
|
1431
|
-
set focused(value: boolean) {
|
|
1432
|
-
focused = value;
|
|
1433
|
-
editor.focused = value;
|
|
1434
|
-
},
|
|
1435
|
-
render,
|
|
1436
|
-
handleInput,
|
|
1437
|
-
invalidate,
|
|
1438
|
-
};
|
|
1439
|
-
});
|
|
1440
|
-
|
|
1441
|
-
const abortHandler = (): void => finishFromAbort?.();
|
|
1442
|
-
signal?.addEventListener("abort", abortHandler, { once: true });
|
|
1443
|
-
if (signal?.aborted) abortHandler();
|
|
1444
|
-
let result: QuestionSelection;
|
|
1445
|
-
try {
|
|
1446
|
-
result = await resultPromise;
|
|
1447
|
-
} finally {
|
|
1448
|
-
signal?.removeEventListener("abort", abortHandler);
|
|
1449
|
-
}
|
|
1450
|
-
|
|
1451
|
-
const simpleOptions = params.options.map((option) => option.label);
|
|
1452
|
-
if (result.kind === "aborted") throw new Error("Question cancelled because the agent operation was aborted");
|
|
1453
|
-
if (result.kind === "cancelled") {
|
|
1454
|
-
return {
|
|
1455
|
-
content: [{ type: "text", text: "User cancelled the question" }],
|
|
1456
|
-
details: { question: params.question, options: simpleOptions, answer: null, cancelled: true },
|
|
1457
|
-
};
|
|
1458
|
-
}
|
|
1459
|
-
if (result.kind === "custom") {
|
|
1460
|
-
return {
|
|
1461
|
-
content: [{ type: "text", text: `User wrote: ${result.answer}` }],
|
|
1462
|
-
details: { question: params.question, options: simpleOptions, answer: result.answer, wasCustom: true },
|
|
1463
|
-
};
|
|
1464
|
-
}
|
|
1465
|
-
return {
|
|
1466
|
-
content: [{ type: "text", text: `User selected: ${result.answer}` }],
|
|
1467
|
-
details: {
|
|
1468
|
-
question: params.question,
|
|
1469
|
-
options: simpleOptions,
|
|
1470
|
-
answer: result.answer,
|
|
1471
|
-
selectedIndex: result.originalIndex,
|
|
1472
|
-
wasCustom: false,
|
|
1473
|
-
},
|
|
1474
|
-
};
|
|
1475
|
-
},
|
|
1476
|
-
|
|
1477
|
-
renderCall(args, theme) {
|
|
1478
|
-
let text = `${theme.fg("toolTitle", theme.bold("question "))}${theme.fg("muted", args.question)}`;
|
|
1479
|
-
if (args.options.length) {
|
|
1480
|
-
const numbered = [...args.options.map((option) => option.label), "Type a custom answer"]
|
|
1481
|
-
.map((option, index) => `${index + 1}. ${option}`);
|
|
1482
|
-
text += `\n${theme.fg("dim", ` Options: ${numbered.join(", ")}`)}`;
|
|
1483
|
-
}
|
|
1484
|
-
return new Text(text, 0, 0);
|
|
1485
|
-
},
|
|
1486
|
-
|
|
1487
|
-
renderResult(result, _options, theme) {
|
|
1488
|
-
const details = result.details;
|
|
1489
|
-
if (!details) {
|
|
1490
|
-
const first = result.content[0];
|
|
1491
|
-
return new Text(first?.type === "text" ? first.text : "", 0, 0);
|
|
1492
|
-
}
|
|
1493
|
-
if (details.cancelled || details.answer === null) return new Text(theme.fg("warning", "Cancelled"), 0, 0);
|
|
1494
|
-
if (details.wasCustom) {
|
|
1495
|
-
return new Text(`${theme.fg("success", "✓ ")}${theme.fg("muted", "(wrote) ")}${theme.fg("accent", details.answer)}`, 0, 0);
|
|
1496
|
-
}
|
|
1497
|
-
return new Text(`${theme.fg("success", "✓ ")}${theme.fg("accent", details.answer)}`, 0, 0);
|
|
1498
|
-
},
|
|
1499
|
-
});
|
|
1500
|
-
}
|
|
1501
|
-
|
|
1502
|
-
const PERSONAL_INSTRUCTIONS_FILE = "AGENTS.local.md";
|
|
1503
|
-
const PERSONAL_INSTRUCTIONS_LIMIT = 32 * 1024;
|
|
1504
|
-
|
|
1505
|
-
function readBoundedText(filePath: string, limit = PERSONAL_INSTRUCTIONS_LIMIT): string | undefined {
|
|
1506
|
-
let descriptor: number | undefined;
|
|
1507
|
-
try {
|
|
1508
|
-
descriptor = openSync(filePath, "r");
|
|
1509
|
-
const buffer = Buffer.alloc(limit + 1);
|
|
1510
|
-
const bytesRead = readSync(descriptor, buffer, 0, buffer.length, 0);
|
|
1511
|
-
const content = buffer.toString("utf8", 0, Math.min(bytesRead, limit));
|
|
1512
|
-
if (!content.trim()) return undefined;
|
|
1513
|
-
return bytesRead > limit
|
|
1514
|
-
? `${content}\n\n[Personal instructions truncated by KillerOS]`
|
|
1515
|
-
: content;
|
|
1516
|
-
} catch {
|
|
1517
|
-
return undefined;
|
|
1518
|
-
} finally {
|
|
1519
|
-
if (descriptor !== undefined) {
|
|
1520
|
-
try {
|
|
1521
|
-
closeSync(descriptor);
|
|
1522
|
-
} catch {
|
|
1523
|
-
// Ignore cleanup failures after a bounded best-effort read.
|
|
1524
|
-
}
|
|
1525
|
-
}
|
|
1526
|
-
}
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
function resolvePersonalInstructions(cwd: string): { content: string; source: string } | undefined {
|
|
1530
|
-
const localPath = path.join(cwd, PERSONAL_INSTRUCTIONS_FILE);
|
|
1531
|
-
const local = readBoundedText(localPath);
|
|
1532
|
-
if (!local) return undefined;
|
|
1533
|
-
|
|
1534
|
-
const importMatch = local.trim().match(/^@(.+)$/u);
|
|
1535
|
-
if (!importMatch) return { content: local, source: localPath };
|
|
1536
|
-
|
|
1537
|
-
const requestedPath = importMatch[1]!.trim();
|
|
1538
|
-
const importedPath = requestedPath.startsWith("~/") || requestedPath.startsWith("~\\")
|
|
1539
|
-
? path.join(os.homedir(), requestedPath.slice(2))
|
|
1540
|
-
: path.resolve(cwd, requestedPath);
|
|
1541
|
-
const imported = readBoundedText(importedPath);
|
|
1542
|
-
return imported ? { content: imported, source: importedPath } : { content: local, source: localPath };
|
|
1543
|
-
}
|
|
1544
|
-
|
|
1545
|
-
function registerPersonalInstructions(pi: ExtensionAPI, initState: InitWorkflowState): void {
|
|
1546
|
-
pi.on("before_agent_start", (event, ctx) => {
|
|
1547
|
-
if (initState.active || !ctx.isProjectTrusted()) return;
|
|
1548
|
-
const personal = resolvePersonalInstructions(ctx.cwd);
|
|
1549
|
-
if (!personal) return;
|
|
1550
|
-
return {
|
|
1551
|
-
systemPrompt: [
|
|
1552
|
-
event.systemPrompt,
|
|
1553
|
-
"",
|
|
1554
|
-
`<personal_instructions source="${personal.source}">`,
|
|
1555
|
-
personal.content,
|
|
1556
|
-
"</personal_instructions>",
|
|
1557
|
-
].join("\n"),
|
|
1558
|
-
};
|
|
1559
|
-
});
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
type KillerosHookEvent = "tool_call" | "tool_result" | "agent_settled";
|
|
1563
|
-
|
|
1564
|
-
interface KillerosHook {
|
|
1565
|
-
matcher?: string;
|
|
1566
|
-
command: string;
|
|
1567
|
-
timeoutMs?: number;
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
interface KillerosHookConfig {
|
|
1571
|
-
hooks?: Partial<Record<KillerosHookEvent, KillerosHook[]>>;
|
|
1572
|
-
}
|
|
1573
|
-
|
|
1574
|
-
interface HookExecutionResult {
|
|
1575
|
-
code: number;
|
|
1576
|
-
stdout: string;
|
|
1577
|
-
stderr: string;
|
|
1578
|
-
timedOut: boolean;
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
const HOOK_EVENTS: readonly KillerosHookEvent[] = ["tool_call", "tool_result", "agent_settled"];
|
|
1582
|
-
const HOOK_OUTPUT_LIMIT = 16 * 1024;
|
|
1583
|
-
|
|
1584
|
-
function loadKillerosHooks(ctx: ExtensionContext): KillerosHookConfig {
|
|
1585
|
-
const configPath = path.join(ctx.cwd, CONFIG_DIR_NAME, "killeros-hooks.json");
|
|
1586
|
-
if (!existsSync(configPath)) return {};
|
|
1587
|
-
if (!ctx.isProjectTrusted()) {
|
|
1588
|
-
ctx.ui.notify(`Ignored untrusted project hooks in ${configPath}`, "warning");
|
|
1589
|
-
return {};
|
|
1590
|
-
}
|
|
1591
|
-
|
|
1592
|
-
try {
|
|
1593
|
-
const parsed = JSON.parse(readFileSync(configPath, "utf8")) as KillerosHookConfig;
|
|
1594
|
-
const hooks: KillerosHookConfig["hooks"] = {};
|
|
1595
|
-
for (const event of HOOK_EVENTS) {
|
|
1596
|
-
const candidates = parsed.hooks?.[event];
|
|
1597
|
-
if (!Array.isArray(candidates)) continue;
|
|
1598
|
-
hooks[event] = candidates.filter((hook, index) => {
|
|
1599
|
-
const valid = hook
|
|
1600
|
-
&& typeof hook.command === "string"
|
|
1601
|
-
&& hook.command.trim().length > 0
|
|
1602
|
-
&& (hook.matcher === undefined || typeof hook.matcher === "string")
|
|
1603
|
-
&& (hook.timeoutMs === undefined || Number.isFinite(hook.timeoutMs));
|
|
1604
|
-
if (!valid) {
|
|
1605
|
-
ctx.ui.notify(`Ignored invalid ${event} hook ${index + 1} in ${configPath}`, "warning");
|
|
1606
|
-
return false;
|
|
1607
|
-
}
|
|
1608
|
-
if (hook.matcher && hook.matcher !== "*") {
|
|
1609
|
-
try {
|
|
1610
|
-
new RegExp(hook.matcher, "u");
|
|
1611
|
-
} catch {
|
|
1612
|
-
ctx.ui.notify(`Ignored ${event} hook ${index + 1}: invalid matcher ${JSON.stringify(hook.matcher)}`, "warning");
|
|
1613
|
-
return false;
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
return true;
|
|
1617
|
-
});
|
|
1618
|
-
}
|
|
1619
|
-
return { hooks };
|
|
1620
|
-
} catch (error) {
|
|
1621
|
-
reportError(ctx, `Invalid ${CONFIG_DIR_NAME}/killeros-hooks.json`, error);
|
|
1622
|
-
return {};
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
function matchesHook(hook: KillerosHook, value: string): boolean {
|
|
1627
|
-
if (!hook.matcher || hook.matcher === "*") return true;
|
|
1628
|
-
try {
|
|
1629
|
-
return new RegExp(hook.matcher, "u").test(value);
|
|
1630
|
-
} catch {
|
|
1631
|
-
return false;
|
|
1632
|
-
}
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
function appendBounded(current: string, chunk: Buffer | string): string {
|
|
1636
|
-
if (current.length >= HOOK_OUTPUT_LIMIT) return current;
|
|
1637
|
-
return (current + chunk.toString()).slice(0, HOOK_OUTPUT_LIMIT);
|
|
1638
|
-
}
|
|
1639
|
-
|
|
1640
|
-
function executeHook(command: string, cwd: string, environment: Record<string, string>, timeoutMs = 30_000): Promise<HookExecutionResult> {
|
|
1641
|
-
return new Promise((resolve) => {
|
|
1642
|
-
const child = spawn(command, {
|
|
1643
|
-
cwd,
|
|
1644
|
-
env: { ...process.env, ...environment },
|
|
1645
|
-
shell: true,
|
|
1646
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1647
|
-
windowsHide: true,
|
|
1648
|
-
});
|
|
1649
|
-
let stdout = "";
|
|
1650
|
-
let stderr = "";
|
|
1651
|
-
let completed = false;
|
|
1652
|
-
let timedOut = false;
|
|
1653
|
-
let timer: NodeJS.Timeout | undefined;
|
|
1654
|
-
const finish = (code: number): void => {
|
|
1655
|
-
if (completed) return;
|
|
1656
|
-
completed = true;
|
|
1657
|
-
if (timer) clearTimeout(timer);
|
|
1658
|
-
resolve({ code, stdout, stderr, timedOut });
|
|
1659
|
-
};
|
|
1660
|
-
child.stdout.on("data", (chunk) => { stdout = appendBounded(stdout, chunk); });
|
|
1661
|
-
child.stderr.on("data", (chunk) => { stderr = appendBounded(stderr, chunk); });
|
|
1662
|
-
child.on("error", (error) => {
|
|
1663
|
-
stderr = appendBounded(stderr, error.message);
|
|
1664
|
-
finish(1);
|
|
1665
|
-
});
|
|
1666
|
-
child.on("close", (code) => finish(code ?? 1));
|
|
1667
|
-
timer = setTimeout(() => {
|
|
1668
|
-
timedOut = true;
|
|
1669
|
-
child.kill("SIGTERM");
|
|
1670
|
-
setTimeout(() => child.kill("SIGKILL"), 1_000).unref?.();
|
|
1671
|
-
finish(124);
|
|
1672
|
-
}, Math.max(1_000, Math.min(timeoutMs, 300_000)));
|
|
1673
|
-
timer.unref?.();
|
|
1674
|
-
});
|
|
1675
|
-
}
|
|
1676
|
-
|
|
1677
|
-
function hookEnvironment(event: KillerosHookEvent, toolName = "", payload: unknown = {}): Record<string, string> {
|
|
1678
|
-
return {
|
|
1679
|
-
KILLEROS_EVENT: event,
|
|
1680
|
-
KILLEROS_TOOL: toolName,
|
|
1681
|
-
KILLEROS_PAYLOAD: JSON.stringify(payload).slice(0, 8_000),
|
|
1682
|
-
};
|
|
1683
|
-
}
|
|
1684
|
-
|
|
1685
|
-
function hookFailureMessage(hook: KillerosHook, result: HookExecutionResult): string {
|
|
1686
|
-
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.code}`;
|
|
1687
|
-
return `Hook failed${result.timedOut ? " (timed out)" : ""}: ${hook.command}\n${detail}`;
|
|
1688
|
-
}
|
|
1689
|
-
|
|
1690
|
-
function registerLifecycleHooks(pi: ExtensionAPI): void {
|
|
1691
|
-
let config: KillerosHookConfig = {};
|
|
1692
|
-
pi.on("session_start", (_event, ctx) => { config = loadKillerosHooks(ctx); });
|
|
1693
|
-
|
|
1694
|
-
pi.on("tool_call", async (event, ctx) => {
|
|
1695
|
-
for (const hook of config.hooks?.tool_call ?? []) {
|
|
1696
|
-
if (!matchesHook(hook, event.toolName)) continue;
|
|
1697
|
-
const result = await executeHook(
|
|
1698
|
-
hook.command,
|
|
1699
|
-
ctx.cwd,
|
|
1700
|
-
hookEnvironment("tool_call", event.toolName, event.input),
|
|
1701
|
-
hook.timeoutMs,
|
|
1702
|
-
);
|
|
1703
|
-
if (result.code !== 0) {
|
|
1704
|
-
const reason = hookFailureMessage(hook, result);
|
|
1705
|
-
ctx.ui.notify(reason, "error");
|
|
1706
|
-
return { block: true, reason };
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
});
|
|
1710
|
-
|
|
1711
|
-
pi.on("tool_result", async (event, ctx) => {
|
|
1712
|
-
for (const hook of config.hooks?.tool_result ?? []) {
|
|
1713
|
-
if (!matchesHook(hook, event.toolName)) continue;
|
|
1714
|
-
const result = await executeHook(
|
|
1715
|
-
hook.command,
|
|
1716
|
-
ctx.cwd,
|
|
1717
|
-
hookEnvironment("tool_result", event.toolName, {
|
|
1718
|
-
input: event.input,
|
|
1719
|
-
isError: event.isError,
|
|
1720
|
-
}),
|
|
1721
|
-
hook.timeoutMs,
|
|
1722
|
-
);
|
|
1723
|
-
if (result.code !== 0) ctx.ui.notify(hookFailureMessage(hook, result), "error");
|
|
1724
|
-
}
|
|
1725
|
-
});
|
|
1726
|
-
|
|
1727
|
-
pi.on("agent_settled", async (_event, ctx) => {
|
|
1728
|
-
for (const hook of config.hooks?.agent_settled ?? []) {
|
|
1729
|
-
const result = await executeHook(
|
|
1730
|
-
hook.command,
|
|
1731
|
-
ctx.cwd,
|
|
1732
|
-
hookEnvironment("agent_settled"),
|
|
1733
|
-
hook.timeoutMs,
|
|
1734
|
-
);
|
|
1735
|
-
if (result.code !== 0) ctx.ui.notify(hookFailureMessage(hook, result), "error");
|
|
1736
|
-
}
|
|
1737
|
-
});
|
|
1738
|
-
}
|
|
1739
|
-
|
|
1740
|
-
const INIT_SURVEY_OUTPUT_LIMIT = 40 * 1024;
|
|
1741
|
-
const INIT_SURVEY_FILE_LIMIT = 8 * 1024;
|
|
1742
|
-
const INIT_SURVEY_PATH_LIMIT = 400;
|
|
1743
|
-
const INIT_SURVEY_DIRECTORY_LIMIT = 120;
|
|
1744
|
-
const INIT_SURVEY_DEPTH_LIMIT = 4;
|
|
1745
|
-
const INIT_SURVEY_EXCLUDED_DIRS = new Set([
|
|
1746
|
-
".agents", ".claude", ".git", ".next", ".pi", ".pytest_cache", ".turbo", ".venv", "__pycache__", "archive", "build", "coverage", "data", "dist", "logs", "node_modules", "target", "test-results", "vendor",
|
|
1747
|
-
]);
|
|
1748
|
-
const INIT_SURVEY_EXCLUDED_FILES = new Set([
|
|
1749
|
-
".cursorrules", "AGENTS.md", "AGENTS.local.md", "CLAUDE.md", "CLAUDE.local.md", "GEMINI.md", "MEMORY.md", "SKILL.md", "copilot-instructions.md",
|
|
1750
|
-
]);
|
|
1751
|
-
const INIT_SURVEY_ROOT_FILES = [
|
|
1752
|
-
"README.md",
|
|
1753
|
-
"README.rst",
|
|
1754
|
-
"README.txt",
|
|
1755
|
-
"package.json",
|
|
1756
|
-
"pyproject.toml",
|
|
1757
|
-
"requirements.txt",
|
|
1758
|
-
"Cargo.toml",
|
|
1759
|
-
"go.mod",
|
|
1760
|
-
"Makefile",
|
|
1761
|
-
"Dockerfile",
|
|
1762
|
-
"compose.yaml",
|
|
1763
|
-
"compose.yml",
|
|
1764
|
-
"config.yaml",
|
|
1765
|
-
"config.yml",
|
|
1766
|
-
"tsconfig.json",
|
|
1767
|
-
"vite.config.ts",
|
|
1768
|
-
"vite.config.js",
|
|
1769
|
-
"eslint.config.js",
|
|
1770
|
-
"eslint.config.mjs",
|
|
1771
|
-
] as const;
|
|
1772
|
-
const INIT_SURVEY_NESTED_FILES = new Set([
|
|
1773
|
-
"package.json", "pyproject.toml", "requirements.txt", "Cargo.toml", "go.mod",
|
|
1774
|
-
]);
|
|
1775
|
-
|
|
1776
|
-
async function collectInitProjectFiles(cwd: string): Promise<string[]> {
|
|
1777
|
-
const files: string[] = [];
|
|
1778
|
-
const queue: Array<{ relativePath: string; depth: number }> = [{ relativePath: "", depth: 0 }];
|
|
1779
|
-
let directoriesRead = 0;
|
|
1780
|
-
while (queue.length && files.length < INIT_SURVEY_PATH_LIMIT && directoriesRead < INIT_SURVEY_DIRECTORY_LIMIT) {
|
|
1781
|
-
const current = queue.shift()!;
|
|
1782
|
-
directoriesRead += 1;
|
|
1783
|
-
let entries;
|
|
1784
|
-
try {
|
|
1785
|
-
entries = await fs.readdir(path.join(cwd, current.relativePath), { withFileTypes: true });
|
|
1786
|
-
} catch (error) {
|
|
1787
|
-
if (!current.relativePath) throw error;
|
|
1788
|
-
continue;
|
|
1789
|
-
}
|
|
1790
|
-
entries.sort((left, right) => left.name === right.name ? 0 : left.name < right.name ? -1 : 1);
|
|
1791
|
-
for (const entry of entries) {
|
|
1792
|
-
if (files.length >= INIT_SURVEY_PATH_LIMIT) break;
|
|
1793
|
-
const relativePath = path.join(current.relativePath, entry.name);
|
|
1794
|
-
if (entry.isDirectory()) {
|
|
1795
|
-
if (current.depth < INIT_SURVEY_DEPTH_LIMIT && !INIT_SURVEY_EXCLUDED_DIRS.has(entry.name)) {
|
|
1796
|
-
queue.push({ relativePath, depth: current.depth + 1 });
|
|
1797
|
-
}
|
|
1798
|
-
} else if (entry.isFile() && !INIT_SURVEY_EXCLUDED_FILES.has(entry.name)) {
|
|
1799
|
-
files.push(relativePath.replaceAll("\\", "/"));
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
return files;
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
async function readFilePrefix(filePath: string, limit: number): Promise<string> {
|
|
1807
|
-
const handle = await fs.open(filePath, "r");
|
|
1808
|
-
try {
|
|
1809
|
-
const buffer = Buffer.alloc(limit);
|
|
1810
|
-
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
1811
|
-
return buffer.toString("utf8", 0, bytesRead);
|
|
1812
|
-
} finally {
|
|
1813
|
-
await handle.close();
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
|
|
1817
|
-
async function runInitSurvey(
|
|
1818
|
-
cwd: string,
|
|
1819
|
-
): Promise<{ output: string; error?: string }> {
|
|
1820
|
-
let projectFiles: string[];
|
|
1821
|
-
try {
|
|
1822
|
-
projectFiles = await collectInitProjectFiles(cwd);
|
|
1823
|
-
} catch (error) {
|
|
1824
|
-
return { output: "", error: error instanceof Error ? error.message : String(error) };
|
|
1825
|
-
}
|
|
1826
|
-
|
|
1827
|
-
const candidates = new Set<string>(INIT_SURVEY_ROOT_FILES);
|
|
1828
|
-
for (const relativePath of projectFiles) {
|
|
1829
|
-
const fileName = path.posix.basename(relativePath);
|
|
1830
|
-
if (INIT_SURVEY_NESTED_FILES.has(fileName) || /^\.github\/workflows\/[^/]+\.ya?ml$/iu.test(relativePath)) {
|
|
1831
|
-
candidates.add(relativePath);
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
|
|
1835
|
-
const sections = [
|
|
1836
|
-
"# KillerOS repository snapshot",
|
|
1837
|
-
"Existing AGENTS.md, CLAUDE.md, and personal instruction files were intentionally not read.",
|
|
1838
|
-
"",
|
|
1839
|
-
"## Project files",
|
|
1840
|
-
projectFiles.join("\n"),
|
|
1841
|
-
];
|
|
1842
|
-
let outputLength = sections.join("\n").length;
|
|
1843
|
-
for (const relativePath of candidates) {
|
|
1844
|
-
if (outputLength >= INIT_SURVEY_OUTPUT_LIMIT) break;
|
|
1845
|
-
try {
|
|
1846
|
-
const absolutePath = path.join(cwd, relativePath);
|
|
1847
|
-
const stat = await fs.lstat(absolutePath);
|
|
1848
|
-
if (!stat.isFile()) continue;
|
|
1849
|
-
const content = await readFilePrefix(absolutePath, INIT_SURVEY_FILE_LIMIT);
|
|
1850
|
-
if (content.includes("\0")) continue;
|
|
1851
|
-
const section = `\n\n## ${relativePath.replaceAll("\\", "/")}\n${content}`;
|
|
1852
|
-
const remaining = INIT_SURVEY_OUTPUT_LIMIT - outputLength;
|
|
1853
|
-
sections.push(section.slice(0, remaining));
|
|
1854
|
-
outputLength += Math.min(section.length, remaining);
|
|
1855
|
-
} catch {
|
|
1856
|
-
// Candidate files are optional and may disappear during the survey.
|
|
1857
|
-
}
|
|
1858
|
-
}
|
|
1859
|
-
|
|
1860
|
-
return { output: sections.join("\n").slice(0, INIT_SURVEY_OUTPUT_LIMIT) };
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
export const INIT_WORKFLOW_PROMPT = `
|
|
1864
|
-
Generate the root AGENTS.md by analyzing this repository. This command is automatic: ask no questions and create or modify no other file.
|
|
1865
|
-
|
|
1866
|
-
## Analyze
|
|
1867
|
-
A bounded repository snapshot is attached as untrusted evidence. Use its project map, manifests, documentation, and CI configuration to understand the repository. Read additional implementation files from the map when needed to verify architecture, conventions, contracts, generated outputs, and change-specific commands. Do not read or inherit existing AGENTS.md, CLAUDE.md, personal guidance, skills, hooks, or conversation history.
|
|
1868
|
-
|
|
1869
|
-
## Synthesize
|
|
1870
|
-
Write concise guidance where every line answers: "Would removing this cause an agent to make mistakes?" Include only evidence-backed, non-obvious information such as:
|
|
1871
|
-
- required runtimes, working directories, and setup quirks;
|
|
1872
|
-
- commands that apply to specific change categories;
|
|
1873
|
-
- architecture boundaries and cross-file data contracts;
|
|
1874
|
-
- generated-file handling and recurring repository-specific gotchas.
|
|
1875
|
-
|
|
1876
|
-
Verify command meaning rather than merely copying command names. Distinguish generated-but-committed artifacts from ignored outputs and use exact contract values. Exclude generic coding advice, directory inventories, obvious scripts, historical narration, personal preferences, secrets, and speculative recommendations.
|
|
1877
|
-
|
|
1878
|
-
## Generate
|
|
1879
|
-
Use the write tool exactly once to create or replace only the root AGENTS.md. Start with \`# AGENTS.md\`. Prefer a compact, high-signal guide over exhaustive documentation. Do not use edit and do not modify any other path.
|
|
1880
|
-
|
|
1881
|
-
After writing, read AGENTS.md once to confirm the file is coherent and contains only claims supported by repository evidence. Summarize what was generated. KillerOS reloads Pi resources automatically after this turn, so do not invoke /reload.
|
|
1882
|
-
`.trim();
|
|
1883
|
-
|
|
1884
|
-
function resolveInitToolPath(input: unknown, cwd: string): string | undefined {
|
|
1885
|
-
if (!input || typeof input !== "object") return undefined;
|
|
1886
|
-
const toolPath = (input as { path?: unknown }).path;
|
|
1887
|
-
return typeof toolPath === "string" ? path.resolve(cwd, toolPath) : undefined;
|
|
1888
|
-
}
|
|
1889
|
-
|
|
1890
|
-
async function initTargetSafetyError(targetPath: string): Promise<string | undefined> {
|
|
1891
|
-
try {
|
|
1892
|
-
const stat = await fs.lstat(targetPath);
|
|
1893
|
-
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink > 1) {
|
|
1894
|
-
return "/init requires root AGENTS.md to be absent or a regular, non-linked file";
|
|
1895
|
-
}
|
|
1896
|
-
} catch (error) {
|
|
1897
|
-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
1898
|
-
return `/init could not inspect root AGENTS.md: ${error instanceof Error ? error.message : String(error)}`;
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
return undefined;
|
|
1902
|
-
}
|
|
1903
|
-
|
|
1904
|
-
function registerInitCommand(pi: ExtensionAPI, initState: InitWorkflowState, goalRuntime: GoalRuntime): void {
|
|
1905
|
-
pi.on("tool_call", async (event) => {
|
|
1906
|
-
const targetPath = initState.targetPath;
|
|
1907
|
-
if (!initState.active || !targetPath || INIT_READ_ONLY_TOOLS.has(event.toolName)) return;
|
|
1908
|
-
const toolPath = resolveInitToolPath(event.input, path.dirname(targetPath));
|
|
1909
|
-
if (event.toolName === "write" && toolPath === targetPath && !initState.writeAttempted) {
|
|
1910
|
-
const safetyError = await initTargetSafetyError(targetPath);
|
|
1911
|
-
if (safetyError) return { block: true, reason: safetyError };
|
|
1912
|
-
initState.writeAttempted = true;
|
|
1913
|
-
initState.writeToolCallId = event.toolCallId;
|
|
1914
|
-
return;
|
|
1915
|
-
}
|
|
1916
|
-
return {
|
|
1917
|
-
block: true,
|
|
1918
|
-
reason: "/init may write the root AGENTS.md exactly once and may not modify any other file",
|
|
1919
|
-
};
|
|
1920
|
-
});
|
|
1921
|
-
|
|
1922
|
-
pi.on("tool_result", (event) => {
|
|
1923
|
-
if (!initState.active || event.toolName !== "write" || event.toolCallId !== initState.writeToolCallId) return;
|
|
1924
|
-
if (event.isError) {
|
|
1925
|
-
initState.writeAttempted = false;
|
|
1926
|
-
initState.writeToolCallId = undefined;
|
|
1927
|
-
return;
|
|
1928
|
-
}
|
|
1929
|
-
initState.writeSucceeded = true;
|
|
1930
|
-
});
|
|
1931
|
-
|
|
1932
|
-
pi.registerCommand("init", {
|
|
1933
|
-
description: "Generate root AGENTS.md from repository evidence",
|
|
1934
|
-
handler: async (args, ctx) => {
|
|
1935
|
-
if (args.trim()) {
|
|
1936
|
-
ctx.ui.notify("/init does not accept arguments", "error");
|
|
1937
|
-
return;
|
|
1938
|
-
}
|
|
1939
|
-
if (ctx.mode !== "tui") {
|
|
1940
|
-
ctx.ui.notify("/init requires interactive TUI mode", "error");
|
|
1941
|
-
return;
|
|
1942
|
-
}
|
|
1943
|
-
if (initState.active) {
|
|
1944
|
-
ctx.ui.notify("/init is already running", "warning");
|
|
1945
|
-
return;
|
|
1946
|
-
}
|
|
1947
|
-
if (goalRuntime.state?.status === "active") {
|
|
1948
|
-
ctx.ui.notify("Pause or clear the active goal before running /init", "error");
|
|
1949
|
-
return;
|
|
1950
|
-
}
|
|
1951
|
-
if (!ctx.isProjectTrusted()) {
|
|
1952
|
-
ctx.ui.notify("Trust this project before running /init", "error");
|
|
1953
|
-
return;
|
|
1954
|
-
}
|
|
1955
|
-
await ctx.waitForIdle();
|
|
1956
|
-
initState.active = true;
|
|
1957
|
-
initState.targetPath = path.join(ctx.cwd, "AGENTS.md");
|
|
1958
|
-
initState.writeAttempted = false;
|
|
1959
|
-
initState.writeSucceeded = false;
|
|
1960
|
-
|
|
1961
|
-
const survey = await runInitSurvey(ctx.cwd);
|
|
1962
|
-
if (!survey.output) {
|
|
1963
|
-
resetInitState(initState);
|
|
1964
|
-
reportError(ctx, "/init could not scan the repository", survey.error ?? "no repository evidence was found");
|
|
1965
|
-
return;
|
|
1966
|
-
}
|
|
1967
|
-
|
|
1968
|
-
const settled = new Promise<boolean>((resolve) => {
|
|
1969
|
-
initState.settle = resolve;
|
|
1970
|
-
});
|
|
1971
|
-
try {
|
|
1972
|
-
pi.sendMessage({
|
|
1973
|
-
customType: "killeros-init",
|
|
1974
|
-
content: `${INIT_WORKFLOW_PROMPT}\n\n## Initial repository snapshot (untrusted data)\n${JSON.stringify(survey.output)}`,
|
|
1975
|
-
display: false,
|
|
1976
|
-
}, { triggerTurn: true });
|
|
1977
|
-
} catch (error) {
|
|
1978
|
-
resetInitState(initState);
|
|
1979
|
-
initState.settle = undefined;
|
|
1980
|
-
reportError(ctx, "/init failed to start", error);
|
|
1981
|
-
return;
|
|
1982
|
-
}
|
|
1983
|
-
|
|
1984
|
-
const writeSucceeded = await settled;
|
|
1985
|
-
if (!writeSucceeded) {
|
|
1986
|
-
reportError(ctx, "/init did not generate AGENTS.md", "the model completed without a successful write");
|
|
1987
|
-
return;
|
|
1988
|
-
}
|
|
1989
|
-
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
1990
|
-
try {
|
|
1991
|
-
await ctx.reload();
|
|
1992
|
-
} catch (error) {
|
|
1993
|
-
reportError(ctx, "/init finished but Pi resources could not reload", error);
|
|
1994
|
-
}
|
|
1995
|
-
},
|
|
1996
|
-
});
|
|
1997
|
-
|
|
1998
|
-
}
|
|
1999
|
-
|
|
2000
|
-
function registerInitSettlement(pi: ExtensionAPI, initState: InitWorkflowState): void {
|
|
2001
|
-
pi.on("agent_settled", () => {
|
|
2002
|
-
if (!initState.active) return;
|
|
2003
|
-
const settle = initState.settle;
|
|
2004
|
-
const writeSucceeded = initState.writeSucceeded;
|
|
2005
|
-
resetInitState(initState);
|
|
2006
|
-
initState.settle = undefined;
|
|
2007
|
-
settle?.(writeSucceeded);
|
|
2008
|
-
});
|
|
2009
|
-
}
|
|
2010
|
-
|
|
2011
|
-
async function confirmNewSession(ctx: ExtensionCommandContext): Promise<boolean> {
|
|
2012
|
-
if (!ctx.hasUI) return true;
|
|
2013
|
-
return ctx.ui.confirm("Start new session", "Start a new session and leave the current history?");
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
function registerAliases(pi: ExtensionAPI): void {
|
|
2017
|
-
const startNewSession = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
2018
|
-
await ctx.waitForIdle();
|
|
2019
|
-
if (!await confirmNewSession(ctx)) return;
|
|
2020
|
-
await ctx.newSession();
|
|
2021
|
-
};
|
|
2022
|
-
pi.registerCommand("clear", { description: "Start a new session after confirmation", handler: startNewSession });
|
|
2023
|
-
pi.registerCommand("exit", {
|
|
2024
|
-
description: "Quit Pi gracefully",
|
|
2025
|
-
handler: async (_args, ctx) => ctx.shutdown(),
|
|
2026
|
-
});
|
|
2027
|
-
}
|
|
2028
|
-
|
|
2029
|
-
interface CommandInfo {
|
|
2030
|
-
name: string;
|
|
2031
|
-
description?: string;
|
|
2032
|
-
category: "Built-in" | "Extension" | "Prompt" | "Skill";
|
|
2033
|
-
syntaxHint?: string;
|
|
2034
|
-
}
|
|
2035
|
-
|
|
2036
|
-
const BUILTIN_COMMANDS: ReadonlyArray<{ name: string; description: string }> = [
|
|
2037
|
-
{ name: "settings", description: "Open settings menu" },
|
|
2038
|
-
{ name: "model", description: "Select model" },
|
|
2039
|
-
{ name: "scoped-models", description: "Configure models for Ctrl+P cycling" },
|
|
2040
|
-
{ name: "export", description: "Export the current session" },
|
|
2041
|
-
{ name: "import", description: "Import and resume a JSONL session" },
|
|
2042
|
-
{ name: "share", description: "Share the session as a secret GitHub gist" },
|
|
2043
|
-
{ name: "copy", description: "Copy the last agent message" },
|
|
2044
|
-
{ name: "name", description: "Set the session display name" },
|
|
2045
|
-
{ name: "session", description: "Show session usage and stats" },
|
|
2046
|
-
{ name: "changelog", description: "Show changelog entries" },
|
|
2047
|
-
{ name: "hotkeys", description: "Show keyboard shortcuts" },
|
|
2048
|
-
{ name: "fork", description: "Fork from a previous user message" },
|
|
2049
|
-
{ name: "clone", description: "Duplicate the session at the current position" },
|
|
2050
|
-
{ name: "tree", description: "Navigate the session tree" },
|
|
2051
|
-
{ name: "trust", description: "Save the project trust decision" },
|
|
2052
|
-
{ name: "login", description: "Configure provider authentication" },
|
|
2053
|
-
{ name: "logout", description: "Remove provider authentication" },
|
|
2054
|
-
{ name: "new", description: "Start a new session" },
|
|
2055
|
-
{ name: "compact", description: "Compact the session context" },
|
|
2056
|
-
{ name: "resume", description: "Resume a different session" },
|
|
2057
|
-
{ name: "reload", description: "Reload extensions and resources" },
|
|
2058
|
-
{ name: "quit", description: "Quit Pi" },
|
|
2059
|
-
];
|
|
2060
|
-
|
|
2061
|
-
const COMMAND_SYNTAX_HINTS: Readonly<Record<string, string>> = {
|
|
2062
|
-
goal: "/goal [objective|clear|edit|pause|resume]",
|
|
2063
|
-
variants: "/variants [level]",
|
|
2064
|
-
model: "/model [provider/model]",
|
|
2065
|
-
"scoped-models": "/scoped-models",
|
|
2066
|
-
login: "/login [provider]",
|
|
2067
|
-
export: "/export [filename]",
|
|
2068
|
-
import: "/import [path]",
|
|
2069
|
-
name: "/name [session-name]",
|
|
2070
|
-
};
|
|
2071
|
-
|
|
2072
|
-
interface TaggedAutocompleteItem extends AutocompleteItem {
|
|
2073
|
-
killerosCommand?: string;
|
|
2074
|
-
}
|
|
2075
|
-
|
|
2076
|
-
function scoreCommandMatch(name: string, prefix: string): number {
|
|
2077
|
-
if (!prefix) return 1;
|
|
2078
|
-
const normalizedName = name.toLocaleLowerCase();
|
|
2079
|
-
const normalizedPrefix = prefix.toLocaleLowerCase();
|
|
2080
|
-
if (normalizedName.startsWith(normalizedPrefix)) return 100;
|
|
2081
|
-
if (normalizedName.split(/[:\-_]/).some((token) => token.startsWith(normalizedPrefix))) return 80;
|
|
2082
|
-
if (normalizedName.includes(normalizedPrefix)) return 50;
|
|
2083
|
-
return 0;
|
|
2084
|
-
}
|
|
2085
|
-
|
|
2086
|
-
function registerSlashAutocomplete(pi: ExtensionAPI): void {
|
|
2087
|
-
const usage = new Map<string, number>();
|
|
2088
|
-
pi.on("session_start", (_event, ctx) => {
|
|
2089
|
-
if (ctx.mode !== "tui") return;
|
|
2090
|
-
ctx.ui.addAutocompleteProvider((current) => ({
|
|
2091
|
-
triggerCharacters: ["/"],
|
|
2092
|
-
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
2093
|
-
const line = lines[cursorLine] ?? "";
|
|
2094
|
-
const beforeCursor = line.slice(0, cursorCol);
|
|
2095
|
-
const match = beforeCursor.match(/(?:^|[ \t])\/([^\s/]*)$/);
|
|
2096
|
-
if (!match) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
2097
|
-
|
|
2098
|
-
const prefix = (match[1] ?? "").toLocaleLowerCase();
|
|
2099
|
-
const baseSuggestions = await current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
2100
|
-
const commands = new Map<string, CommandInfo>();
|
|
2101
|
-
BUILTIN_COMMANDS.forEach((command) => commands.set(command.name, {
|
|
2102
|
-
...command,
|
|
2103
|
-
category: "Built-in",
|
|
2104
|
-
syntaxHint: COMMAND_SYNTAX_HINTS[command.name],
|
|
2105
|
-
}));
|
|
2106
|
-
|
|
2107
|
-
for (const command of pi.getCommands()) {
|
|
2108
|
-
const category: CommandInfo["category"] = command.source === "skill"
|
|
2109
|
-
? "Skill"
|
|
2110
|
-
: command.source === "prompt"
|
|
2111
|
-
? "Prompt"
|
|
2112
|
-
: "Extension";
|
|
2113
|
-
commands.set(command.name, {
|
|
2114
|
-
name: command.name,
|
|
2115
|
-
description: command.description,
|
|
2116
|
-
category,
|
|
2117
|
-
syntaxHint: COMMAND_SYNTAX_HINTS[command.name],
|
|
2118
|
-
});
|
|
2119
|
-
}
|
|
2120
|
-
|
|
2121
|
-
for (const item of baseSuggestions?.items ?? []) {
|
|
2122
|
-
const name = (item.value || item.label).replace(/^\//, "").trim().split(/\s+/)[0] ?? "";
|
|
2123
|
-
if (name && !commands.has(name)) {
|
|
2124
|
-
commands.set(name, { name, description: item.description, category: "Built-in" });
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
2127
|
-
|
|
2128
|
-
const ranked = [...commands.values()]
|
|
2129
|
-
.map((command) => ({
|
|
2130
|
-
command,
|
|
2131
|
-
score: scoreCommandMatch(command.name, prefix) + Math.min((usage.get(command.name) ?? 0) * 2, 15),
|
|
2132
|
-
}))
|
|
2133
|
-
.filter(({ command }) => scoreCommandMatch(command.name, prefix) > 0)
|
|
2134
|
-
.sort((left, right) => right.score - left.score || left.command.name.localeCompare(right.command.name));
|
|
2135
|
-
if (!ranked.length) return baseSuggestions;
|
|
2136
|
-
|
|
2137
|
-
return {
|
|
2138
|
-
prefix: `/${prefix}`,
|
|
2139
|
-
items: ranked.map(({ command }): TaggedAutocompleteItem => {
|
|
2140
|
-
const syntax = command.syntaxHint ? `${command.syntaxHint} — ` : "";
|
|
2141
|
-
return {
|
|
2142
|
-
value: `/${command.name} `,
|
|
2143
|
-
label: `/${command.name}`,
|
|
2144
|
-
description: `[${command.category}] ${syntax}${command.description ?? ""}`.trim(),
|
|
2145
|
-
killerosCommand: command.name,
|
|
2146
|
-
};
|
|
2147
|
-
}),
|
|
2148
|
-
};
|
|
2149
|
-
},
|
|
2150
|
-
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
2151
|
-
const tagged = item as TaggedAutocompleteItem;
|
|
2152
|
-
if (!tagged.killerosCommand) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
2153
|
-
usage.set(tagged.killerosCommand, (usage.get(tagged.killerosCommand) ?? 0) + 1);
|
|
2154
|
-
const line = lines[cursorLine] ?? "";
|
|
2155
|
-
const beforeCursor = line.slice(0, cursorCol);
|
|
2156
|
-
let afterCursor = line.slice(cursorCol);
|
|
2157
|
-
const match = beforeCursor.match(/(?:^|[ \t])\/([^\s/]*)$/);
|
|
2158
|
-
if (!match || match.index === undefined) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
2159
|
-
const slashIndex = match.index + (match[0].startsWith("/") ? 0 : 1);
|
|
2160
|
-
const newBefore = beforeCursor.slice(0, slashIndex) + item.value;
|
|
2161
|
-
if (item.value.endsWith(" ") && afterCursor.startsWith(" ")) afterCursor = afterCursor.trimStart();
|
|
2162
|
-
const nextLines = [...lines];
|
|
2163
|
-
nextLines[cursorLine] = newBefore + afterCursor;
|
|
2164
|
-
return { lines: nextLines, cursorLine, cursorCol: newBefore.length };
|
|
2165
|
-
},
|
|
2166
|
-
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
2167
|
-
return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
|
|
2168
|
-
},
|
|
2169
|
-
}));
|
|
2170
|
-
});
|
|
2171
|
-
}
|
|
2172
|
-
|
|
2173
|
-
type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
2174
|
-
|
|
2175
|
-
const ALL_LEVELS: readonly ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
2176
|
-
const LEVEL_LABELS: Readonly<Record<ThinkingLevel, string>> = {
|
|
2177
|
-
off: "Off",
|
|
2178
|
-
minimal: "Minimal",
|
|
2179
|
-
low: "Low",
|
|
2180
|
-
medium: "Medium",
|
|
2181
|
-
high: "High",
|
|
2182
|
-
xhigh: "Extra High",
|
|
2183
|
-
max: "Maximum",
|
|
2184
|
-
};
|
|
2185
|
-
const LEVEL_DESCRIPTIONS: Readonly<Record<ThinkingLevel, string>> = {
|
|
2186
|
-
off: "No extended reasoning",
|
|
2187
|
-
minimal: "Brief reasoning",
|
|
2188
|
-
low: "Light reasoning",
|
|
2189
|
-
medium: "Balanced reasoning",
|
|
2190
|
-
high: "Deep reasoning",
|
|
2191
|
-
xhigh: "Extensive reasoning",
|
|
2192
|
-
max: "Maximum supported reasoning",
|
|
2193
|
-
};
|
|
2194
|
-
const LEVEL_COLORS: Readonly<Record<ThinkingLevel, ThemeColor>> = {
|
|
2195
|
-
off: "thinkingOff",
|
|
2196
|
-
minimal: "thinkingMinimal",
|
|
2197
|
-
low: "thinkingLow",
|
|
2198
|
-
medium: "thinkingMedium",
|
|
2199
|
-
high: "thinkingHigh",
|
|
2200
|
-
xhigh: "thinkingXhigh",
|
|
2201
|
-
max: "thinkingMax",
|
|
2202
|
-
};
|
|
2203
|
-
const LEVEL_ALIASES: Readonly<Record<string, ThinkingLevel>> = {
|
|
2204
|
-
quick: "minimal",
|
|
2205
|
-
fast: "minimal",
|
|
2206
|
-
light: "low",
|
|
2207
|
-
balanced: "medium",
|
|
2208
|
-
deep: "high",
|
|
2209
|
-
maximum: "max",
|
|
2210
|
-
none: "off",
|
|
2211
|
-
};
|
|
2212
|
-
|
|
2213
|
-
function isThinkingLevel(value: string): value is ThinkingLevel {
|
|
2214
|
-
return (ALL_LEVELS as readonly string[]).includes(value);
|
|
2215
|
-
}
|
|
2216
|
-
|
|
2217
|
-
function resolveThinkingLevel(input: string): ThinkingLevel | undefined {
|
|
2218
|
-
const normalized = input.trim().toLocaleLowerCase();
|
|
2219
|
-
return isThinkingLevel(normalized) ? normalized : LEVEL_ALIASES[normalized];
|
|
2220
|
-
}
|
|
2221
|
-
|
|
2222
|
-
function supportedLevels(model: ExtensionContext["model"]): ThinkingLevel[] {
|
|
2223
|
-
if (!model?.reasoning) return ["off"];
|
|
2224
|
-
return ALL_LEVELS.filter((level) => {
|
|
2225
|
-
const mapped = model.thinkingLevelMap?.[level];
|
|
2226
|
-
if (mapped === null) return false;
|
|
2227
|
-
return level !== "xhigh" && level !== "max" || mapped !== undefined;
|
|
2228
|
-
});
|
|
2229
|
-
}
|
|
2230
|
-
|
|
2231
|
-
function modelLabel(model: ExtensionContext["model"]): string {
|
|
2232
|
-
return model ? `${model.provider}/${model.id}` : "unknown model";
|
|
2233
|
-
}
|
|
2234
|
-
|
|
2235
|
-
function registerVariants(pi: ExtensionAPI): void {
|
|
2236
|
-
const setLevel = (ctx: ExtensionContext, level: ThinkingLevel): void => {
|
|
2237
|
-
const supported = supportedLevels(ctx.model);
|
|
2238
|
-
if (!supported.includes(level)) {
|
|
2239
|
-
ctx.ui.notify(`${LEVEL_LABELS[level]} is not supported by ${modelLabel(ctx.model)}. Supported: ${supported.join(", ")}`, "warning");
|
|
2240
|
-
return;
|
|
2241
|
-
}
|
|
2242
|
-
pi.setThinkingLevel(level);
|
|
2243
|
-
ctx.ui.notify(`Thinking: ${LEVEL_LABELS[level]}`, "info");
|
|
2244
|
-
};
|
|
2245
|
-
|
|
2246
|
-
pi.registerCommand("variants", {
|
|
2247
|
-
description: "Set reasoning level: off, minimal, low, medium, high, xhigh, or max",
|
|
2248
|
-
handler: async (args, ctx) => {
|
|
2249
|
-
if (args.trim()) {
|
|
2250
|
-
const level = resolveThinkingLevel(args);
|
|
2251
|
-
if (!level) {
|
|
2252
|
-
ctx.ui.notify(`Unknown reasoning level "${args.trim()}". Use: ${ALL_LEVELS.join(", ")}`, "error");
|
|
2253
|
-
return;
|
|
2254
|
-
}
|
|
2255
|
-
setLevel(ctx, level);
|
|
2256
|
-
return;
|
|
2257
|
-
}
|
|
2258
|
-
if (ctx.mode !== "tui") {
|
|
2259
|
-
ctx.ui.notify("Use /variants <level> outside TUI mode", "error");
|
|
2260
|
-
return;
|
|
2261
|
-
}
|
|
2262
|
-
|
|
2263
|
-
const supported = supportedLevels(ctx.model);
|
|
2264
|
-
if (supported.length === 1) {
|
|
2265
|
-
ctx.ui.notify(`${modelLabel(ctx.model)} does not support extended reasoning`, "info");
|
|
2266
|
-
return;
|
|
2267
|
-
}
|
|
2268
|
-
const current = pi.getThinkingLevel() as ThinkingLevel;
|
|
2269
|
-
const items = supported.map((level) => ({
|
|
2270
|
-
value: level,
|
|
2271
|
-
label: level === current ? `${LEVEL_LABELS[level]} ← current` : LEVEL_LABELS[level],
|
|
2272
|
-
description: LEVEL_DESCRIPTIONS[level],
|
|
2273
|
-
}));
|
|
2274
|
-
const selected = await ctx.ui.custom<ThinkingLevel | null>((tui, theme, _keybindings, done) => {
|
|
2275
|
-
const container = new Container();
|
|
2276
|
-
container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
|
|
2277
|
-
container.addChild(new Text(theme.fg("accent", theme.bold("Thinking variants")), 1, 0));
|
|
2278
|
-
container.addChild(new Text(theme.fg("dim", `Model: ${modelLabel(ctx.model)}`), 1, 0));
|
|
2279
|
-
container.addChild(new Text("", 0, 0));
|
|
2280
|
-
const selectList = new SelectList(items, Math.min(items.length, 10), {
|
|
2281
|
-
selectedPrefix: (text) => theme.fg("accent", text),
|
|
2282
|
-
selectedText: (text) => theme.fg("accent", text),
|
|
2283
|
-
description: (text) => theme.fg("muted", text),
|
|
2284
|
-
scrollInfo: (text) => theme.fg("dim", text),
|
|
2285
|
-
noMatch: (text) => theme.fg("warning", text),
|
|
2286
|
-
});
|
|
2287
|
-
selectList.onSelect = (item) => done(isThinkingLevel(item.value) ? item.value : null);
|
|
2288
|
-
selectList.onCancel = () => done(null);
|
|
2289
|
-
container.addChild(selectList);
|
|
2290
|
-
container.addChild(new Text("", 0, 0));
|
|
2291
|
-
container.addChild(new Text(theme.fg("dim", "↑↓ navigate • Enter select • Esc cancel"), 1, 0));
|
|
2292
|
-
container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
|
|
2293
|
-
return {
|
|
2294
|
-
render: (width) => container.render(width).map((line) => truncateToWidth(line, width, "")),
|
|
2295
|
-
invalidate: () => container.invalidate(),
|
|
2296
|
-
handleInput: (data) => {
|
|
2297
|
-
selectList.handleInput(data);
|
|
2298
|
-
tui.requestRender();
|
|
2299
|
-
},
|
|
2300
|
-
};
|
|
2301
|
-
});
|
|
2302
|
-
if (selected) setLevel(ctx, selected);
|
|
2303
|
-
},
|
|
2304
|
-
});
|
|
2305
|
-
}
|
|
2306
|
-
|
|
2307
|
-
export function formatCost(usd: number): string {
|
|
2308
|
-
if (!Number.isFinite(usd)) return "$—";
|
|
2309
|
-
return `$${usd.toFixed(2)}`;
|
|
2310
|
-
}
|
|
2311
|
-
|
|
2312
|
-
function formatTime(milliseconds: number): string {
|
|
2313
|
-
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1_000));
|
|
2314
|
-
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
2315
|
-
const minutes = Math.floor(totalSeconds / 60);
|
|
2316
|
-
if (minutes < 60) return `${minutes}m`;
|
|
2317
|
-
return `${Math.floor(minutes / 60)}h${minutes % 60}m`;
|
|
2318
|
-
}
|
|
2319
|
-
|
|
2320
|
-
function formatTokens(value: number): string {
|
|
2321
|
-
const amount = Math.max(0, value);
|
|
2322
|
-
if (amount < 1_000) return `${Math.round(amount)}`;
|
|
2323
|
-
if (amount >= 1_000_000) {
|
|
2324
|
-
const precision = amount >= 10_000_000 ? 0 : 1;
|
|
2325
|
-
return `${Number((amount / 1_000_000).toFixed(precision))}M`;
|
|
2326
|
-
}
|
|
2327
|
-
const precision = amount >= 100_000 ? 0 : 1;
|
|
2328
|
-
return `${Number((amount / 1_000).toFixed(precision))}k`;
|
|
2329
|
-
}
|
|
2330
|
-
|
|
2331
|
-
export function formatContextProgress(tokensUsed: number | null, contextWindow: number, theme: Theme): string {
|
|
2332
|
-
if (tokensUsed === null) return theme.fg("dim", "—% left (—)");
|
|
2333
|
-
const windowSize = contextWindow > 0 ? contextWindow : 128_000;
|
|
2334
|
-
const remaining = Math.max(0, Math.min(windowSize, windowSize - Math.max(0, tokensUsed)));
|
|
2335
|
-
const percentLeft = Math.max(0, Math.min(100, Math.round((remaining / windowSize) * 100)));
|
|
2336
|
-
const color: ThemeColor = percentLeft < 20 ? "error" : percentLeft <= 50 ? "warning" : "success";
|
|
2337
|
-
const action = percentLeft < 15 ? " · /compact" : "";
|
|
2338
|
-
return theme.fg(color, `${percentLeft}% left (${formatTokens(remaining)})${action}`);
|
|
2339
|
-
}
|
|
2340
|
-
|
|
2341
|
-
function sumSessionCost(ctx: ExtensionContext): number {
|
|
2342
|
-
let total = 0;
|
|
2343
|
-
for (const entry of ctx.sessionManager.getEntries()) {
|
|
2344
|
-
if (entry.type === "message" && entry.message.role === "assistant") total += entry.message.usage.cost.total;
|
|
2345
|
-
else if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.usage) {
|
|
2346
|
-
total += entry.message.usage.cost.total;
|
|
2347
|
-
} else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
|
|
2348
|
-
total += entry.usage.cost.total;
|
|
2349
|
-
}
|
|
2350
|
-
}
|
|
2351
|
-
return total;
|
|
2352
|
-
}
|
|
2353
|
-
|
|
2354
|
-
const PROVIDER_LABELS: Readonly<Record<string, string>> = {
|
|
2355
|
-
"amazon-bedrock": "Amazon Bedrock",
|
|
2356
|
-
"azure-openai-responses": "Azure OpenAI",
|
|
2357
|
-
"github-copilot": "GitHub Copilot",
|
|
2358
|
-
"google-vertex": "Google Vertex",
|
|
2359
|
-
"openai-codex": "OpenAI",
|
|
2360
|
-
anthropic: "Anthropic",
|
|
2361
|
-
deepseek: "DeepSeek",
|
|
2362
|
-
google: "Google",
|
|
2363
|
-
ollama: "Ollama",
|
|
2364
|
-
openai: "OpenAI",
|
|
2365
|
-
openrouter: "OpenRouter",
|
|
2366
|
-
};
|
|
2367
|
-
|
|
2368
|
-
const PROVIDER_WORDS: Readonly<Record<string, string>> = {
|
|
2369
|
-
ai: "AI",
|
|
2370
|
-
api: "API",
|
|
2371
|
-
deepseek: "DeepSeek",
|
|
2372
|
-
github: "GitHub",
|
|
2373
|
-
llm: "LLM",
|
|
2374
|
-
openai: "OpenAI",
|
|
2375
|
-
openrouter: "OpenRouter",
|
|
2376
|
-
};
|
|
2377
|
-
|
|
2378
|
-
function formatProviderName(provider: string): string {
|
|
2379
|
-
const normalized = provider.trim();
|
|
2380
|
-
const known = PROVIDER_LABELS[normalized.toLocaleLowerCase()];
|
|
2381
|
-
if (known) return known;
|
|
2382
|
-
return normalized
|
|
2383
|
-
.split(/[-_]+/u)
|
|
2384
|
-
.filter(Boolean)
|
|
2385
|
-
.map((word) => PROVIDER_WORDS[word.toLocaleLowerCase()] ?? `${word.charAt(0).toLocaleUpperCase()}${word.slice(1)}`)
|
|
2386
|
-
.join(" ") || "Unknown provider";
|
|
2387
|
-
}
|
|
2388
|
-
|
|
2389
|
-
function modelDisplayName(model: NonNullable<ExtensionContext["model"]>): string {
|
|
2390
|
-
return model.name?.trim() || model.id;
|
|
2391
|
-
}
|
|
2392
|
-
|
|
2393
|
-
function formatModel(model: ExtensionContext["model"], theme: Theme, includeProvider = true): string {
|
|
2394
|
-
if (!model) return theme.fg("dim", "No model");
|
|
2395
|
-
const name = theme.fg("text", theme.bold(modelDisplayName(model)));
|
|
2396
|
-
return includeProvider ? `${name} ${theme.fg("dim", formatProviderName(model.provider))}` : name;
|
|
2397
|
-
}
|
|
2398
|
-
|
|
2399
|
-
function compactDirectory(cwd: string): string {
|
|
2400
|
-
if (cwd === "~" || cwd === "/" || /^[A-Za-z]:[\\/]?$/u.test(cwd)) return cwd;
|
|
2401
|
-
const normalized = cwd.replace(/\\/gu, "/").replace(/\/$/u, "");
|
|
2402
|
-
const finalSegment = normalized.split("/").at(-1);
|
|
2403
|
-
return finalSegment ? `…/${finalSegment}` : cwd;
|
|
2404
|
-
}
|
|
2405
|
-
|
|
2406
|
-
function joinFooterParts(parts: string[], theme: Theme): string {
|
|
2407
|
-
return parts.filter(Boolean).join(theme.fg("dim", " · "));
|
|
2408
|
-
}
|
|
2409
|
-
|
|
2410
|
-
function footerRowFits(left: string, right: string, width: number): boolean {
|
|
2411
|
-
const contentWidth = visibleWidth(left) + (right ? visibleWidth(right) + 1 : 0);
|
|
2412
|
-
return contentWidth + 2 <= width;
|
|
2413
|
-
}
|
|
2414
|
-
|
|
2415
|
-
function renderFooterRow(left: string, right: string, width: number): string {
|
|
2416
|
-
if (width <= 0) return "";
|
|
2417
|
-
if (width < 3) return " ".repeat(width);
|
|
2418
|
-
|
|
2419
|
-
const innerWidth = width - 2;
|
|
2420
|
-
if (!right) return ` ${padRight(left, innerWidth)} `;
|
|
2421
|
-
|
|
2422
|
-
const clippedRight = truncateToWidth(right, innerWidth, "");
|
|
2423
|
-
const rightWidth = visibleWidth(clippedRight);
|
|
2424
|
-
const leftBudget = Math.max(0, innerWidth - rightWidth - 1);
|
|
2425
|
-
const clippedLeft = truncateToWidth(left, leftBudget, "…");
|
|
2426
|
-
const gap = " ".repeat(Math.max(0, innerWidth - visibleWidth(clippedLeft) - rightWidth));
|
|
2427
|
-
return ` ${clippedLeft}${gap}${clippedRight} `;
|
|
2428
|
-
}
|
|
2429
|
-
|
|
2430
|
-
function formatGoalFooter(state: GoalState | undefined, theme: Theme): string {
|
|
2431
|
-
if (!state) return "";
|
|
2432
|
-
if (state.status === "active") return theme.fg("accent", `✻ goal · ${formatTime(goalElapsedMilliseconds(state))}`);
|
|
2433
|
-
if (state.status === "paused") return theme.fg("warning", "Ⅱ goal paused");
|
|
2434
|
-
if (state.status === "blocked") return theme.fg("error", "! goal blocked");
|
|
2435
|
-
return theme.fg("success", "✓ goal complete");
|
|
2436
|
-
}
|
|
2437
|
-
|
|
2438
|
-
function registerFooter(pi: ExtensionAPI, goalRuntime: GoalRuntime): void {
|
|
2439
|
-
let currentModel: ExtensionContext["model"];
|
|
2440
|
-
let thinkingLevel: ThinkingLevel = "off";
|
|
2441
|
-
let activeTui: TUI | undefined;
|
|
2442
|
-
goalRuntime.requestRender = () => activeTui?.requestRender();
|
|
2443
|
-
|
|
2444
|
-
pi.on("session_start", (_event, ctx) => {
|
|
2445
|
-
if (ctx.mode !== "tui") return;
|
|
2446
|
-
const sessionStart = Date.now();
|
|
2447
|
-
currentModel = ctx.model;
|
|
2448
|
-
thinkingLevel = pi.getThinkingLevel() as ThinkingLevel;
|
|
2449
|
-
const cwd = formatCwd(ctx.cwd);
|
|
2450
|
-
|
|
2451
|
-
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
2452
|
-
activeTui = tui;
|
|
2453
|
-
const unsubscribe = footerData.onBranchChange(() => tui.requestRender());
|
|
2454
|
-
const refreshTimer = setInterval(() => tui.requestRender(), FOOTER_REFRESH_INTERVAL_MS);
|
|
2455
|
-
refreshTimer.unref?.();
|
|
2456
|
-
return {
|
|
2457
|
-
dispose() {
|
|
2458
|
-
unsubscribe();
|
|
2459
|
-
clearInterval(refreshTimer);
|
|
2460
|
-
if (activeTui === tui) activeTui = undefined;
|
|
2461
|
-
},
|
|
2462
|
-
invalidate() {},
|
|
2463
|
-
render(width: number): string[] {
|
|
2464
|
-
if (width <= 0) return [];
|
|
2465
|
-
const model = currentModel ?? ctx.model;
|
|
2466
|
-
const level = model?.reasoning === false
|
|
2467
|
-
? theme.fg("thinkingOff", "no reasoning")
|
|
2468
|
-
: theme.fg(LEVEL_COLORS[thinkingLevel], thinkingLevel);
|
|
2469
|
-
const usage = ctx.getContextUsage();
|
|
2470
|
-
const contextWindow = usage?.contextWindow ?? model?.contextWindow ?? 128_000;
|
|
2471
|
-
const context = formatContextProgress(usage?.tokens ?? null, contextWindow, theme);
|
|
2472
|
-
const branch = footerData.getGitBranch();
|
|
2473
|
-
const signature = formatModel(model, theme);
|
|
2474
|
-
const fullDirectory = theme.fg("dim", cwd);
|
|
2475
|
-
const focusedDirectory = theme.fg("dim", compactDirectory(cwd));
|
|
2476
|
-
const goal = formatGoalFooter(goalRuntime.state, theme);
|
|
2477
|
-
const rich = joinFooterParts([
|
|
2478
|
-
signature,
|
|
2479
|
-
level,
|
|
2480
|
-
context,
|
|
2481
|
-
goal,
|
|
2482
|
-
branch ? theme.fg("dim", branch) : "",
|
|
2483
|
-
theme.fg("dim", formatTime(Date.now() - sessionStart)),
|
|
2484
|
-
theme.fg("dim", formatCost(sumSessionCost(ctx))),
|
|
2485
|
-
], theme);
|
|
2486
|
-
const focused = joinFooterParts([signature, context, goal], theme);
|
|
2487
|
-
|
|
2488
|
-
if (footerRowFits(rich, fullDirectory, width)) {
|
|
2489
|
-
return [renderFooterRow(rich, fullDirectory, width)];
|
|
2490
|
-
}
|
|
2491
|
-
if (footerRowFits(rich, focusedDirectory, width)) {
|
|
2492
|
-
return [renderFooterRow(rich, focusedDirectory, width)];
|
|
2493
|
-
}
|
|
2494
|
-
if (footerRowFits(focused, focusedDirectory, width)) {
|
|
2495
|
-
return [renderFooterRow(focused, focusedDirectory, width)];
|
|
2496
|
-
}
|
|
2497
|
-
if (footerRowFits(focused, "", width)) {
|
|
2498
|
-
return [renderFooterRow(focused, "", width)];
|
|
2499
|
-
}
|
|
2500
|
-
if (goal) {
|
|
2501
|
-
const essentialGoal = joinFooterParts([context, goal], theme);
|
|
2502
|
-
if (footerRowFits(essentialGoal, "", width)) return [renderFooterRow(essentialGoal, "", width)];
|
|
2503
|
-
return [renderFooterRow(goal, context, width)];
|
|
2504
|
-
}
|
|
2505
|
-
|
|
2506
|
-
const essentialModel = formatModel(model, theme, false);
|
|
2507
|
-
return [renderFooterRow(essentialModel, context, width)];
|
|
2508
|
-
},
|
|
2509
|
-
};
|
|
2510
|
-
});
|
|
2511
|
-
});
|
|
2512
|
-
|
|
2513
|
-
pi.on("model_select", (event) => {
|
|
2514
|
-
currentModel = event.model;
|
|
2515
|
-
activeTui?.requestRender();
|
|
2516
|
-
});
|
|
2517
|
-
pi.on("thinking_level_select", (event) => {
|
|
2518
|
-
thinkingLevel = event.level;
|
|
2519
|
-
activeTui?.requestRender();
|
|
2520
|
-
});
|
|
2521
|
-
pi.on("session_shutdown", () => {
|
|
2522
|
-
activeTui = undefined;
|
|
2523
|
-
goalRuntime.requestRender = undefined;
|
|
2524
|
-
});
|
|
2525
|
-
}
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { registerSubagentTool } from "./killeros/subagents.ts";
|
|
3
|
+
import { registerAliases, registerSlashAutocomplete } from "./killeros/commands.ts";
|
|
4
|
+
import { registerConcisePrompt } from "./killeros/concise.ts";
|
|
5
|
+
import { registerFooter } from "./killeros/footer.ts";
|
|
6
|
+
import { registerGoal, registerGoalSettlement } from "./killeros/goals.ts";
|
|
7
|
+
import { registerLifecycleHooks } from "./killeros/hooks.ts";
|
|
8
|
+
import { registerInitCommand, registerInitSettlement } from "./killeros/init.ts";
|
|
9
|
+
import { registerPersonalInstructions } from "./killeros/personal-instructions.ts";
|
|
10
|
+
import { registerQuestionTool } from "./killeros/question.ts";
|
|
11
|
+
import { createGoalRuntime, createInitRuntime } from "./killeros/runtime.ts";
|
|
12
|
+
import { registerShellUi } from "./killeros/shell-ui.ts";
|
|
13
|
+
import { registerVariants } from "./killeros/variants.ts";
|
|
14
|
+
|
|
15
|
+
export { CONCISE_SYSTEM_PROMPT, isConcisedEnabled } from "./killeros/concise.ts";
|
|
16
|
+
export { formatCost, formatContextProgress } from "./killeros/footer.ts";
|
|
17
|
+
export { executeHook } from "./killeros/hooks.ts";
|
|
18
|
+
export { INIT_WORKFLOW_PROMPT, writeInitAgentsFile } from "./killeros/init.ts";
|
|
2526
19
|
|
|
2527
20
|
export default function Killeros(pi: ExtensionAPI): void {
|
|
2528
|
-
const
|
|
2529
|
-
|
|
2530
|
-
writeAttempted: false,
|
|
2531
|
-
writeSucceeded: false,
|
|
2532
|
-
};
|
|
2533
|
-
const goalRuntime: GoalRuntime = {
|
|
2534
|
-
continuationScheduled: false,
|
|
2535
|
-
continuationHeld: false,
|
|
2536
|
-
goalTurnInFlight: false,
|
|
2537
|
-
agentEndObserved: false,
|
|
2538
|
-
persistenceRetryNeeded: false,
|
|
2539
|
-
};
|
|
21
|
+
const initRuntime = createInitRuntime();
|
|
22
|
+
const goalRuntime = createGoalRuntime();
|
|
2540
23
|
registerShellUi(pi);
|
|
2541
24
|
registerConcisePrompt(pi);
|
|
2542
|
-
registerGoal(pi, goalRuntime,
|
|
2543
|
-
registerPersonalInstructions(pi,
|
|
25
|
+
registerGoal(pi, goalRuntime, initRuntime);
|
|
26
|
+
registerPersonalInstructions(pi, initRuntime);
|
|
2544
27
|
registerQuestionTool(pi);
|
|
2545
28
|
registerSubagentTool(pi);
|
|
2546
29
|
registerAliases(pi);
|
|
2547
30
|
registerSlashAutocomplete(pi);
|
|
2548
31
|
registerFooter(pi, goalRuntime);
|
|
2549
32
|
registerVariants(pi);
|
|
2550
|
-
registerInitCommand(pi,
|
|
33
|
+
registerInitCommand(pi, initRuntime, goalRuntime);
|
|
2551
34
|
registerLifecycleHooks(pi);
|
|
2552
|
-
registerGoalSettlement(pi, goalRuntime,
|
|
2553
|
-
registerInitSettlement(pi,
|
|
35
|
+
registerGoalSettlement(pi, goalRuntime, initRuntime);
|
|
36
|
+
registerInitSettlement(pi, initRuntime);
|
|
2554
37
|
}
|