pi-petrroll 0.2.1 → 0.3.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 CHANGED
@@ -6,6 +6,7 @@ Small, focused extensions for [Pi](https://pi.dev). MIT licensed.
6
6
  | --- | --- | --- |
7
7
  | [Change directory](#change-directory) | `/cd <path>` | `change_directory` |
8
8
  | [External costs](#external-costs) | — | `add_cost` |
9
+ | [Scrollbar marks](#scrollbar-marks) | — | — |
9
10
 
10
11
  Independent, focused extensions. No skills, shell wrappers, or replacement built-in tools.
11
12
 
@@ -47,7 +48,7 @@ All extensions load by default. To load only `cd`, including after future update
47
48
  }
48
49
  ```
49
50
 
50
- Disabling `cd` disables both `/cd` and its `change_directory` tool. Disabling `cost` disables `add_cost`. To load only cost recording, use `"extensions": ["extensions/cost/index.ts"]` in the package entry above.
51
+ Disabling `cd` disables both `/cd` and its `change_directory` tool. Disabling `cost` disables `add_cost`. Disabling `scrollbar-marks` restores Pi's plain scrollbar. To load only cost recording, use `"extensions": ["extensions/cost/index.ts"]` in the package entry above.
51
52
 
52
53
  ## Change directory
53
54
 
@@ -85,7 +86,7 @@ Manual `/cd` switches without starting another model response; the agent tool re
85
86
  - A new session ID and session file are created for the destination, using Pi's `SessionManager.forkFrom()`.
86
87
  - The original session is left in place. The full conversation tree is copied, and the currently selected branch is preserved.
87
88
  - Pi's native session replacement rebuilds built-in tools, the working-directory display, settings, extensions, skills, and project context such as `AGENTS.md` for the destination.
88
- - `pi -c` from the destination can continue the copied session. Copies use Pi's normal per-directory session storage (respecting `PI_CODING_AGENT_DIR`), not a source session's explicit `--session-dir` or `PI_CODING_AGENT_SESSION_DIR` override. If you use those overrides, resume the copy by its file path or remove the override.
89
+ - `pi -c` from the destination can continue the copied session. Copies stay in the source session's storage: if it uses a custom session directory (`--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, or the `sessionDir` setting), the copy is written there too, so `pi --session <id>` and `/resume` find it under the same override. Otherwise copies use Pi's normal per-directory storage for the destination (respecting `PI_CODING_AGENT_DIR`).
89
90
  - No `process.chdir()` trick, built-in tool overrides, or Pi internals are patched. Your parent terminal's working directory does **not** change.
90
91
 
91
92
  ### Safety and limitations
@@ -123,6 +124,22 @@ After launching a subagent with the ordinary `bash` tool, Pi can call `add_cost`
123
124
 
124
125
  Pi's totals include all entries in the session file, including abandoned branches. Forked or copied sessions inherit costs present in their copied history; a new empty session starts at zero. No session files or Pi internals are patched.
125
126
 
127
+ ## Scrollbar marks
128
+
129
+ Marks where your prompts and the assistant's replies start on the scrollbar at the right of Pi's fullscreen transcript, like an editor's overview ruler:
130
+
131
+ - **Prompts**: `━` in the theme's accent color. A prompt under the thumb shows as an accent `█`.
132
+ - **Replies** (assistant text): `─` in the text color. Replies under the thumb are not shown separately.
133
+
134
+ Each mark sits at its proportional position in the transcript, so dragging or scrolling the thumb onto a mark brings that message into view. Prompts win when both fall on the same row. Tool output, thinking-only, and tool-call-only assistant turns are not marked.
135
+
136
+ The marks appear whenever Pi shows the scrollbar. With the default `"fullscreenScrollbar": "auto"`, that is only briefly while scrolling. Set `"fullscreenScrollbar": "always"` in `~/.pi/agent/settings.json` to keep the scrollbar and marks visible.
137
+
138
+ Limitations:
139
+
140
+ - Fullscreen TUI mode only (Pi's default `tuiMode`). In regular mode the terminal owns scrollback and the scrollbar, so the extension does nothing. Print, JSON, and RPC modes are unaffected.
141
+ - Pi has no public scrollbar API yet. The extension wraps the transcript `ScrollView`'s scrollbar style callbacks and content render on that one instance, and wraps `UserMessageComponent.render` once per process to tell prompts from replies. It finds message starts from the OSC 133 zone markers Pi already renders. Disabling or reloading restores the original callbacks. Tested against Pi 1.4.0; future Pi versions may change these internals.
142
+
126
143
  ## Development
127
144
 
128
145
  ```sh
@@ -131,7 +148,7 @@ npm run check
131
148
  npm test
132
149
  ```
133
150
 
134
- Tests cover cost validation, native cost accumulation, persistence/resume, compaction, path handling, copy/branch preservation, cancellation, aborts, concurrency, and a real Pi runtime handoff with a fake model stream. The runtime test verifies that tool results are copied, `read` and `bash` use the new cwd, destination `AGENTS.md` replaces source context, and the agent continues only after the host finishes switching. Unit tests also cover continuation-submission failures without rolling back the successful switch. Tests do not call a model API or use your credentials.
151
+ Tests cover scrollbar mark detection, scaling, painting, and restoration, cost validation, native cost accumulation, persistence/resume, compaction, path handling, copy/branch preservation, cancellation, aborts, concurrency, and a real Pi runtime handoff with a fake model stream. The runtime test verifies that tool results are copied, `read` and `bash` use the new cwd, destination `AGENTS.md` replaces source context, and the agent continues only after the host finishes switching. Unit tests also cover continuation-submission failures without rolling back the successful switch. Tests do not call a model API or use your credentials.
135
152
 
136
153
  ```text
137
154
  extensions/
@@ -139,10 +156,14 @@ extensions/
139
156
  index.ts
140
157
  cost/
141
158
  index.ts
159
+ scrollbar-marks/
160
+ index.ts
161
+ marks.ts
142
162
  tests/
143
163
  cd.test.ts
144
164
  cost.test.ts
145
165
  runtime.test.ts
166
+ scrollbar-marks.test.ts
146
167
  ```
147
168
 
148
169
  Pi discovers entry points through `pi.extensions` in `package.json`. Add future independent extensions under `extensions/<name>/index.ts`; no new skill or package is needed. Keep helpers inside the extension directory so they are not discovered as standalone extensions.
@@ -39,6 +39,20 @@ function requireSavedSession(ctx: ExtensionContext): string {
39
39
  return file;
40
40
  }
41
41
 
42
+ /**
43
+ * Where the copied session should live. A custom session dir (--session-dir,
44
+ * PI_CODING_AGENT_SESSION_DIR, or the sessionDir setting) is shared across
45
+ * projects and must be kept; otherwise resume/listing in that dir cannot find
46
+ * the copy. The default dir is per-cwd, so the copy gets the target's default.
47
+ */
48
+ export function targetSessionDir(sessionManager: ExtensionContext["sessionManager"]): string | undefined {
49
+ // The live object is a full SessionManager; ReadonlySessionManager just does
50
+ // not expose this predicate in its type.
51
+ const usesDefault = (sessionManager as { usesDefaultSessionDir?: () => boolean }).usesDefaultSessionDir;
52
+ if (typeof usesDefault !== "function" || usesDefault.call(sessionManager)) return undefined;
53
+ return sessionManager.getSessionDir();
54
+ }
55
+
42
56
  export default function cdExtension(pi: ExtensionAPI) {
43
57
  let busy = false;
44
58
  let toolRequest: { argument: string; signal: AbortSignal | undefined } | undefined;
@@ -66,7 +80,7 @@ export default function cdExtension(pi: ExtensionAPI) {
66
80
  return;
67
81
  }
68
82
 
69
- const copy = SessionManager.forkFrom(source, target);
83
+ const copy = SessionManager.forkFrom(source, target, targetSessionDir(ctx.sessionManager));
70
84
  // forkFrom copies the whole tree but opens its last entry. Preserve the
71
85
  // actual selected leaf, including when the user navigated with /tree.
72
86
  const leaf = ctx.sessionManager.getLeafId();
@@ -0,0 +1,111 @@
1
+ import { UserMessageComponent, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { attachScrollbarMarks, type AttachOptions, type MarkKind, type MarkStyles, type ScrollViewLike } from "./marks.ts";
3
+
4
+ const WIDGET_KEY = "pi-petrroll.scrollbar-marks";
5
+ const USER_SINK = Symbol.for("pi-petrroll.scrollbar-marks.user-sink");
6
+ const USER_PATCHED = Symbol.for("pi-petrroll.scrollbar-marks.user-patched");
7
+
8
+ type SinkHolder = typeof globalThis & { [USER_SINK]?: Set<string> };
9
+
10
+ /**
11
+ * Record the first rendered line of every user message while a transcript render is collecting.
12
+ * Installed once per process; it survives `/reload` and only forwards to the current collector.
13
+ */
14
+ function patchUserMessages(): boolean {
15
+ const proto = (UserMessageComponent as unknown as { prototype?: Record<PropertyKey, unknown> } | undefined)?.prototype;
16
+ if (!proto || typeof proto.render !== "function") return false;
17
+ if (proto[USER_PATCHED]) return true;
18
+ const original = proto.render as (this: unknown, width: number) => string[];
19
+ proto.render = function (this: unknown, width: number): string[] {
20
+ const lines = original.call(this, width);
21
+ const sink = (globalThis as SinkHolder)[USER_SINK];
22
+ if (sink && lines.length > 0) sink.add(lines[0]!);
23
+ return lines;
24
+ };
25
+ proto[USER_PATCHED] = true;
26
+ return true;
27
+ }
28
+
29
+ const classifyUserMessages: NonNullable<AttachOptions["classify"]> = (render) => {
30
+ const holder = globalThis as SinkHolder;
31
+ const previous = holder[USER_SINK];
32
+ const prompts = new Set<string>();
33
+ holder[USER_SINK] = prompts;
34
+ try {
35
+ return { result: render(), isPrompt: (line) => prompts.has(line) };
36
+ } finally {
37
+ holder[USER_SINK] = previous;
38
+ }
39
+ };
40
+
41
+ type ThemeLike = { fg(color: "accent" | "text", text: string): string };
42
+
43
+ export function createMarkStyles(theme: ThemeLike): MarkStyles {
44
+ const color = (kind: MarkKind) => (kind === "prompt" ? "accent" : "text");
45
+ return {
46
+ track: (kind) => theme.fg(color(kind), kind === "prompt" ? "━" : "─"),
47
+ // Pi's thumb already uses the text color, so only prompts stand out on it.
48
+ thumb: (kind, glyph) => (kind === "prompt" ? theme.fg("accent", "█") : undefined),
49
+ };
50
+ }
51
+
52
+ function isTranscriptView(value: unknown): value is ScrollViewLike {
53
+ const view = value as Partial<ScrollViewLike> | undefined;
54
+ return (
55
+ !!view &&
56
+ view.primary === true &&
57
+ typeof view.updateLayout === "function" &&
58
+ typeof view.scrollbarTrackStyle === "function" &&
59
+ typeof view.scrollbarThumbStyle === "function" &&
60
+ Array.isArray(view.children) &&
61
+ typeof view.children[0]?.render === "function"
62
+ );
63
+ }
64
+
65
+ function install(ctx: ExtensionContext): void {
66
+ const canClassify = patchUserMessages();
67
+ ctx.ui.setWidget(
68
+ WIDGET_KEY,
69
+ (tui, theme) => {
70
+ let view: ScrollViewLike | undefined;
71
+ let restore: (() => void) | undefined;
72
+ const styles = createMarkStyles(theme);
73
+ return {
74
+ // Renders nothing below the editor. It is only here to see the TUI each frame and attach to
75
+ // the fullscreen transcript once it exists (regular mode has no primary scroll view).
76
+ render(): string[] {
77
+ const candidate = (tui as unknown as { getPrimaryScrollView?: () => unknown }).getPrimaryScrollView?.();
78
+ if (candidate !== view && isTranscriptView(candidate)) {
79
+ restore?.();
80
+ view = candidate;
81
+ restore = attachScrollbarMarks(candidate, {
82
+ styles,
83
+ ...(canClassify ? { classify: classifyUserMessages } : {}),
84
+ });
85
+ tui.requestRender();
86
+ }
87
+ return [];
88
+ },
89
+ invalidate(): void {},
90
+ dispose(): void {
91
+ restore?.();
92
+ restore = undefined;
93
+ view = undefined;
94
+ },
95
+ };
96
+ },
97
+ { placement: "belowEditor" },
98
+ );
99
+ }
100
+
101
+ export default function (pi: ExtensionAPI) {
102
+ pi.on("session_start", async (_event, ctx) => {
103
+ if (ctx.mode !== "tui") return;
104
+ install(ctx);
105
+ });
106
+
107
+ pi.on("session_shutdown", async (_event, ctx) => {
108
+ if (ctx.mode !== "tui") return;
109
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
110
+ });
111
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Scrollbar marks for Pi's fullscreen transcript.
3
+ *
4
+ * Pi paints the transcript scrollbar one row at a time, top to bottom, calling the ScrollView's
5
+ * `scrollbarTrackStyle` or `scrollbarThumbStyle` once per row right after layout. This module wraps
6
+ * those callbacks on one ScrollView instance (plus its content render and `updateLayout`) so each
7
+ * row can show whether a prompt or reply starts in the corresponding part of the transcript.
8
+ * Everything is instance-level and fully reversible; no Pi module is modified.
9
+ */
10
+
11
+ export type MarkKind = "prompt" | "reply";
12
+
13
+ /** Rendered message starts carry an OSC 133 prompt-zone start, possibly after other zone markers. */
14
+ const ZONE_START = /^(?:\x1b\]133;[BC](?:\x07|\x1b\\))*\x1b\]133;A(?:\x07|\x1b\\)/;
15
+
16
+ export interface MarkStyles {
17
+ /** Track cell (outside the thumb) for a row containing a mark. */
18
+ track(kind: MarkKind): string;
19
+ /** Thumb cell for a row containing a mark; receives Pi's thumb glyph. Return undefined to keep Pi's thumb. */
20
+ thumb(kind: MarkKind, glyph: string): string | undefined;
21
+ }
22
+
23
+ /** Minimal structural view of `@earendil-works/pi-tui`'s ScrollView that this module relies on. */
24
+ export interface ScrollViewLike {
25
+ readonly primary: boolean;
26
+ readonly children: { render(width: number): string[] }[];
27
+ scrollbarTrackStyle: (text: string) => string;
28
+ scrollbarThumbStyle: (text: string) => string;
29
+ updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void;
30
+ }
31
+
32
+ /** Content rows where prompts and replies start, in transcript order. */
33
+ export interface ContentMarks {
34
+ prompt: number[];
35
+ reply: number[];
36
+ }
37
+
38
+ /**
39
+ * Find message starts in rendered transcript lines.
40
+ * `isPrompt(line)` decides whether a zone-start line belongs to a user prompt; others are replies.
41
+ */
42
+ export function findMarks(lines: readonly string[], isPrompt: (line: string) => boolean): ContentMarks {
43
+ const marks: ContentMarks = { prompt: [], reply: [] };
44
+ for (let row = 0; row < lines.length; row++) {
45
+ const line = lines[row]!;
46
+ if (!ZONE_START.test(line)) continue;
47
+ (isPrompt(line) ? marks.prompt : marks.reply).push(row);
48
+ }
49
+ return marks;
50
+ }
51
+
52
+ /**
53
+ * Map content rows onto scrollbar rows, like an overview ruler: row `r` of `contentHeight` lands on
54
+ * track row `floor(r * trackHeight / contentHeight)`. Prompts win over replies on shared rows.
55
+ */
56
+ export function mapToTrack(marks: ContentMarks, contentHeight: number, trackHeight: number): (MarkKind | undefined)[] {
57
+ const track: (MarkKind | undefined)[] = new Array(Math.max(0, trackHeight)).fill(undefined);
58
+ if (contentHeight <= 0 || trackHeight <= 0) return track;
59
+ const scale = Math.min(1, trackHeight / contentHeight);
60
+ const place = (row: number, kind: MarkKind) => {
61
+ const index = Math.min(trackHeight - 1, Math.floor(row * scale));
62
+ if (index >= 0 && track[index] !== "prompt") track[index] = kind;
63
+ };
64
+ for (const row of marks.reply) place(row, "reply");
65
+ for (const row of marks.prompt) place(row, "prompt");
66
+ return track;
67
+ }
68
+
69
+ export interface AttachOptions {
70
+ styles: MarkStyles;
71
+ /**
72
+ * Run the transcript render and report which zone-start lines are prompts.
73
+ * Defaults to treating every zone start as a reply.
74
+ */
75
+ classify?: <T>(render: () => T) => { result: T; isPrompt: (line: string) => boolean };
76
+ }
77
+
78
+ const ATTACHED = Symbol.for("pi-petrroll.scrollbar-marks.attached");
79
+
80
+ /** Install marks on a ScrollView. Returns an idempotent function that restores the original behavior. */
81
+ export function attachScrollbarMarks(view: ScrollViewLike, options: AttachOptions): () => void {
82
+ const target = view as ScrollViewLike & { [ATTACHED]?: () => void };
83
+ target[ATTACHED]?.();
84
+
85
+ const child = view.children[0];
86
+ if (!child) return () => {};
87
+
88
+ const originalTrack = view.scrollbarTrackStyle;
89
+ const originalThumb = view.scrollbarThumbStyle;
90
+ const hadOwnUpdateLayout = Object.prototype.hasOwnProperty.call(view, "updateLayout");
91
+ const originalUpdateLayout = view.updateLayout;
92
+ const hadOwnRender = Object.prototype.hasOwnProperty.call(child, "render");
93
+ const originalRender = child.render;
94
+ const classify = options.classify ?? ((render) => ({ result: render(), isPrompt: () => false }));
95
+
96
+ let marks: ContentMarks = { prompt: [], reply: [] };
97
+ let track: (MarkKind | undefined)[] = [];
98
+ let row = 0;
99
+
100
+ child.render = function (this: unknown, width: number): string[] {
101
+ const { result, isPrompt } = classify(() => originalRender.call(child, width));
102
+ marks = findMarks(result, isPrompt);
103
+ return result;
104
+ };
105
+
106
+ view.updateLayout = function (this: unknown, contentHeight, viewportHeight, requestRender) {
107
+ originalUpdateLayout.call(view, contentHeight, viewportHeight, requestRender);
108
+ track = mapToTrack(marks, contentHeight, viewportHeight);
109
+ row = 0;
110
+ };
111
+
112
+ view.scrollbarTrackStyle = (text) => {
113
+ const kind = track[row++];
114
+ return kind ? options.styles.track(kind) : originalTrack(text);
115
+ };
116
+ view.scrollbarThumbStyle = (text) => {
117
+ const kind = track[row++];
118
+ return (kind && options.styles.thumb(kind, text)) ?? originalThumb(text);
119
+ };
120
+
121
+ let restored = false;
122
+ const restore = () => {
123
+ if (restored) return;
124
+ restored = true;
125
+ view.scrollbarTrackStyle = originalTrack;
126
+ view.scrollbarThumbStyle = originalThumb;
127
+ if (hadOwnUpdateLayout) view.updateLayout = originalUpdateLayout;
128
+ else delete (view as Partial<ScrollViewLike>).updateLayout;
129
+ if (hadOwnRender) child.render = originalRender;
130
+ else delete (child as Partial<typeof child>).render;
131
+ if (target[ATTACHED] === restore) delete target[ATTACHED];
132
+ };
133
+ target[ATTACHED] = restore;
134
+ return restore;
135
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-petrroll",
3
- "version": "0.2.1",
4
- "description": "Small, focused Pi extensions by petrroll: switch projects and track external costs in your session.",
3
+ "version": "0.3.0",
4
+ "description": "Small, focused Pi extensions by petrroll: switch projects, track external costs, and mark prompts on the scrollbar.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Petr Houška (petrroll)",