@each1024/pi-model-handoff 0.0.0-stage → 0.1.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/src/index.ts ADDED
@@ -0,0 +1,393 @@
1
+ import { Type } from "typebox";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { laneKeyFromModel, resolveTokenCap } from "./handoff-budget.ts";
8
+ import { formatHistoryReadText, readBranchHistory } from "./history-read-tool.ts";
9
+ import {
10
+ collectFrozenRecords,
11
+ handoffRecordKey,
12
+ projectMessagesForLane,
13
+ segmentBranchIntoRuns,
14
+ sliceActiveBranchAfterCompaction,
15
+ } from "./lane-projection.ts";
16
+ import {
17
+ HANDOFF_ENTRY_TYPE,
18
+ STATUS_KEY,
19
+ TOOL_NAME_HISTORY_READ,
20
+ type ConversationRun,
21
+ type FrozenHandoffRecord,
22
+ type LaneKey,
23
+ type ProjectionResult,
24
+ } from "./types.ts";
25
+
26
+ const HistoryReadParamsSchema = Type.Object({
27
+ entryId: Type.Optional(
28
+ Type.String({
29
+ description:
30
+ "Inspect a specific session entry by id (ignores view and pagination cursors).",
31
+ }),
32
+ ),
33
+ textOffset: Type.Optional(
34
+ Type.Integer({
35
+ minimum: 0,
36
+ description:
37
+ "Character offset when paging through a long entry selected by entryId.",
38
+ }),
39
+ ),
40
+ view: Type.Optional(
41
+ Type.Union([Type.Literal("messages"), Type.Literal("activity")], {
42
+ description:
43
+ 'History filter: "messages" (default) for user/assistant/summary messages, or "activity" to include tool/bash executions.',
44
+ }),
45
+ ),
46
+ beforePosition: Type.Optional(
47
+ Type.Integer({
48
+ minimum: 0,
49
+ description: "Return entries strictly before this 0-based timeline position.",
50
+ }),
51
+ ),
52
+ afterPosition: Type.Optional(
53
+ Type.Integer({
54
+ minimum: 0,
55
+ description: "Return entries strictly after this 0-based timeline position.",
56
+ }),
57
+ ),
58
+ limit: Type.Optional(
59
+ Type.Integer({
60
+ minimum: 1,
61
+ maximum: 50,
62
+ description: "Maximum items to return per page (1-50, default 10).",
63
+ }),
64
+ ),
65
+ maxCharsPerItem: Type.Optional(
66
+ Type.Integer({
67
+ minimum: 200,
68
+ maximum: 20000,
69
+ description: "Maximum characters per returned item (200-20000, default 4000).",
70
+ }),
71
+ ),
72
+ });
73
+
74
+ interface BranchLaneState {
75
+ runs: ConversationRun[];
76
+ frozenRecords: Map<string, FrozenHandoffRecord>;
77
+ targetRecords: FrozenHandoffRecord[];
78
+ lastDeliveredRun: ConversationRun | null;
79
+ pendingFromLane: LaneKey | null;
80
+ }
81
+
82
+ function getTargetLane(model: ExtensionContext["model"]): LaneKey | null {
83
+ if (!model) {
84
+ return null;
85
+ }
86
+ return laneKeyFromModel(model.provider, model.id);
87
+ }
88
+
89
+ function formatStrategyTag(record: FrozenHandoffRecord): string {
90
+ if (record.strategy === "delta_since_target_last_seen") {
91
+ return "delta";
92
+ }
93
+ return record.fallbackReset ? "reset" : "full";
94
+ }
95
+
96
+ function inspectBranchState(
97
+ branch: SessionEntry[],
98
+ targetLane: LaneKey | null,
99
+ extraRecords: ReadonlyMap<string, FrozenHandoffRecord>,
100
+ ): BranchLaneState {
101
+ const activeEntries = sliceActiveBranchAfterCompaction(branch);
102
+ const runs = segmentBranchIntoRuns(activeEntries, targetLane ?? "unknown/unknown");
103
+ const frozenRecords = collectFrozenRecords(activeEntries, extraRecords);
104
+
105
+ const targetRecords: FrozenHandoffRecord[] = [];
106
+ if (targetLane) {
107
+ for (const run of runs) {
108
+ const rec = frozenRecords.get(handoffRecordKey(targetLane, run.userEntryId));
109
+ if (rec) {
110
+ targetRecords.push(rec);
111
+ }
112
+ }
113
+ }
114
+
115
+ let lastDeliveredRun: ConversationRun | null = null;
116
+ for (let i = runs.length - 1; i >= 0; i--) {
117
+ if (runs[i].delivered && runs[i].ownerLane !== null) {
118
+ lastDeliveredRun = runs[i];
119
+ break;
120
+ }
121
+ }
122
+
123
+ let pendingFromLane: LaneKey | null = null;
124
+ if (
125
+ targetLane &&
126
+ runs.length > 0 &&
127
+ lastDeliveredRun &&
128
+ lastDeliveredRun.ownerLane !== null &&
129
+ lastDeliveredRun.ownerLane !== targetLane
130
+ ) {
131
+ const anchorRun = runs[runs.length - 1];
132
+ const hasAnchorRecord = frozenRecords.has(
133
+ handoffRecordKey(targetLane, anchorRun.userEntryId),
134
+ );
135
+ if (!hasAnchorRecord) {
136
+ pendingFromLane = lastDeliveredRun.ownerLane;
137
+ }
138
+ }
139
+
140
+ return {
141
+ runs,
142
+ frozenRecords,
143
+ targetRecords,
144
+ lastDeliveredRun,
145
+ pendingFromLane,
146
+ };
147
+ }
148
+
149
+ function formatStatusLine(
150
+ targetLane: LaneKey | null,
151
+ bypass: boolean,
152
+ state: BranchLaneState,
153
+ projection?: ProjectionResult,
154
+ ): string | undefined {
155
+ if (!targetLane) {
156
+ return bypass ? "handoff: bypass" : undefined;
157
+ }
158
+ if (bypass) {
159
+ return `handoff: ${targetLane} [bypass]`;
160
+ }
161
+
162
+ if (projection) {
163
+ if (projection.appliedRecords.length > 0) {
164
+ const latest =
165
+ projection.appliedRecords[projection.appliedRecords.length - 1];
166
+ return `handoff: ${targetLane} (${formatStrategyTag(latest)}, ${projection.keptNativeRuns}/${projection.totalRuns}r)`;
167
+ }
168
+ return projection.totalRuns > 0
169
+ ? `handoff: ${targetLane} (${projection.totalRuns}r)`
170
+ : `handoff: ${targetLane}`;
171
+ }
172
+
173
+ if (state.targetRecords.length > 0) {
174
+ const latest = state.targetRecords[state.targetRecords.length - 1];
175
+ return `handoff: ${targetLane} (${formatStrategyTag(latest)}, ${state.runs.length}r)`;
176
+ }
177
+ if (state.pendingFromLane) {
178
+ return `handoff: ${targetLane} (switch←${state.pendingFromLane})`;
179
+ }
180
+ return state.runs.length > 0
181
+ ? `handoff: ${targetLane} (${state.runs.length}r)`
182
+ : `handoff: ${targetLane}`;
183
+ }
184
+
185
+ function formatCommandSummary(
186
+ targetLane: LaneKey | null,
187
+ bypass: boolean,
188
+ tokenCap: number,
189
+ state: BranchLaneState,
190
+ ): string {
191
+ const lines: string[] = [
192
+ `Lane: ${targetLane ?? "(none)"}`,
193
+ `Mode: ${bypass ? "bypass (off)" : "active (on)"}`,
194
+ `Token cap: ${tokenCap}`,
195
+ `Active runs: ${state.runs.length}${state.lastDeliveredRun?.ownerLane ? ` (last delivered: ${state.lastDeliveredRun.ownerLane})` : ""}`,
196
+ `Frozen records: ${state.targetRecords.length} on lane / ${state.frozenRecords.size} total`,
197
+ ];
198
+
199
+ if (state.targetRecords.length > 0) {
200
+ const latest = state.targetRecords[state.targetRecords.length - 1];
201
+ lines.push(
202
+ `Latest handoff: ${latest.strategy}${latest.fallbackReset ? " [fallback-reset]" : ""} from ${latest.fromLane ?? "none"}, runs ${latest.coveredRunFrom}..${latest.coveredRunTo}, included=${latest.includedCount}, omitted=${latest.omittedCount}, ~${latest.estimatedTokens} tok`,
203
+ );
204
+ } else if (state.pendingFromLane) {
205
+ lines.push(
206
+ `Pending handoff: next turn will project from ${state.pendingFromLane} to ${targetLane}`,
207
+ );
208
+ }
209
+
210
+ return lines.join("\n");
211
+ }
212
+
213
+ /**
214
+ * Pi extension entrypoint for per-model context lanes, budgeted handoffs,
215
+ * frozen cache-stable capsules, and on-demand thread history retrieval.
216
+ */
217
+ export default function piModelHandoffExtension(pi: ExtensionAPI): void {
218
+ const extraRecords = new Map<string, FrozenHandoffRecord>();
219
+ let bypass = false;
220
+
221
+ const refreshStatus = (
222
+ ctx: ExtensionContext,
223
+ modelOverride?: ExtensionContext["model"],
224
+ projection?: ProjectionResult,
225
+ ): void => {
226
+ if (!ctx.hasUI) {
227
+ return;
228
+ }
229
+ const targetLane = getTargetLane(modelOverride ?? ctx.model);
230
+ const state = inspectBranchState(
231
+ ctx.sessionManager.getBranch(),
232
+ targetLane,
233
+ extraRecords,
234
+ );
235
+ ctx.ui.setStatus(
236
+ STATUS_KEY,
237
+ formatStatusLine(targetLane, bypass, state, projection),
238
+ );
239
+ };
240
+
241
+ pi.registerTool({
242
+ name: TOOL_NAME_HISTORY_READ,
243
+ label: "Thread History Read",
244
+ description:
245
+ "Read full or paginated messages and activity from the current session branch when prior turns were summarized or truncated by a model handoff.",
246
+ promptSnippet:
247
+ "Pull omitted or truncated earlier messages and tool activity from the session branch",
248
+ promptGuidelines: [
249
+ `When a handoff capsule omits or truncates an entry you need, call ${TOOL_NAME_HISTORY_READ} with entryId (or paginate with view/beforePosition/afterPosition) instead of guessing.`,
250
+ ],
251
+ parameters: HistoryReadParamsSchema,
252
+ annotations: {
253
+ readOnlyHint: true,
254
+ },
255
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
256
+ const result = readBranchHistory(ctx.sessionManager.getBranch(), params);
257
+ return {
258
+ content: [{ type: "text", text: formatHistoryReadText(result) }],
259
+ details: result,
260
+ };
261
+ },
262
+ });
263
+
264
+ pi.on("context", (event, ctx) => {
265
+ const targetLane = getTargetLane(ctx.model);
266
+ if (!targetLane || !ctx.model) {
267
+ refreshStatus(ctx);
268
+ return undefined;
269
+ }
270
+
271
+ const result = projectMessagesForLane({
272
+ eventMessages: event.messages,
273
+ branch: ctx.sessionManager.getBranch(),
274
+ targetLane,
275
+ modelContextWindow: ctx.model.contextWindow,
276
+ tokenCap: resolveTokenCap(),
277
+ extraRecords,
278
+ bypass,
279
+ });
280
+
281
+ if (result.newRecord) {
282
+ const key = handoffRecordKey(
283
+ result.newRecord.targetLane,
284
+ result.newRecord.anchorUserEntryId,
285
+ );
286
+ extraRecords.set(key, result.newRecord);
287
+ pi.appendEntry(HANDOFF_ENTRY_TYPE, result.newRecord);
288
+
289
+ if (ctx.hasUI) {
290
+ ctx.ui.notify(
291
+ `Handoff → ${result.newRecord.targetLane} (${formatStrategyTag(result.newRecord)}, from ${result.newRecord.fromLane ?? "none"}, ~${result.newRecord.estimatedTokens} tok)`,
292
+ "info",
293
+ );
294
+ }
295
+ }
296
+
297
+ refreshStatus(ctx, ctx.model, result);
298
+
299
+ if (result.modified) {
300
+ return { messages: result.messages };
301
+ }
302
+ return undefined;
303
+ });
304
+
305
+ pi.on("session_start", (_event, ctx) => {
306
+ extraRecords.clear();
307
+ refreshStatus(ctx);
308
+ });
309
+
310
+ pi.on("session_tree", (_event, ctx) => {
311
+ extraRecords.clear();
312
+ refreshStatus(ctx);
313
+ });
314
+
315
+ pi.on("session_compact", (_event, ctx) => {
316
+ extraRecords.clear();
317
+ refreshStatus(ctx);
318
+ });
319
+
320
+ pi.on("model_select", (event, ctx) => {
321
+ refreshStatus(ctx, event.model);
322
+ });
323
+
324
+ pi.registerCommand("handoff-status", {
325
+ description:
326
+ "Show current model lane and handoff summary, or toggle bypass with on/off",
327
+ getArgumentCompletions(argumentPrefix) {
328
+ const options = [
329
+ { value: "on", label: "on", description: "Enable model handoff (bypass off)" },
330
+ { value: "off", label: "off", description: "Bypass model handoff (pass-through)" },
331
+ { value: "bypass", label: "bypass", description: "Toggle bypass mode" },
332
+ ];
333
+ const prefix = argumentPrefix.trim().toLowerCase();
334
+ const filtered = options.filter((opt) => opt.value.startsWith(prefix));
335
+ return filtered.length > 0 ? filtered : null;
336
+ },
337
+ async handler(args, ctx) {
338
+ const arg = args.trim().toLowerCase();
339
+ if (arg === "on" || arg === "bypass off") {
340
+ bypass = false;
341
+ refreshStatus(ctx);
342
+ if (ctx.hasUI) {
343
+ ctx.ui.notify("Model handoff enabled (bypass=off).", "info");
344
+ }
345
+ return;
346
+ }
347
+ if (arg === "off" || arg === "bypass on") {
348
+ bypass = true;
349
+ refreshStatus(ctx);
350
+ if (ctx.hasUI) {
351
+ ctx.ui.notify("Model handoff bypassed (bypass=on).", "warning");
352
+ }
353
+ return;
354
+ }
355
+ if (arg === "bypass" || arg === "toggle") {
356
+ bypass = !bypass;
357
+ refreshStatus(ctx);
358
+ if (ctx.hasUI) {
359
+ ctx.ui.notify(
360
+ bypass
361
+ ? "Model handoff bypassed (bypass=on)."
362
+ : "Model handoff enabled (bypass=off).",
363
+ bypass ? "warning" : "info",
364
+ );
365
+ }
366
+ return;
367
+ }
368
+ if (arg.length > 0 && arg !== "status") {
369
+ if (ctx.hasUI) {
370
+ ctx.ui.notify(
371
+ "Usage: /handoff-status [on|off|bypass]",
372
+ "warning",
373
+ );
374
+ }
375
+ return;
376
+ }
377
+
378
+ const targetLane = getTargetLane(ctx.model);
379
+ const state = inspectBranchState(
380
+ ctx.sessionManager.getBranch(),
381
+ targetLane,
382
+ extraRecords,
383
+ );
384
+ refreshStatus(ctx);
385
+ if (ctx.hasUI) {
386
+ ctx.ui.notify(
387
+ formatCommandSummary(targetLane, bypass, resolveTokenCap(), state),
388
+ "info",
389
+ );
390
+ }
391
+ },
392
+ });
393
+ }