@hcflabs/pi-herdr-tools 0.0.0-stage → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +167 -2
- package/docs/btw-merge-sequence.html +156 -0
- package/docs/btw-merge-sequence.svg +138 -0
- package/docs/clone-flow.html +171 -0
- package/docs/clone-flow.svg +146 -0
- package/docs/done-flow.html +213 -0
- package/docs/done-flow.svg +196 -0
- package/extensions/index.ts +40 -0
- package/internal/btw.ts +770 -0
- package/internal/clone-tab.ts +228 -0
- package/internal/config.ts +67 -0
- package/internal/context-store.ts +282 -0
- package/internal/core.ts +386 -0
- package/internal/done.ts +99 -0
- package/internal/handoff.ts +132 -0
- package/internal/merge.ts +306 -0
- package/internal/recap.ts +159 -0
- package/internal/rename.ts +408 -0
- package/internal/router.ts +42 -0
- package/internal/task-models.ts +51 -0
- package/internal/worktree.ts +243 -0
- package/package.json +38 -4
- package/prompts/handoff-worktree.md +13 -0
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { BtwPayload } from "./core.ts";
|
|
3
|
+
|
|
4
|
+
export const MERGE_PROTOCOL_VERSION = 2 as const;
|
|
5
|
+
export const MERGE_REQUEST_FILE = "merge-request.json";
|
|
6
|
+
export const MERGE_CUSTOM_TYPE = "pi-herdr-btw.merge";
|
|
7
|
+
const MAX_SUMMARY_BYTES = 64 * 1024;
|
|
8
|
+
export const MAX_PROMPT_BYTES = 16 * 1024;
|
|
9
|
+
/** Transcript budget stays well under MAX_SUMMARY_BYTES for JSON overhead. */
|
|
10
|
+
const MERGE_TRANSCRIPT_BUDGET_BYTES = 48 * 1024;
|
|
11
|
+
const TRANSCRIPT_TRUNCATION_NOTE =
|
|
12
|
+
"[earlier side-thread turns omitted to fit the merge budget]";
|
|
13
|
+
|
|
14
|
+
export type MergeRequest = {
|
|
15
|
+
protocolVersion: typeof MERGE_PROTOCOL_VERSION;
|
|
16
|
+
requestId: string;
|
|
17
|
+
launchId: string;
|
|
18
|
+
parentSessionId: string;
|
|
19
|
+
capability: string;
|
|
20
|
+
createdAt: string;
|
|
21
|
+
/** Trimmed, 1..64 KiB packaged side-thread transcript. */
|
|
22
|
+
summary: string;
|
|
23
|
+
/** Trimmed, 1..16 KiB user prompt the parent auto-submits after the merge. */
|
|
24
|
+
prompt: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function isMergeRequest(value: unknown): value is MergeRequest {
|
|
28
|
+
if (!value || typeof value !== "object") return false;
|
|
29
|
+
const request = value as Partial<MergeRequest>;
|
|
30
|
+
return (
|
|
31
|
+
request.protocolVersion === MERGE_PROTOCOL_VERSION &&
|
|
32
|
+
typeof request.requestId === "string" &&
|
|
33
|
+
request.requestId.length > 0 &&
|
|
34
|
+
typeof request.launchId === "string" &&
|
|
35
|
+
request.launchId.length > 0 &&
|
|
36
|
+
typeof request.parentSessionId === "string" &&
|
|
37
|
+
request.parentSessionId.length > 0 &&
|
|
38
|
+
typeof request.capability === "string" &&
|
|
39
|
+
request.capability.length >= 32 &&
|
|
40
|
+
typeof request.createdAt === "string" &&
|
|
41
|
+
typeof request.summary === "string" &&
|
|
42
|
+
isSummaryWithinBounds(request.summary) &&
|
|
43
|
+
typeof request.prompt === "string" &&
|
|
44
|
+
isPromptWithinBounds(request.prompt)
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isSummaryWithinBounds(summary: string): boolean {
|
|
49
|
+
const trimmed = summary.trim();
|
|
50
|
+
return trimmed.length > 0 && Buffer.byteLength(trimmed, "utf8") <= MAX_SUMMARY_BYTES;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function isPromptWithinBounds(prompt: string): boolean {
|
|
54
|
+
const trimmed = prompt.trim();
|
|
55
|
+
return trimmed.length > 0 && Buffer.byteLength(trimmed, "utf8") <= MAX_PROMPT_BYTES;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A merge request is trusted only when it echoes the exact launch identity,
|
|
60
|
+
* capability token, and parent session binding of its own launch payload.
|
|
61
|
+
*/
|
|
62
|
+
function validateRequestAgainstPayload(
|
|
63
|
+
request: MergeRequest,
|
|
64
|
+
payload: BtwPayload,
|
|
65
|
+
): string | undefined {
|
|
66
|
+
if (request.launchId !== payload.launchId) return "launch ID mismatch";
|
|
67
|
+
if (request.capability !== payload.capability) return "capability mismatch";
|
|
68
|
+
if (request.parentSessionId !== payload.parentSessionId) return "parent session mismatch";
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buildMergeMessageContent(summary: string): string {
|
|
73
|
+
return `Merged from /btw (side-thread transcript)\n\n<btw-merge>\n${summary.trim()}\n</btw-merge>`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type EntryLike = {
|
|
77
|
+
type: string;
|
|
78
|
+
customType?: string;
|
|
79
|
+
details?: unknown;
|
|
80
|
+
message?: { role?: unknown; content?: unknown };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
function isMergeEntry(entry: EntryLike, requestId: string): boolean {
|
|
84
|
+
return (
|
|
85
|
+
entry.type === "custom_message" &&
|
|
86
|
+
entry.customType === MERGE_CUSTOM_TYPE &&
|
|
87
|
+
!!entry.details &&
|
|
88
|
+
typeof entry.details === "object" &&
|
|
89
|
+
(entry.details as { requestId?: unknown }).requestId === requestId
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Deduplicate against an already-persisted merge custom message by requestId. */
|
|
94
|
+
function hasMergedRequestId(entries: EntryLike[], requestId: string): boolean {
|
|
95
|
+
return entries.some((entry) => isMergeEntry(entry, requestId));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Detect durable evidence that this merge's user prompt was persisted. */
|
|
99
|
+
function hasSubmittedPromptRequestId(
|
|
100
|
+
entries: EntryLike[],
|
|
101
|
+
requestId: string,
|
|
102
|
+
prompt: string,
|
|
103
|
+
): boolean {
|
|
104
|
+
const mergeIndex = entries.findIndex(
|
|
105
|
+
(entry) => isMergeEntry(entry, requestId) && (entry.details as { prompt?: unknown }).prompt === prompt,
|
|
106
|
+
);
|
|
107
|
+
return mergeIndex >= 0 && entries.slice(mergeIndex + 1).some(
|
|
108
|
+
(entry) => entry.type === "message" && entry.message?.role === "user" && textOfTurn(entry.message.content) === prompt.trim(),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function textOfTurn(content: unknown): string {
|
|
113
|
+
if (typeof content === "string") return content.trim();
|
|
114
|
+
if (!Array.isArray(content)) return "";
|
|
115
|
+
return content
|
|
116
|
+
.filter(
|
|
117
|
+
(block): block is { type: "text"; text: string } =>
|
|
118
|
+
!!block && typeof block === "object" && block.type === "text" && typeof block.text === "string",
|
|
119
|
+
)
|
|
120
|
+
.map((block) => block.text)
|
|
121
|
+
.join("\n")
|
|
122
|
+
.trim();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Keep at most maxBytes of UTF-8 from the tail of the text. */
|
|
126
|
+
export function tailBytes(text: string, maxBytes: number): string {
|
|
127
|
+
let sliced = text.slice(-maxBytes);
|
|
128
|
+
while (Buffer.byteLength(sliced, "utf8") > maxBytes) {
|
|
129
|
+
const excess = Buffer.byteLength(sliced, "utf8") - maxBytes;
|
|
130
|
+
sliced = sliced.slice(Math.max(1, Math.ceil(excess / 4)));
|
|
131
|
+
}
|
|
132
|
+
return sliced;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Package the child's own conversation (user/assistant text turns only, no
|
|
137
|
+
* tool payloads) as the merge transcript. When over budget, whole turns are
|
|
138
|
+
* dropped from the head so the most recent findings survive.
|
|
139
|
+
*/
|
|
140
|
+
export function buildMergeTranscript(messages: AgentMessage[]): string | undefined {
|
|
141
|
+
const turns: string[] = [];
|
|
142
|
+
for (const message of messages) {
|
|
143
|
+
const { role, content } = message as { role?: string; content?: unknown };
|
|
144
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
145
|
+
const text = textOfTurn(content);
|
|
146
|
+
if (text) turns.push(`${role === "user" ? "User" : "Assistant"}:\n${text}`);
|
|
147
|
+
}
|
|
148
|
+
if (turns.length === 0) return undefined;
|
|
149
|
+
|
|
150
|
+
const kept: string[] = [];
|
|
151
|
+
let used = 0;
|
|
152
|
+
for (let index = turns.length - 1; index >= 0; index -= 1) {
|
|
153
|
+
const turn = turns[index] as string;
|
|
154
|
+
const bytes = Buffer.byteLength(turn, "utf8") + 2;
|
|
155
|
+
if (used + bytes > MERGE_TRANSCRIPT_BUDGET_BYTES) {
|
|
156
|
+
if (kept.length === 0) {
|
|
157
|
+
// A single oversized turn keeps its tail (the latest content).
|
|
158
|
+
kept.unshift(`${TRANSCRIPT_TRUNCATION_NOTE}\n${tailBytes(turn, MERGE_TRANSCRIPT_BUDGET_BYTES)}`);
|
|
159
|
+
} else {
|
|
160
|
+
kept.unshift(TRANSCRIPT_TRUNCATION_NOTE);
|
|
161
|
+
}
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
kept.unshift(turn);
|
|
165
|
+
used += bytes;
|
|
166
|
+
}
|
|
167
|
+
return kept.join("\n\n");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
type MergeStorePort = {
|
|
171
|
+
listLaunchPayloadPaths(): Promise<string[]>;
|
|
172
|
+
read(payloadPath: string): Promise<BtwPayload>;
|
|
173
|
+
readMergeRequest(payloadPath: string): Promise<unknown>;
|
|
174
|
+
remove(payloadPath: string): Promise<void>;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
type ParentSessionPort = {
|
|
178
|
+
getSessionId(): string;
|
|
179
|
+
isIdle(): boolean;
|
|
180
|
+
getBranch(): EntryLike[];
|
|
181
|
+
/** Check model and authentication before consuming a merge request. */
|
|
182
|
+
canSubmitPrompt(): Promise<boolean>;
|
|
183
|
+
sendMergeMessage(content: string, details: { requestId: string; launchId: string; prompt: string }): void;
|
|
184
|
+
/** Submit the merge prompt as a user message that triggers a model turn. */
|
|
185
|
+
submitPrompt(prompt: string): void;
|
|
186
|
+
notify(message: string, type: "info" | "warning" | "error"): void;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
type ScanResult = {
|
|
190
|
+
delivered: number;
|
|
191
|
+
deferred: number;
|
|
192
|
+
rejected: number;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Parent-side merge coordinator. Scans the private launch store for pending
|
|
197
|
+
* merge requests bound to the current parent session and consumes each after
|
|
198
|
+
* delivery or rejection.
|
|
199
|
+
*/
|
|
200
|
+
export class MergeCoordinator {
|
|
201
|
+
private readonly store: MergeStorePort;
|
|
202
|
+
private readonly session: ParentSessionPort;
|
|
203
|
+
private scanning = false;
|
|
204
|
+
|
|
205
|
+
constructor(store: MergeStorePort, session: ParentSessionPort) {
|
|
206
|
+
this.store = store;
|
|
207
|
+
this.session = session;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async scan(): Promise<ScanResult> {
|
|
211
|
+
if (this.scanning) return { delivered: 0, deferred: 0, rejected: 0 };
|
|
212
|
+
this.scanning = true;
|
|
213
|
+
try {
|
|
214
|
+
return await this.scanOnce();
|
|
215
|
+
} finally {
|
|
216
|
+
this.scanning = false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private async scanOnce(): Promise<ScanResult> {
|
|
221
|
+
const result: ScanResult = { delivered: 0, deferred: 0, rejected: 0 };
|
|
222
|
+
let payloadPaths: string[];
|
|
223
|
+
try {
|
|
224
|
+
payloadPaths = await this.store.listLaunchPayloadPaths();
|
|
225
|
+
} catch {
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
for (const payloadPath of payloadPaths) {
|
|
230
|
+
if (result.delivered > 0) break;
|
|
231
|
+
try {
|
|
232
|
+
await this.processLaunch(payloadPath, result);
|
|
233
|
+
} catch {
|
|
234
|
+
// Unsafe or unreadable launch directories are skipped, never trusted.
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private async processLaunch(payloadPath: string, result: ScanResult): Promise<void> {
|
|
241
|
+
const rawRequest = await this.store.readMergeRequest(payloadPath);
|
|
242
|
+
if (rawRequest === undefined) return;
|
|
243
|
+
|
|
244
|
+
const payload = await this.store.read(payloadPath);
|
|
245
|
+
// Only the session a launch is bound to may consume its merge requests.
|
|
246
|
+
if (payload.parentSessionId !== this.session.getSessionId()) return;
|
|
247
|
+
|
|
248
|
+
if (!isMergeRequest(rawRequest)) {
|
|
249
|
+
await this.reject(payloadPath, "malformed merge request");
|
|
250
|
+
result.rejected += 1;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const validationError = validateRequestAgainstPayload(rawRequest, payload);
|
|
254
|
+
if (validationError) {
|
|
255
|
+
await this.reject(payloadPath, validationError);
|
|
256
|
+
result.rejected += 1;
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const entries = this.session.getBranch();
|
|
261
|
+
if (hasSubmittedPromptRequestId(entries, rawRequest.requestId, rawRequest.prompt)) {
|
|
262
|
+
await this.store.remove(payloadPath);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// pi.sendUserMessage() is fire-and-forget. Keep the request pending when
|
|
267
|
+
// current model/auth state would reject its prompt.
|
|
268
|
+
if (!(await this.session.canSubmitPrompt())) {
|
|
269
|
+
result.deferred += 1;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!this.session.isIdle()) {
|
|
274
|
+
// Never steer or queue a model turn mid-stream; retry on agent_settled.
|
|
275
|
+
result.deferred += 1;
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Refresh branch evidence after authentication; branch can change while the
|
|
280
|
+
// asynchronous model check is pending.
|
|
281
|
+
const currentEntries = this.session.getBranch();
|
|
282
|
+
if (hasSubmittedPromptRequestId(currentEntries, rawRequest.requestId, rawRequest.prompt)) {
|
|
283
|
+
await this.store.remove(payloadPath);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Re-check the session binding immediately before appending.
|
|
288
|
+
if (payload.parentSessionId !== this.session.getSessionId()) return;
|
|
289
|
+
if (!hasMergedRequestId(currentEntries, rawRequest.requestId)) {
|
|
290
|
+
this.session.sendMergeMessage(buildMergeMessageContent(rawRequest.summary), {
|
|
291
|
+
requestId: rawRequest.requestId,
|
|
292
|
+
launchId: rawRequest.launchId,
|
|
293
|
+
prompt: rawRequest.prompt,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
this.session.submitPrompt(rawRequest.prompt);
|
|
297
|
+
result.delivered += 1;
|
|
298
|
+
await this.store.remove(payloadPath);
|
|
299
|
+
this.session.notify("Merged a /btw side thread into this session; continuing with its prompt.", "info");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private async reject(payloadPath: string, reason: string): Promise<void> {
|
|
303
|
+
await this.store.remove(payloadPath);
|
|
304
|
+
this.session.notify(`Rejected a /btw merge request: ${reason}`, "warning");
|
|
305
|
+
}
|
|
306
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { buildSessionContext, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
3
|
+
import { executeTaskRoutes, registerModelTask, registerTaskModelsConfigReporting, type ModelTask } from "@hcflabs/pi-task-models";
|
|
4
|
+
import { buildMergeTranscript, tailBytes } from "./merge.ts";
|
|
5
|
+
import { configuredTaskRoutes } from "./task-models.ts";
|
|
6
|
+
|
|
7
|
+
const WIDGET_KEY = "pi-herdr-recap";
|
|
8
|
+
/** Long enough that a short look away costs no model call; short enough that the recap is ready after a typical visit to other panes. */
|
|
9
|
+
export const RECAP_IDLE_MS = 240_000;
|
|
10
|
+
const RECAP_MAX_WORDS = 40;
|
|
11
|
+
/** One budget for the whole prompt keeps it within small task-model context windows. */
|
|
12
|
+
export const RECAP_PROMPT_BUDGET_BYTES = 48 * 1024;
|
|
13
|
+
/** The title and newest summary use at most this share, so the newest turns always fit. */
|
|
14
|
+
const RECAP_SUMMARY_BUDGET_BYTES = 16 * 1024;
|
|
15
|
+
const RECAP_PROMPT = `The user stepped away from this coding conversation and is returning. Write a recap of at most ${RECAP_MAX_WORDS} words in one or two plain sentences without markdown: the overall goal, the current state, then one next action. Reply with the recap only.`;
|
|
16
|
+
export const RECAP_TASK = {
|
|
17
|
+
id: "pi-herdr-tools/recap",
|
|
18
|
+
label: "Idle recap",
|
|
19
|
+
purpose: "Summarize where an idle conversation stopped.",
|
|
20
|
+
defaultProfile: "fast",
|
|
21
|
+
} as const satisfies ModelTask;
|
|
22
|
+
|
|
23
|
+
class RecapModelError extends Error {}
|
|
24
|
+
|
|
25
|
+
/** Put the accent icon at column 0 and indent continuation lines under the dim recap text. */
|
|
26
|
+
function renderRecapWidget(text: string, theme: Theme, width: number): string[] {
|
|
27
|
+
return wrapTextWithAnsi(`Recap: ${text}`, Math.max(1, width - 2)).map((line, index) =>
|
|
28
|
+
truncateToWidth(`${index ? " " : `${theme.fg("accent", "↺")} `}${theme.fg("dim", line)}`, Math.max(1, width), ""),
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Keep at most maxBytes of UTF-8 from the head of the text. */
|
|
33
|
+
function headBytes(text: string, maxBytes: number): string {
|
|
34
|
+
const bytes = Buffer.from(text);
|
|
35
|
+
// A cut inside a multibyte character decodes to a trailing U+FFFD; drop it to stay within the budget.
|
|
36
|
+
return bytes.length <= maxBytes ? text : bytes.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD+$/, "");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function generateRecap(prompt: string, ctx: ExtensionContext, signal: AbortSignal, reportTaskModels: (ctx: ExtensionContext) => void): Promise<string> {
|
|
40
|
+
return executeTaskRoutes(
|
|
41
|
+
configuredTaskRoutes(ctx, RECAP_TASK, "Recap", reportTaskModels),
|
|
42
|
+
async (route) => {
|
|
43
|
+
let response;
|
|
44
|
+
try {
|
|
45
|
+
response = await ctx.modelRegistry.streamSimple(route.model, {
|
|
46
|
+
systemPrompt: RECAP_PROMPT,
|
|
47
|
+
messages: [{ role: "user", content: prompt, timestamp: Date.now() }],
|
|
48
|
+
}, {
|
|
49
|
+
signal,
|
|
50
|
+
maxRetries: 0,
|
|
51
|
+
...(route.thinkingLevel === "off" ? {} : { reasoning: route.thinkingLevel }),
|
|
52
|
+
}).result();
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (signal.aborted) throw error;
|
|
55
|
+
throw new RecapModelError(error instanceof Error ? error.message : "Recap task model failed.");
|
|
56
|
+
}
|
|
57
|
+
if (response.stopReason !== "stop") throw new RecapModelError(response.errorMessage || "Recap task model did not return a complete recap.");
|
|
58
|
+
const words = response.content
|
|
59
|
+
.flatMap((part) => (part.type === "text" ? part.text.split(/\s+/) : []))
|
|
60
|
+
.filter(Boolean);
|
|
61
|
+
if (!words.length) throw new RecapModelError("Recap task model returned no text.");
|
|
62
|
+
return words.slice(0, RECAP_MAX_WORDS).join(" ");
|
|
63
|
+
},
|
|
64
|
+
{ signal, shouldFallback: (error) => error instanceof RecapModelError },
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** After a settled run stays idle, show a short recap above the editor. The recap never enters model context. */
|
|
69
|
+
export default function idleRecapExtension(pi: ExtensionAPI): void {
|
|
70
|
+
registerModelTask(pi, RECAP_TASK);
|
|
71
|
+
const reportTaskModels = registerTaskModelsConfigReporting(pi);
|
|
72
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
73
|
+
let active: AbortController | undefined;
|
|
74
|
+
let stopTerminalInput: (() => void) | undefined;
|
|
75
|
+
let recappedLeaf: string | null | undefined;
|
|
76
|
+
const warned = new Set<string>();
|
|
77
|
+
|
|
78
|
+
const cancelPending = () => {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
timer = undefined;
|
|
81
|
+
active?.abort();
|
|
82
|
+
active = undefined;
|
|
83
|
+
stopTerminalInput?.();
|
|
84
|
+
stopTerminalInput = undefined;
|
|
85
|
+
};
|
|
86
|
+
const cancel = (ctx: ExtensionContext) => {
|
|
87
|
+
cancelPending();
|
|
88
|
+
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
89
|
+
};
|
|
90
|
+
const idle = (ctx: ExtensionContext) => ctx.isIdle() && !ctx.ui.getEditorText().trim();
|
|
91
|
+
|
|
92
|
+
const recap = async (ctx: ExtensionContext) => {
|
|
93
|
+
timer = undefined;
|
|
94
|
+
const leaf = ctx.sessionManager.getLeafId();
|
|
95
|
+
if (leaf === recappedLeaf || !idle(ctx)) return;
|
|
96
|
+
const messages = buildSessionContext(ctx.sessionManager.getEntries(), leaf).messages;
|
|
97
|
+
// buildMergeTranscript keeps only user and assistant turns; summaries carry the goal after compaction or branch navigation.
|
|
98
|
+
const summary = messages.flatMap((message) =>
|
|
99
|
+
message.role === "compactionSummary" || message.role === "branchSummary" ? [message.summary] : [],
|
|
100
|
+
).at(-1);
|
|
101
|
+
const transcript = buildMergeTranscript(messages);
|
|
102
|
+
if (!transcript && !summary) return;
|
|
103
|
+
const title = pi.getSessionName();
|
|
104
|
+
const head = headBytes(
|
|
105
|
+
[title && `Conversation title: ${title}`, summary && `Earlier summary: ${summary}`].filter(Boolean).join("\n\n"),
|
|
106
|
+
RECAP_SUMMARY_BUDGET_BYTES,
|
|
107
|
+
);
|
|
108
|
+
const tail = transcript && tailBytes(transcript, RECAP_PROMPT_BUDGET_BYTES - Buffer.byteLength(head, "utf8") - 2);
|
|
109
|
+
const prompt = [head, tail].filter(Boolean).join("\n\n");
|
|
110
|
+
const controller = new AbortController();
|
|
111
|
+
active = controller;
|
|
112
|
+
try {
|
|
113
|
+
const text = await generateRecap(prompt, ctx, controller.signal, reportTaskModels);
|
|
114
|
+
if (active !== controller || !idle(ctx) || ctx.sessionManager.getLeafId() !== leaf) return;
|
|
115
|
+
recappedLeaf = leaf;
|
|
116
|
+
if (ctx.mode === "tui") {
|
|
117
|
+
ctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => ({
|
|
118
|
+
invalidate() {},
|
|
119
|
+
render: (width) => renderRecapWidget(text, theme, width),
|
|
120
|
+
}));
|
|
121
|
+
} else {
|
|
122
|
+
ctx.ui.setWidget(WIDGET_KEY, [`↺ Recap: ${text}`]);
|
|
123
|
+
}
|
|
124
|
+
} catch (error) {
|
|
125
|
+
// Route errors repeat on every idle cycle until /task-models changes, so show each message once.
|
|
126
|
+
const message = error instanceof Error ? error.message : "Idle recap failed.";
|
|
127
|
+
if (active === controller && !warned.has(message)) {
|
|
128
|
+
warned.add(message);
|
|
129
|
+
ctx.ui.notify(message, "warning");
|
|
130
|
+
}
|
|
131
|
+
} finally {
|
|
132
|
+
if (active === controller) active = undefined;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
137
|
+
cancel(ctx);
|
|
138
|
+
if (!ctx.hasUI || ctx.ui.getEditorText().trim()) return;
|
|
139
|
+
timer = setTimeout(() => void recap(ctx), RECAP_IDLE_MS);
|
|
140
|
+
timer.unref();
|
|
141
|
+
// Extension commands, built-in commands, and `!` shell commands do not emit `input`; any key cancels the pending recap.
|
|
142
|
+
if (ctx.mode === "tui") {
|
|
143
|
+
stopTerminalInput = ctx.ui.onTerminalInput(() => {
|
|
144
|
+
cancelPending();
|
|
145
|
+
return undefined;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
pi.on("input", (_event, ctx) => {
|
|
150
|
+
cancel(ctx);
|
|
151
|
+
return { action: "continue" };
|
|
152
|
+
});
|
|
153
|
+
pi.on("user_bash", (_event, ctx) => {
|
|
154
|
+
cancel(ctx);
|
|
155
|
+
});
|
|
156
|
+
pi.on("agent_start", (_event, ctx) => cancel(ctx));
|
|
157
|
+
pi.on("session_tree", (_event, ctx) => cancel(ctx));
|
|
158
|
+
pi.on("session_shutdown", (_event, ctx) => cancel(ctx));
|
|
159
|
+
}
|