@narumitw/pi-btw 0.62.0 → 0.63.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/README.md +7 -2
- package/dist/index.ts +371 -118
- package/dist/index.ts.map +4 -4
- package/docs/main-context-runtime.md +45 -0
- package/docs/workflows.md +48 -5
- package/package.json +1 -1
- package/src/btw.ts +39 -14
- package/src/import-main-updates.ts +84 -0
- package/src/keybindings.ts +29 -4
- package/src/main-context-snapshot.ts +125 -0
- package/src/menu.ts +1 -0
- package/src/side-thread.ts +66 -17
- package/src/transcript-markdown.ts +5 -5
- package/src/transcript-pager.ts +47 -6
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Manual main-context import: runtime audit
|
|
2
|
+
|
|
3
|
+
[Workflow](./workflows.md#import-main-updates)
|
|
4
|
+
|
|
5
|
+
Manual import reads finalized main-session entries and appends a quoted background message to the side conversation. It does not navigate the main tree, submit a main message, stop main work, execute tools, or call a provider at confirmation time.
|
|
6
|
+
|
|
7
|
+
## Authoritative runtime decisions
|
|
8
|
+
|
|
9
|
+
The installed Pi implementation is authoritative for the following decisions. Dependency versions come from the workspace manifests and lockfile.
|
|
10
|
+
|
|
11
|
+
| Runtime source | Relevant behavior | Import policy |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| `pi-coding-agent/dist/core/agent-session.js`, `_handleAgentEvent()` | Extension and public `message_end` notifications run before `SessionManager.appendMessage()`. User, assistant, system, and tool-result messages are appended; custom messages use a separate entry type. | Read the session tree, not event payloads. Notifications request rendering only; they never commit an import. |
|
|
14
|
+
| `pi-coding-agent/dist/core/session-manager.js`, `getBranch()` | Walks parent IDs from the selected/current leaf; returns all entry types in source order, not the compaction-aware model projection. | Capture initial text and the last entry ID from the same synchronous branch read. Require the cursor and preview target to remain ancestors of the current leaf. |
|
|
15
|
+
| `pi-agent-core/dist/agent-loop.js`, `runLoop()` | Finalized error/aborted assistant responses finish the turn with no tool execution. Length-limited tool calls receive synthetic failed results instead of execution. Other completed responses can execute their calls. | Preserve response status in text. Do not wait for results from calls in error/aborted responses; wait for synthetic results from length-limited calls. |
|
|
16
|
+
| `pi-agent-core/dist/agent-loop.js`, tool execution and `emitToolResultMessage()` | Tool calls can execute in parallel; each final result emits message start/end. `turn_end` follows all final tool results. | Track outstanding tool-call IDs and advance only through a complete batch. Include final textual results, including error results, in actual append order. Do not use partial tool events. |
|
|
17
|
+
| `pi-coding-agent/dist/core/session-manager.js`, context projection and append methods | Compaction, branch summaries, and context edits change interpretation without removing all raw historical entries. | Reject any such boundary after the cursor, including one added during preview. A newly created source after a boundary uses the existing initial-context policy and starts a new import range. |
|
|
18
|
+
|
|
19
|
+
Streaming assistant deltas never enter the import snapshot. The normal runtime does not persist `pending` stream messages, but restored `pending` entries and `deferred` provider handles are treated as incomplete barriers: only earlier complete entries are eligible, and the cursor does not cross the barrier. A new side thread can use a later completed source. A finalized aborted or failed response can contain partial text; its status remains visible and no success is inferred. Pending tool batches can coexist with earlier complete entries: those earlier entries can be imported, and the pending batch remains available for a later import. A source selected between a call and its results still waits for all outstanding results.
|
|
20
|
+
|
|
21
|
+
User and assistant text, tool-call arguments, and standalone tool-result text are eligible. Thinking, image data, system messages, custom messages, and non-message state are not. Initial context retains its established extraction policy, including exclusion of standalone tool-result messages. Incremental imports deliberately add standalone tool evidence; they do not change that initial policy.
|
|
22
|
+
|
|
23
|
+
The cursor is scoped by the source session ID and the session-owned in-memory thread. Empty roots use a null entry ID. A missing cursor, an ancestor/sibling navigation that removes it, or a different session rejects import. The extension lifetime additionally aborts work on session replacement and reload.
|
|
24
|
+
|
|
25
|
+
## Publication and request ordering
|
|
26
|
+
|
|
27
|
+
Preview data is fixed before awaiting the UI. Confirmation rechecks cancellation, session-manager ownership, source identity, current branch compatibility, side-turn count, and update count. It then commits the immutable text payload and target cursor synchronously. A duplicate or stale confirmation cannot append another update. Preview failure and cancellation leave the cursor unchanged.
|
|
28
|
+
|
|
29
|
+
Updates are separate records indexed by their position among existing side turns. Errors remain display-only. Imports are not side answers, do not enter Q&A export scopes, and do not change question counts or resume ordering. Imported-only threads remain resumable without inventing a question title.
|
|
30
|
+
|
|
31
|
+
Successful request user messages retain their serialized timestamps. Stored import messages and the optional initial background message also retain theirs. Later successful turns keep the prior serialized message sequence as an exact prefix. A failed or cancelled unanswered question is excluded as before; it is not a committed request-prefix baseline. Imports before the first successful answer use a stable initial background message followed by the imported updates and the new side question.
|
|
32
|
+
|
|
33
|
+
The provider receives each import as a user-role background message whose payload is a JSON-quoted string, not as tool traffic or an assistant response. This labels provenance but is not a general prompt-injection protection guarantee. The side model still has no tools.
|
|
34
|
+
|
|
35
|
+
## Verification evidence
|
|
36
|
+
|
|
37
|
+
The package tests cover snapshot scope, historical/empty sources, missing or divergent cursors, context boundaries before confirmation, parallel tool results, finalized errors/aborts/length limits and their synthetic failures, pending/deferred barriers, content exclusions, and explicit size limits. Import tests cover chronology, exact serialized request prefixes, fixed previews while main advances, duplicate/stale confirmations, provider failure, cancellation, draft recovery, and imported-only resume.
|
|
38
|
+
|
|
39
|
+
The preview uses Kit's existing read-only review component, plain-text document hard wrapping, framing, theme roles, and lifecycle cancellation. Tests drive the real review with confirmation, back, hard cancel, disposal, and shutdown; callback evidence is asserted after interaction completion. Native fullscreen search tests include imported context. Shortcut tests cover fallback selection, remapping, collisions, aliases, invalid inputs, and legacy/enhanced terminal modes. Existing settings tests cover the new action through the same atomic store and invalid-file safeguards.
|
|
40
|
+
|
|
41
|
+
## Terminal-only handoff and release limits
|
|
42
|
+
|
|
43
|
+
A terminal operator must check physical keyboard protocols, IME placement, actual clipboard behavior, and subjective visual placement after a successful build and deterministic checks. Exercise manual import while main output continues in fullscreen and both split layouts; cancel a nested preview, then verify the restored draft and pane focus. These terminal-specific behaviors are not established by mocked rendering or the non-interactive package smoke.
|
|
44
|
+
|
|
45
|
+
No live-provider request is required to verify the context-ordering contract. Do not claim terminal-only acceptance until the operator completes it. Package publication, tags, and release workflow dispatch require separate explicit user approval.
|
package/docs/workflows.md
CHANGED
|
@@ -6,15 +6,56 @@
|
|
|
6
6
|
|
|
7
7
|
`/btw` lets you start from the current conversation or choose **Start from main thread tree…** to use the root-to-selected-entry path, including the selected entry.
|
|
8
8
|
The tree snapshots persisted entries and preserves the main editor draft without navigating, forking, appending to, or switching the main conversation.
|
|
9
|
-
|
|
9
|
+
|
|
10
|
+
For either context source, only user and assistant messages contribute text and formatted tool-call or tool-result blocks.
|
|
11
|
+
Images, standalone tool-result messages, compaction summaries, branch summaries, and other session entries are excluded.
|
|
12
|
+
The side thread retains the last 40,000 characters of this text and adds a truncation notice when earlier content is omitted.
|
|
13
|
+
The initial snapshot stays immutable. Later main progress reaches the side model only after an explicit import; see [Import main updates](#import-main-updates).
|
|
10
14
|
An explicit `Shift+L` label edit is the selector's only main-session mutation and persists through Pi.
|
|
11
15
|
Native tree copying reports success or failure; Escape returns to the manager and Ctrl+C closes the flow.
|
|
12
16
|
|
|
13
|
-
**Resume side thread** searches
|
|
17
|
+
**Resume side thread** searches retained in-memory threads by their first question and question count; threads containing only confirmed imports use **Main context updates** as their title.
|
|
14
18
|
The first question remains the title; threads are ordered by their newest answer or visible error.
|
|
15
19
|
Opening and closing without a new result does not reorder them.
|
|
16
20
|
`/btw <question>` bypasses selection and always starts a new thread.
|
|
17
21
|
|
|
22
|
+
## Import main updates
|
|
23
|
+
|
|
24
|
+
While the side composer is idle, use **Import main updates** (`F9` by default, then the first usable `F10` or `F11`) to review new persisted main-thread context.
|
|
25
|
+
The shortcut is configurable in `/btw` → **Settings**.
|
|
26
|
+
A `(new)` hint indicates eligible updates when the footer has room; main progress never imports content automatically.
|
|
27
|
+
If no shortcut is available, change the BTW shortcut or the conflicting Pi binding.
|
|
28
|
+
Import is unavailable while answering or draining queued side questions.
|
|
29
|
+
|
|
30
|
+
The read-only preview shows the source session, entry range, retained character count, and any omission notices.
|
|
31
|
+
Confirm to append exactly that snapshot, or press Escape to return without changes.
|
|
32
|
+
Ctrl+C closes the side flow without applying the pending import.
|
|
33
|
+
The main agent keeps running; entries added after the preview opens remain available for the next explicit import.
|
|
34
|
+
The side draft is restored when returning to the composer.
|
|
35
|
+
|
|
36
|
+
Imports contain new user text, finalized assistant text, and textual tool calls and standalone tool results in source order.
|
|
37
|
+
Finalized error, aborted, and length-limited assistant responses retain their status labels; they are not evidence of successful work.
|
|
38
|
+
Tool calls on error or aborted responses are not executed by Pi; length-limited calls receive synthetic error results instead of execution.
|
|
39
|
+
A tool-call batch waits until all its results exist, including parallel results; live stream deltas and partial tool updates are excluded.
|
|
40
|
+
Thinking, images, system instructions, and unrelated state entries are excluded.
|
|
41
|
+
Persisted pending responses or deferred provider handles block the cursor from advancing past them; start a new side thread from a later completed source if needed.
|
|
42
|
+
Each text or tool-call block is limited to 8,000 characters, and each import is limited to 40,000 characters including explicit omission notices.
|
|
43
|
+
Imports are limited background snapshots, not complete transcripts. Repeated imports increase total context and can increase provider cost or reach the model's context limit.
|
|
44
|
+
Confirmed text is sent to the selected side model's provider with the next question, not at confirmation time.
|
|
45
|
+
|
|
46
|
+
Each import appears as a searchable **Main context update**, between earlier side exchanges and later questions.
|
|
47
|
+
It does not count as a question or change the title.
|
|
48
|
+
The existing bring-to-main scopes still export successful side Q&A only, not imported main content.
|
|
49
|
+
Repeated imports do not duplicate the same entry range, and a later failed or cancelled side response does not undo a confirmed import.
|
|
50
|
+
Closing and resuming retains imports in memory, including imports made before the first question; these appear as **Main context updates** until the first question supplies a title.
|
|
51
|
+
|
|
52
|
+
The cursor must remain on the current main branch.
|
|
53
|
+
Navigation to an ancestor or another branch, a missing cursor, or a compaction, branch summary, or context edit after the cursor blocks import without changing the side thread.
|
|
54
|
+
Start a new side thread from the desired context in those cases.
|
|
55
|
+
Historical-tree sources can import only when they are ancestors of the current main branch.
|
|
56
|
+
Session replacement, reload, and restart discard imports with the rest of the retained side thread.
|
|
57
|
+
The [runtime audit](./main-context-runtime.md) records source boundaries, tests, and terminal-only verification limits.
|
|
58
|
+
|
|
18
59
|
## Read, select, and search
|
|
19
60
|
|
|
20
61
|
The dedicated workspace places the scrollable transcript above pending questions, the editor, and a compact footer.
|
|
@@ -43,14 +84,15 @@ The view reports `No selection to copy`, `Copied!`, or a sanitized clipboard err
|
|
|
43
84
|
Right-click clipboard paste is not installed because Pi has no public clipboard-read callback for this workspace.
|
|
44
85
|
Ctrl+C always cancels the side flow, even if `app.message.copy` is also mapped to Ctrl+C.
|
|
45
86
|
|
|
46
|
-
Use Pi's effective transcript-search binding (`Ctrl+Shift+F` by default) to search
|
|
87
|
+
Use Pi's effective transcript-search binding (`Ctrl+Shift+F` by default) to search the displayed transcript, excluding the footer.
|
|
88
|
+
Search remains available while answering, covering previous turns and the current question; the current answer appears only after the response completes.
|
|
47
89
|
The default next-match keys are Enter or `Ctrl+G`; previous-match keys are `Shift+Enter` or `Ctrl+Shift+G`.
|
|
48
90
|
Pi's effective search-close binding, Escape by default, closes search and returns focus to the composer.
|
|
49
91
|
|
|
50
92
|
Scroll with the mouse wheel, trackpad, or Pi's effective viewport paging bindings (`PgUp`/`PgDn` by default).
|
|
51
93
|
Remapped or disabled bindings control behavior; the composer does not retain hidden literal paging shortcuts.
|
|
52
94
|
The native transcript uses automatic scrollbars and previous/next-message navigation metadata.
|
|
53
|
-
Manual scrolling stays fixed
|
|
95
|
+
Manual scrolling stays fixed when new turns appear, during resize, and when content temporarily fits; explicitly returning to the latest content resumes follow mode.
|
|
54
96
|
On Pi 0.85 or newer, scrolling away from the latest content reveals **Jump to latest message**.
|
|
55
97
|
Click it or use Pi's effective `tui.altScreen.bottom` binding (`Ctrl+End` by default) to resume following new output.
|
|
56
98
|
|
|
@@ -75,6 +117,7 @@ Completed questions, answers, and visible errors remain resumable until the exte
|
|
|
75
117
|
## Bring context to the main editor
|
|
76
118
|
|
|
77
119
|
After a successful answer, use the bring-to-main shortcut (`Ctrl+R` by default) to choose the latest question and answer, everything from one question onward, an exact range, or the full thread.
|
|
120
|
+
All scopes, including the exact-range selector, use successful question-and-answer exchanges only; failed questions and error messages are excluded.
|
|
78
121
|
The scope chooser reports the latest exchange and full-thread sizes.
|
|
79
122
|
Question-suffix, exact-range, and full-thread choices show an exact, read-only preview before closing the side thread.
|
|
80
123
|
The context block is editable after it is loaded into the main editor.
|
|
@@ -92,7 +135,7 @@ Cancel returns to the side thread without changing either draft, and concurrent
|
|
|
92
135
|
The success message reports whether context was loaded, appended, or replaced and its approximate size.
|
|
93
136
|
|
|
94
137
|
Without an explicit bring action, closing `/btw` never changes the main conversation.
|
|
95
|
-
Resume state is memory-only: `/new`, Pi `/resume`, `/reload`, extension replacement, and process restart discard it.
|
|
138
|
+
Resume state is memory-only: `/new`, Pi `/resume`, `/fork`, `/reload`, extension replacement, and process restart discard it.
|
|
96
139
|
Unsent drafts, steering queues, interrupted answers, and model credentials are not retained.
|
|
97
140
|
|
|
98
141
|
## Core compatibility and verification
|
package/package.json
CHANGED
package/src/btw.ts
CHANGED
|
@@ -13,8 +13,9 @@ import {
|
|
|
13
13
|
summarizeBringToMain,
|
|
14
14
|
} from "./bring-to-main.js";
|
|
15
15
|
import type { BtwDisplayModel } from "./conversation-chrome.js";
|
|
16
|
-
import { buildConversationContext } from "./conversation-context.js";
|
|
17
16
|
import { type RunBtwFullscreen, runBtwFullscreen } from "./fullscreen-ui.js";
|
|
17
|
+
import { importMainUpdates } from "./import-main-updates.js";
|
|
18
|
+
import { buildMainContextSnapshot, captureMainContextSource } from "./main-context-snapshot.js";
|
|
18
19
|
import { registerBtwMainThreadUpdates } from "./main-thread-updates.js";
|
|
19
20
|
import { pickMainEntry } from "./main-tree-picker.js";
|
|
20
21
|
import {
|
|
@@ -43,6 +44,7 @@ import {
|
|
|
43
44
|
createSideThread,
|
|
44
45
|
type SideQuestionAuth,
|
|
45
46
|
type SideThread,
|
|
47
|
+
sideTranscript,
|
|
46
48
|
} from "./side-thread.js";
|
|
47
49
|
import { sanitizeSingleLine } from "./text.js";
|
|
48
50
|
import { type BtwMarkdownTransformers, prepareBtwTranscriptMarkdown } from "./transcript-markdown.js";
|
|
@@ -218,11 +220,11 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
218
220
|
const listResumeThreads = (resumableThreads: Map<string, BtwThreadState>): BtwResumeThreadSummary[] =>
|
|
219
221
|
[...resumableThreads.values()]
|
|
220
222
|
.reverse()
|
|
221
|
-
.filter((state) => state.thread.turns.length > 0 && state.title)
|
|
223
|
+
.filter((state) => (state.thread.turns.length > 0 && state.title) || state.thread.updates.length > 0)
|
|
222
224
|
.sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt)
|
|
223
225
|
.map((state) => ({
|
|
224
226
|
id: state.id,
|
|
225
|
-
title: state.title ?? "
|
|
227
|
+
title: state.title ?? "Main context updates",
|
|
226
228
|
questionCount: state.thread.turns.length,
|
|
227
229
|
}));
|
|
228
230
|
pi.registerCommand("btw", {
|
|
@@ -253,7 +255,7 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
253
255
|
}
|
|
254
256
|
|
|
255
257
|
let menuResult: BtwCommandMenuResult = "start";
|
|
256
|
-
let
|
|
258
|
+
let selectedSource: ReturnType<typeof captureMainContextSource> | undefined;
|
|
257
259
|
if (!question) {
|
|
258
260
|
while (true) {
|
|
259
261
|
menuResult = await showCommandMenu(pi, ctx, listResumeThreads(resumableThreads));
|
|
@@ -273,7 +275,7 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
273
275
|
notifySafely(ctx, "The selected main-thread branch is no longer available", "warning");
|
|
274
276
|
continue;
|
|
275
277
|
}
|
|
276
|
-
|
|
278
|
+
selectedSource = captureMainContextSource(ctx.sessionManager, treeResult.entryId, branch);
|
|
277
279
|
menuResult = "start";
|
|
278
280
|
break;
|
|
279
281
|
} catch {
|
|
@@ -310,11 +312,10 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
310
312
|
if (lifetime.signal.aborted) return Promise.resolve({ kind: "closed" as const });
|
|
311
313
|
if (!state) {
|
|
312
314
|
const createdAt = Date.now();
|
|
315
|
+
const source = selectedSource ?? captureMainContextSource(fullscreenCtx.sessionManager);
|
|
313
316
|
state = {
|
|
314
317
|
id: `btw-${nextThreadNumber}`,
|
|
315
|
-
thread: createSideThread(
|
|
316
|
-
selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch()),
|
|
317
|
-
),
|
|
318
|
+
thread: createSideThread(source.conversationContext, source.anchor),
|
|
318
319
|
thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
|
|
319
320
|
createdAt,
|
|
320
321
|
updatedAt: createdAt,
|
|
@@ -345,7 +346,11 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
345
346
|
},
|
|
346
347
|
);
|
|
347
348
|
} finally {
|
|
348
|
-
if (
|
|
349
|
+
if (
|
|
350
|
+
!lifetime.signal.aborted &&
|
|
351
|
+
state &&
|
|
352
|
+
((state.title && state.thread.turns.length > 0) || state.thread.updates.length > 0)
|
|
353
|
+
) {
|
|
349
354
|
if (state.thread.turns.length > startingTurnCount) {
|
|
350
355
|
resumableThreads.delete(state.id);
|
|
351
356
|
}
|
|
@@ -400,6 +405,7 @@ interface RunBtwThreadDependencies {
|
|
|
400
405
|
deliverBringToMain?: typeof loadBringToMainDraft;
|
|
401
406
|
persistThinkingLevel?: (level: BtwThinkingLevel) => Promise<unknown>;
|
|
402
407
|
now?: () => number;
|
|
408
|
+
importUpdates?: typeof importMainUpdates;
|
|
403
409
|
}
|
|
404
410
|
|
|
405
411
|
export type BtwThreadResult = { kind: "closed" };
|
|
@@ -454,7 +460,8 @@ export async function runBtwThread({
|
|
|
454
460
|
dependencies.persistThinkingLevel ??
|
|
455
461
|
((level: BtwThinkingLevel) => updateBtwSettings({ thinkingLevel: level }, { settingsPath }));
|
|
456
462
|
const now = dependencies.now ?? Date.now;
|
|
457
|
-
const
|
|
463
|
+
const source = state ? undefined : captureMainContextSource(ctx.sessionManager);
|
|
464
|
+
const thread = state?.thread ?? createSideThread(source?.conversationContext ?? "", source?.anchor);
|
|
458
465
|
const thinkingLevels = getSupportedThinkingLevels(selected.model);
|
|
459
466
|
const pendingWrites = new Set<Promise<void>>();
|
|
460
467
|
const steeringQuestions: string[] = [];
|
|
@@ -495,6 +502,12 @@ export async function runBtwThread({
|
|
|
495
502
|
provider: selected.model.provider,
|
|
496
503
|
});
|
|
497
504
|
if (ctx.signal?.aborted || action.kind === "close") return { kind: "closed" };
|
|
505
|
+
if (action.kind === "importMainUpdates") {
|
|
506
|
+
composerDraft = action.questionDraft;
|
|
507
|
+
const result = await (dependencies.importUpdates ?? importMainUpdates)(thread, ctx);
|
|
508
|
+
if (ctx.signal?.aborted || result === "close") return { kind: "closed" };
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
498
511
|
if (action.kind === "bringToMain") {
|
|
499
512
|
const choice = await chooseBringToMainAction(thread, ctx);
|
|
500
513
|
if (ctx.signal?.aborted) return { kind: "closed" };
|
|
@@ -813,8 +826,8 @@ async function prepareCurrentTranscriptMarkdown(
|
|
|
813
826
|
if (ctx.signal?.aborted) return undefined;
|
|
814
827
|
const turnCount = thread.turns.length;
|
|
815
828
|
const createMarkdownTransformers = ctx.signal
|
|
816
|
-
? await prepareBtwTranscriptMarkdown(thread
|
|
817
|
-
: await prepareBtwTranscriptMarkdown(thread
|
|
829
|
+
? await prepareBtwTranscriptMarkdown(sideTranscript(thread), pendingQuestion, ctx.signal)
|
|
830
|
+
: await prepareBtwTranscriptMarkdown(sideTranscript(thread), pendingQuestion);
|
|
818
831
|
if (!createMarkdownTransformers || ctx.signal?.aborted) return undefined;
|
|
819
832
|
if (thread.turns.length === turnCount) return createMarkdownTransformers;
|
|
820
833
|
}
|
|
@@ -835,7 +848,7 @@ async function askThreadQuestion(
|
|
|
835
848
|
const view = new BtwAnsweringView(
|
|
836
849
|
tui,
|
|
837
850
|
theme,
|
|
838
|
-
thread
|
|
851
|
+
sideTranscript(thread),
|
|
839
852
|
question,
|
|
840
853
|
() => {
|
|
841
854
|
if (settled) return;
|
|
@@ -881,9 +894,21 @@ async function showThreadComposer(
|
|
|
881
894
|
): Promise<TranscriptPagerAction> {
|
|
882
895
|
const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
|
|
883
896
|
if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
|
|
897
|
+
let statusLeaf: string | null | undefined;
|
|
898
|
+
let hasUpdates = false;
|
|
899
|
+
const mainUpdates = () => {
|
|
900
|
+
if (ctx.signal?.aborted || !thread.source) return false;
|
|
901
|
+
const leaf = ctx.sessionManager.getLeafId();
|
|
902
|
+
if (leaf !== statusLeaf) {
|
|
903
|
+
statusLeaf = leaf;
|
|
904
|
+
hasUpdates = buildMainContextSnapshot(ctx.sessionManager, thread.source).kind === "ready";
|
|
905
|
+
}
|
|
906
|
+
return hasUpdates;
|
|
907
|
+
};
|
|
884
908
|
return ctx.ui.custom<TranscriptPagerAction>(
|
|
885
909
|
(tui, theme, keybindings, done) =>
|
|
886
|
-
new BtwTranscriptPager(tui, theme, thread
|
|
910
|
+
new BtwTranscriptPager(tui, theme, sideTranscript(thread), done, {
|
|
911
|
+
mainUpdates,
|
|
887
912
|
startAtBottom,
|
|
888
913
|
initialQuestion,
|
|
889
914
|
model,
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { MenuContext } from "@narumitw/pi-tui-kit";
|
|
3
|
+
import {
|
|
4
|
+
buildMainContextSnapshot,
|
|
5
|
+
type MainContextSnapshot,
|
|
6
|
+
validateMainContextSnapshot,
|
|
7
|
+
} from "./main-context-snapshot.js";
|
|
8
|
+
import { runBtwMenuPreservingEditor } from "./menu.js";
|
|
9
|
+
import { appendMainContextUpdate, type SideThread } from "./side-thread.js";
|
|
10
|
+
|
|
11
|
+
export type ImportMainResult = "imported" | "back" | "close";
|
|
12
|
+
export type MainUpdatePreview = (
|
|
13
|
+
ctx: ExtensionCommandContext,
|
|
14
|
+
snapshot: MainContextSnapshot,
|
|
15
|
+
) => Promise<"confirm" | "back" | "close">;
|
|
16
|
+
|
|
17
|
+
export async function importMainUpdates(
|
|
18
|
+
thread: SideThread,
|
|
19
|
+
ctx: ExtensionCommandContext,
|
|
20
|
+
preview: MainUpdatePreview = showMainUpdatePreview,
|
|
21
|
+
): Promise<ImportMainResult> {
|
|
22
|
+
if (ctx.mode !== "tui" || ctx.signal?.aborted) return "close";
|
|
23
|
+
const manager = ctx.sessionManager;
|
|
24
|
+
const snapshot = buildMainContextSnapshot(manager, thread.source);
|
|
25
|
+
if (snapshot.kind !== "ready") {
|
|
26
|
+
ctx.ui.notify(
|
|
27
|
+
snapshot.kind === "empty" ? "No completed main updates to import." : snapshot.reason,
|
|
28
|
+
snapshot.kind === "empty" ? "info" : "warning",
|
|
29
|
+
);
|
|
30
|
+
return "back";
|
|
31
|
+
}
|
|
32
|
+
const turnCount = thread.turns.length;
|
|
33
|
+
const updateCount = thread.updates.length;
|
|
34
|
+
const result = await preview(ctx, snapshot);
|
|
35
|
+
if (ctx.signal?.aborted || result === "close") return "close";
|
|
36
|
+
if (result !== "confirm") return "back";
|
|
37
|
+
if (
|
|
38
|
+
ctx.sessionManager !== manager ||
|
|
39
|
+
thread.turns.length !== turnCount ||
|
|
40
|
+
thread.updates.length !== updateCount ||
|
|
41
|
+
!validateMainContextSnapshot(manager, snapshot) ||
|
|
42
|
+
!appendMainContextUpdate(thread, snapshot)
|
|
43
|
+
) {
|
|
44
|
+
ctx.ui.notify("Main context or side thread changed. Import was not applied; review it again.", "warning");
|
|
45
|
+
return "back";
|
|
46
|
+
}
|
|
47
|
+
return "imported";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function showMainUpdatePreview(
|
|
51
|
+
ctx: ExtensionCommandContext,
|
|
52
|
+
snapshot: MainContextSnapshot,
|
|
53
|
+
): Promise<"confirm" | "back" | "close"> {
|
|
54
|
+
if (ctx.mode !== "tui" || ctx.signal?.aborted) return "close";
|
|
55
|
+
const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
|
|
56
|
+
if (ctx.signal?.aborted) return "close";
|
|
57
|
+
let confirmed = false;
|
|
58
|
+
const menu = defineMenu<void, "preview", "import", MenuContext>({
|
|
59
|
+
start: "preview",
|
|
60
|
+
screens: {
|
|
61
|
+
preview: () => ({
|
|
62
|
+
kind: "review",
|
|
63
|
+
title: `Import main updates · ${snapshot.text.length} characters`,
|
|
64
|
+
content: `Source session: ${snapshot.source.sessionId}\nEntries: ${snapshot.source.entryId ?? "root"} → ${snapshot.target.entryId}\n${snapshot.entryCount} entries scanned. Text and bounded tool evidence only.\n\n${snapshot.text}`,
|
|
65
|
+
viewportSize: "adaptive",
|
|
66
|
+
hint: "back",
|
|
67
|
+
confirm: { id: "import", label: "Import", action: "import" },
|
|
68
|
+
}),
|
|
69
|
+
},
|
|
70
|
+
actions: {
|
|
71
|
+
import: () => {
|
|
72
|
+
confirmed = true;
|
|
73
|
+
return { kind: "close" };
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
const result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>
|
|
78
|
+
runMenu(menuContext, menu, { getState: () => undefined, signal: ctx.signal }),
|
|
79
|
+
);
|
|
80
|
+
if (ctx.signal?.aborted || result.kind === "stale") return "close";
|
|
81
|
+
if (result.kind === "error") throw result.error;
|
|
82
|
+
if (confirmed && result.kind === "closed" && result.reason === "close") return "confirm";
|
|
83
|
+
return result.kind === "closed" && result.reason === "back" ? "back" : "close";
|
|
84
|
+
}
|
package/src/keybindings.ts
CHANGED
|
@@ -9,7 +9,13 @@ import {
|
|
|
9
9
|
} from "@earendil-works/pi-tui";
|
|
10
10
|
import { formatKeyLabel } from "./text.js";
|
|
11
11
|
|
|
12
|
-
export const BTW_SHORTCUT_ACTIONS = [
|
|
12
|
+
export const BTW_SHORTCUT_ACTIONS = [
|
|
13
|
+
"exit",
|
|
14
|
+
"cycleThinkingLevel",
|
|
15
|
+
"bringToMain",
|
|
16
|
+
"switchPane",
|
|
17
|
+
"importMainUpdates",
|
|
18
|
+
] as const;
|
|
13
19
|
export type BtwShortcutAction = (typeof BTW_SHORTCUT_ACTIONS)[number];
|
|
14
20
|
export type BtwKeybindingOverrides = Partial<Record<BtwShortcutAction, string>>;
|
|
15
21
|
|
|
@@ -204,13 +210,20 @@ function resolveShortcutSnapshot(
|
|
|
204
210
|
copyOnSelect = true,
|
|
205
211
|
): BtwShortcuts {
|
|
206
212
|
const reserved = reservedKeys(keybindings, copyOnSelect);
|
|
207
|
-
const keys: BtwShortcuts["keys"] = {
|
|
213
|
+
const keys: BtwShortcuts["keys"] = {
|
|
214
|
+
exit: ["ctrl+c"],
|
|
215
|
+
cycleThinkingLevel: [],
|
|
216
|
+
bringToMain: [],
|
|
217
|
+
switchPane: [],
|
|
218
|
+
importMainUpdates: [],
|
|
219
|
+
};
|
|
208
220
|
const warnings: string[] = [];
|
|
209
221
|
const defaults: Record<BtwShortcutAction, readonly string[]> = {
|
|
210
222
|
exit: ["ctrl+c"],
|
|
211
223
|
cycleThinkingLevel: keybindings.getKeys("app.thinking.cycle"),
|
|
212
224
|
bringToMain: ["ctrl+r"],
|
|
213
225
|
switchPane: ["f6", "f7", "f8"],
|
|
226
|
+
importMainUpdates: ["f9", "f10", "f11"],
|
|
214
227
|
};
|
|
215
228
|
const usable = (action: BtwShortcutAction, candidate: string, inherited = false): string | undefined => {
|
|
216
229
|
const key = normalizeBtwKey(candidate);
|
|
@@ -244,6 +257,18 @@ function resolveShortcutSnapshot(
|
|
|
244
257
|
) === false,
|
|
245
258
|
)
|
|
246
259
|
.slice(0, 1);
|
|
260
|
+
availableDefaults.importMainUpdates = availableDefaults.importMainUpdates
|
|
261
|
+
.filter(
|
|
262
|
+
(key) =>
|
|
263
|
+
!BTW_SHORTCUT_ACTIONS.some(
|
|
264
|
+
(action) =>
|
|
265
|
+
action !== "importMainUpdates" &&
|
|
266
|
+
(candidates[action] ? [candidates[action]] : availableDefaults[action]).some((other) =>
|
|
267
|
+
btwKeysOverlap(key, other),
|
|
268
|
+
),
|
|
269
|
+
),
|
|
270
|
+
)
|
|
271
|
+
.slice(0, 1);
|
|
247
272
|
// Compare the complete proposal, not only actions visited earlier. Reject conflicts
|
|
248
273
|
// together, then repeat because a rejected override restores its default bindings.
|
|
249
274
|
for (;;) {
|
|
@@ -281,7 +306,7 @@ function resolveShortcutSnapshot(
|
|
|
281
306
|
keys[action] =
|
|
282
307
|
action === "exit"
|
|
283
308
|
? [...new Set([...effective, "ctrl+c"])]
|
|
284
|
-
: action === "switchPane"
|
|
309
|
+
: action === "switchPane" || action === "importMainUpdates"
|
|
285
310
|
? effective.slice(0, 1)
|
|
286
311
|
: effective;
|
|
287
312
|
if (!keys[action].length && (override !== undefined || defaults[action].length > 0))
|
|
@@ -313,7 +338,7 @@ export function validateBtwShortcutEdit(
|
|
|
313
338
|
if (
|
|
314
339
|
(item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? "")) ||
|
|
315
340
|
(item !== action &&
|
|
316
|
-
!(item === "switchPane" && overrides
|
|
341
|
+
!((item === "switchPane" || item === "importMainUpdates") && overrides[item] === undefined) &&
|
|
317
342
|
previous.keys[item].some((key) => !resolved.keys[item].includes(key)))
|
|
318
343
|
) {
|
|
319
344
|
return `${item} conflicts with another BTW shortcut, editing, selection, search, scrolling, or copying. Choose a different key.`;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { buildConversationContext } from "./conversation-context.js";
|
|
3
|
+
|
|
4
|
+
type Manager = ExtensionContext["sessionManager"];
|
|
5
|
+
export interface MainContextAnchor {
|
|
6
|
+
sessionId: string;
|
|
7
|
+
entryId: string | null;
|
|
8
|
+
}
|
|
9
|
+
export interface MainContextSnapshot {
|
|
10
|
+
kind: "ready";
|
|
11
|
+
source: MainContextAnchor;
|
|
12
|
+
target: MainContextAnchor;
|
|
13
|
+
text: string;
|
|
14
|
+
entryCount: number;
|
|
15
|
+
}
|
|
16
|
+
export type MainContextResult = MainContextSnapshot | { kind: "empty" } | { kind: "unavailable"; reason: string };
|
|
17
|
+
|
|
18
|
+
export function captureMainContextSource(manager: Manager, entryId?: string, branch = manager.getBranch(entryId)) {
|
|
19
|
+
const sessionId = manager.getSessionId?.();
|
|
20
|
+
return {
|
|
21
|
+
conversationContext: buildConversationContext(branch),
|
|
22
|
+
anchor: sessionId ? { sessionId, entryId: branch.at(-1)?.id ?? null } : undefined,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const LIMIT = 40_000;
|
|
27
|
+
const BLOCK_LIMIT = 8_000;
|
|
28
|
+
const boundaries = new Set(["compaction", "branch_summary", "context_edit"]);
|
|
29
|
+
|
|
30
|
+
/** SessionManager holds finalized message_end entries, never streaming deltas. */
|
|
31
|
+
export function buildMainContextSnapshot(manager: Manager, source: MainContextAnchor | undefined): MainContextResult {
|
|
32
|
+
if (!source || manager.getSessionId?.() !== source.sessionId)
|
|
33
|
+
return { kind: "unavailable", reason: "The source session is unavailable. Start a new side thread." };
|
|
34
|
+
const branch = manager.getBranch();
|
|
35
|
+
const index = source.entryId === null ? -1 : branch.findIndex((entry) => entry.id === source.entryId);
|
|
36
|
+
if (source.entryId !== null && index < 0)
|
|
37
|
+
return {
|
|
38
|
+
kind: "unavailable",
|
|
39
|
+
reason: "The main branch no longer contains the import cursor. Start a new side thread.",
|
|
40
|
+
};
|
|
41
|
+
const entries = branch.slice(index + 1);
|
|
42
|
+
if (entries.some((entry) => boundaries.has(entry.type)))
|
|
43
|
+
return {
|
|
44
|
+
kind: "unavailable",
|
|
45
|
+
reason: "Main context crossed a compaction, branch summary, or context edit. Start a new side thread.",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// Results may arrive in parallel. Do not advance past a call until all its
|
|
49
|
+
// results exist. A cursor created between call and result is also supported.
|
|
50
|
+
const pending = new Set<string>();
|
|
51
|
+
for (const entry of branch.slice(0, index + 1)) {
|
|
52
|
+
if (boundaries.has(entry.type)) pending.clear();
|
|
53
|
+
if (entry.type !== "message") continue;
|
|
54
|
+
if (
|
|
55
|
+
entry.message.role === "assistant" &&
|
|
56
|
+
entry.message.stopReason !== "error" &&
|
|
57
|
+
entry.message.stopReason !== "aborted"
|
|
58
|
+
) {
|
|
59
|
+
for (const block of entry.message.content) if (block.type === "toolCall") pending.add(block.id);
|
|
60
|
+
} else if (entry.message.role === "toolResult") pending.delete(entry.message.toolCallId);
|
|
61
|
+
}
|
|
62
|
+
let safeLength = 0;
|
|
63
|
+
for (let i = 0; i < entries.length; i++) {
|
|
64
|
+
const entry = entries[i];
|
|
65
|
+
if (entry?.type === "message") {
|
|
66
|
+
// Normal streaming deltas are not persisted. Also fail closed for restored
|
|
67
|
+
// partial entries and provider-deferred handles, which are not answers.
|
|
68
|
+
if (
|
|
69
|
+
entry.message.role === "assistant" &&
|
|
70
|
+
(entry.message.stopReason === "pending" || entry.message.stopReason === "deferred")
|
|
71
|
+
)
|
|
72
|
+
break;
|
|
73
|
+
if (
|
|
74
|
+
entry.message.role === "assistant" &&
|
|
75
|
+
entry.message.stopReason !== "error" &&
|
|
76
|
+
entry.message.stopReason !== "aborted"
|
|
77
|
+
) {
|
|
78
|
+
for (const block of entry.message.content) if (block.type === "toolCall") pending.add(block.id);
|
|
79
|
+
} else if (entry.message.role === "toolResult") pending.delete(entry.message.toolCallId);
|
|
80
|
+
}
|
|
81
|
+
if (pending.size === 0) safeLength = i + 1;
|
|
82
|
+
}
|
|
83
|
+
const eligible = entries.slice(0, safeLength);
|
|
84
|
+
const sections: string[] = [];
|
|
85
|
+
for (const entry of eligible) {
|
|
86
|
+
if (entry.type !== "message") continue;
|
|
87
|
+
const message = entry.message;
|
|
88
|
+
if (message.role !== "user" && message.role !== "assistant" && message.role !== "toolResult") continue;
|
|
89
|
+
const content =
|
|
90
|
+
typeof message.content === "string" ? [{ type: "text" as const, text: message.content }] : message.content;
|
|
91
|
+
const lines: string[] = [];
|
|
92
|
+
for (const block of content) {
|
|
93
|
+
if (block.type === "text") lines.push(bound(block.text, BLOCK_LIMIT));
|
|
94
|
+
else if (block.type === "toolCall")
|
|
95
|
+
lines.push(bound(`Tool call: ${block.name}(${JSON.stringify(block.arguments)})`, BLOCK_LIMIT));
|
|
96
|
+
}
|
|
97
|
+
if (!lines.some((line) => line.trim())) continue;
|
|
98
|
+
const label =
|
|
99
|
+
message.role === "toolResult"
|
|
100
|
+
? `Tool result: ${message.toolName}${message.isError ? " (error)" : ""}`
|
|
101
|
+
: message.role;
|
|
102
|
+
const status = message.role === "assistant" && message.stopReason !== "stop" ? ` (${message.stopReason})` : "";
|
|
103
|
+
sections.push(`${label}${status}:\n${lines.join("\n")}`);
|
|
104
|
+
}
|
|
105
|
+
if (sections.length === 0) return { kind: "empty" };
|
|
106
|
+
return {
|
|
107
|
+
kind: "ready",
|
|
108
|
+
source: { ...source },
|
|
109
|
+
target: { sessionId: source.sessionId, entryId: eligible.at(-1)?.id ?? source.entryId },
|
|
110
|
+
text: bound(sections.join("\n\n"), LIMIT),
|
|
111
|
+
entryCount: eligible.length,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function bound(text: string, limit: number): string {
|
|
116
|
+
const notice = "\n[Remaining content omitted: import size limit.]";
|
|
117
|
+
return text.length <= limit ? text : text.slice(0, limit - notice.length) + notice;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function validateMainContextSnapshot(manager: Manager, snapshot: MainContextSnapshot): boolean {
|
|
121
|
+
const latest = buildMainContextSnapshot(manager, snapshot.source);
|
|
122
|
+
if (latest.kind !== "ready") return false;
|
|
123
|
+
const branch = manager.getBranch();
|
|
124
|
+
return branch.some((entry) => entry.id === snapshot.target.entryId);
|
|
125
|
+
}
|
package/src/menu.ts
CHANGED
|
@@ -130,6 +130,7 @@ export async function showBtwCommandMenu(
|
|
|
130
130
|
cycleThinkingLevel: "Cycle thinking level shortcut",
|
|
131
131
|
bringToMain: "Bring to main shortcut",
|
|
132
132
|
switchPane: "Switch pane shortcut",
|
|
133
|
+
importMainUpdates: "Import main updates shortcut",
|
|
133
134
|
};
|
|
134
135
|
const shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {
|
|
135
136
|
if (!keybindings) return "Default";
|