@geohar/pi-title 0.0.0-stage → 0.4.2

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 ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thinkscape (pi-status, the original)
4
+ Copyright (c) 2026 George Harker
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
1
+ # pi-title
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [pi](https://pi.dev) extension that sets your terminal's tab title from parts you
4
+ choose: session name, folder, model, thinking level, git branch, the tool running now,
5
+ and a few more. It changes the title only when one of those parts changes.
6
+
7
+ ```text
8
+ π - fix-login-redirect - my-project
9
+ π | claude-opus-5-5 | my-session | my-project | high | feat/config
10
+ ```
11
+
12
+ It does not show whether pi is busy. pi can already show that as a progress indicator
13
+ in the tab (OSC 9;4, which Ghostty and some other terminals support). Turn it on in
14
+ pi's `settings.json`:
15
+
16
+ ```json
17
+ { "terminal": { "showTerminalProgress": true } }
18
+ ```
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pi install npm:@geohar/pi-title
24
+ ```
25
+
26
+ Or try it for one run:
27
+
28
+ ```bash
29
+ pi -e npm:@geohar/pi-title
30
+ ```
31
+
32
+ ## Commands
33
+
34
+ `/pi-title` opens a settings list, in the same style as pi's `/settings`:
35
+
36
+ - **Status**: on or off for this session (Enter or Space switches it)
37
+ - **Components**: what the title shows and in what order
38
+ - **Separator**: the text placed between components
39
+ - **Reset to defaults**: asks before restoring the default components and separator
40
+
41
+ Esc closes a submenu, then the list.
42
+
43
+ Each part can also be opened directly:
44
+
45
+ ```text
46
+ /pi-title open the settings
47
+ /pi-title on turn the title on for this session
48
+ /pi-title off turn it off; pi's own title comes back on its next update
49
+ /pi-title components choose and reorder components
50
+ /pi-title separator change the separator (up to 5 characters)
51
+ /pi-title reset restore the defaults
52
+ ```
53
+
54
+ ### Components
55
+
56
+ The picker shows a live preview of the title above the list.
57
+
58
+ - `↑` / `↓` move through the list
59
+ - `Enter` / `Space` turns a component on or off
60
+ - `Ctrl+↑` / `Ctrl+↓` moves it up or down (the title follows the list's order)
61
+ - `Esc` saves and closes
62
+
63
+ | ID | Shows | Default |
64
+ |----------------|----------------------------------------------|---------|
65
+ | `pi_symbol` | π | on |
66
+ | `session` | Session name | on |
67
+ | `cwd` | Working directory's folder name | on |
68
+ | `model` | Current model | off |
69
+ | `thinking` | Thinking level | off |
70
+ | `tokens` | Context token usage | off |
71
+ | `turn` | Turn number, while the agent is working | off |
72
+ | `git_branch` | Current git branch | off |
73
+ | `tools_count` | Number of active tools | off |
74
+ | `current_tool` | The tool running right now | off |
75
+
76
+ The default separator is `" - "`.
77
+
78
+ ## Configuration
79
+
80
+ The settings live in their own file, never in pi's `settings.json`:
81
+
82
+ - `~/.pi/agent/pi-title.json` (in `$PI_CODING_AGENT_DIR` when that is set). This is the
83
+ only file `/pi-title` writes.
84
+ - `.pi/pi-title.json` in a project. When present it is read instead of the global file.
85
+ You edit it by hand.
86
+
87
+ ```json
88
+ {
89
+ "separator": " | ",
90
+ "components": [
91
+ { "id": "pi_symbol", "enabled": true },
92
+ { "id": "model", "enabled": true },
93
+ { "id": "session", "enabled": true },
94
+ { "id": "cwd", "enabled": true },
95
+ { "id": "thinking", "enabled": true },
96
+ { "id": "git_branch", "enabled": true }
97
+ ]
98
+ }
99
+ ```
100
+
101
+ Components you leave out are added after the ones you list, in their default state.
102
+
103
+ To start pi with the title turned off:
104
+
105
+ ```bash
106
+ PI_TITLE_DISABLED=1 pi
107
+ ```
108
+
109
+ `1`, `true`, `yes` and `on` all count.
110
+
111
+ ### Coming from pi-status
112
+
113
+ pi-title began as a fork of pi-status. If you used pi-status, your settings carry over:
114
+ a `pi-status.json` is read when there is no `pi-title.json` next to it, and
115
+ `PI_STATUS_DISABLED` still works. The first change you save goes to `pi-title.json`.
116
+ Uninstall `@thinkscape/pi-status` so the two don't both set the title.
117
+
118
+ ## Credits
119
+
120
+ pi-title is based on [pi-status](https://github.com/Thinkscape/pi-status) by
121
+ [Thinkscape](https://github.com/Thinkscape), MIT licensed. It keeps pi-status's
122
+ title components and its component picker. It drops the spinner and the
123
+ Ghostty-specific code, because pi now shows progress itself. It also moves the settings
124
+ out of pi's `settings.json` into their own file, and rebuilds the menu on pi's settings
125
+ components.
126
+
127
+ ## Development
128
+
129
+ ```bash
130
+ bun install
131
+ bun run check # tsc
132
+ bun test
133
+ ```
134
+
135
+ ## Releasing
136
+
137
+ ```bash
138
+ bun run release:patch # check, bump, commit, tag (also :minor / :major)
139
+ git push origin main --tags
140
+ ```
141
+
142
+ Pushing a `v*` tag publishes to npm through trusted publishing and creates a GitHub
143
+ release. CI runs the type check, the tests and a dry-run pack on every push and pull
144
+ request.
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@geohar/pi-title",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.2",
4
+ "description": "Configurable terminal title for the pi coding agent: session, folder, model, git branch, current tool and more.",
5
+ "type": "module",
6
+ "packageManager": "bun@1.3.9",
7
+ "author": "George Harker <george@georgeharker.com>",
8
+ "homepage": "https://github.com/georgeharker/pi-title#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/georgeharker/pi-title.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/georgeharker/pi-title/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "pi-coding-agent",
20
+ "terminal",
21
+ "title",
22
+ "tab-title"
23
+ ],
24
+ "license": "MIT",
25
+ "files": [
26
+ "src",
27
+ "!src/**/*.test.ts",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "check": "tsc --noEmit",
33
+ "test": "bun test",
34
+ "version:patch": "bun run scripts/version.ts patch",
35
+ "version:minor": "bun run scripts/version.ts minor",
36
+ "version:major": "bun run scripts/version.ts major",
37
+ "release:patch": "bun run scripts/release.ts patch",
38
+ "release:minor": "bun run scripts/release.ts minor",
39
+ "release:major": "bun run scripts/release.ts major",
40
+ "pack:dry-run": "npm pack --dry-run",
41
+ "prepublishOnly": "bun run check && bun test"
42
+ },
43
+ "pi": {
44
+ "extensions": [
45
+ "./src/index.ts"
46
+ ]
47
+ },
48
+ "peerDependencies": {
49
+ "@earendil-works/pi-coding-agent": ">=0.84.4",
50
+ "@earendil-works/pi-tui": ">=0.84.4"
51
+ },
52
+ "devDependencies": {
53
+ "@earendil-works/pi-coding-agent": "1.5.2",
54
+ "@earendil-works/pi-tui": "1.5.2",
55
+ "@types/bun": "^1.3.13",
56
+ "@types/node": "25.6.0",
57
+ "typescript": "6.0.3"
58
+ },
59
+ "contributors": [
60
+ "Thinkscape (original pi-status)"
61
+ ],
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }
package/src/config.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * pi-title configuration: the components and separator of the title, kept
3
+ * in pi-title.json in pi's agent dir (pi's getAgentDir: PI_CODING_AGENT_DIR,
4
+ * else ~/.pi/agent). That is the only file pi-title writes. A project's
5
+ * .pi/pi-title.json, if present, is read instead (a per-project override,
6
+ * never written). pi's own settings.json is never read or written.
7
+ *
8
+ * Earlier versions were named pi-status: a pi-status.json (global or
9
+ * project) is still read when there is no pi-title.json beside it, and
10
+ * PI_STATUS_DISABLED is honoured alongside PI_TITLE_DISABLED.
11
+ */
12
+ import path from "node:path";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
+
16
+ export const ALL_COMPONENT_IDS = [
17
+ "pi_symbol",
18
+ "session",
19
+ "cwd",
20
+ "model",
21
+ "thinking",
22
+ "tokens",
23
+ "turn",
24
+ "git_branch",
25
+ "tools_count",
26
+ "current_tool",
27
+ ] as const;
28
+
29
+ export type ComponentId = (typeof ALL_COMPONENT_IDS)[number];
30
+
31
+ export interface ComponentConfig {
32
+ id: ComponentId;
33
+ enabled: boolean;
34
+ }
35
+
36
+ export interface PiTitleConfig {
37
+ separator: string;
38
+ components: ComponentConfig[];
39
+ }
40
+
41
+ export const COMPONENT_LABELS: Record<ComponentId, string> = {
42
+ pi_symbol: "π symbol",
43
+ session: "Session name",
44
+ cwd: "Working directory",
45
+ model: "Current model",
46
+ thinking: "Thinking level",
47
+ tokens: "Token usage",
48
+ turn: "Turn number",
49
+ git_branch: "Git branch",
50
+ tools_count: "Active tool count",
51
+ current_tool: "Current tool name",
52
+ };
53
+
54
+ const DEFAULT_ENABLED: ReadonlySet<ComponentId> = new Set(["pi_symbol", "session", "cwd"]);
55
+
56
+ export const DEFAULT_CONFIG: PiTitleConfig = {
57
+ separator: " - ",
58
+ components: ALL_COMPONENT_IDS.map((id) => ({ id, enabled: DEFAULT_ENABLED.has(id) })),
59
+ };
60
+
61
+ /** The longest separator /pi-title accepts. */
62
+ export const MAX_SEPARATOR_LENGTH = 5;
63
+
64
+ /** Set to 1/true/yes/on to start with pi-title disabled. */
65
+ export const DISABLE_ENV = "PI_TITLE_DISABLED";
66
+ /** The same, from when this was pi-status. */
67
+ export const LEGACY_DISABLE_ENV = "PI_STATUS_DISABLED";
68
+
69
+ const isComponentId = (id: unknown): id is ComponentId =>
70
+ typeof id === "string" && (ALL_COMPONENT_IDS as readonly string[]).includes(id);
71
+
72
+ /** A pi-title.json as read from disk, before it is checked. */
73
+ export interface StoredConfig {
74
+ separator?: unknown;
75
+ components?: unknown;
76
+ }
77
+
78
+ /** A usable config from whatever was stored: a missing or malformed value
79
+ * is the default; unknown components (e.g. ones a later or earlier version
80
+ * had) are dropped; the stored order is kept, and components it leaves out
81
+ * are added at the end in their default state. */
82
+ export function normalizeConfig(stored: StoredConfig | undefined): PiTitleConfig {
83
+ if (!stored) return structuredClone(DEFAULT_CONFIG);
84
+ const separator = typeof stored.separator === "string" ? stored.separator : DEFAULT_CONFIG.separator;
85
+ const listed = Array.isArray(stored.components) ? stored.components : [];
86
+ const components: ComponentConfig[] = [];
87
+ const seen = new Set<ComponentId>();
88
+ for (const c of listed as Array<{ id?: unknown; enabled?: unknown }>) {
89
+ if (!isComponentId(c?.id) || seen.has(c.id)) continue;
90
+ seen.add(c.id);
91
+ components.push({ id: c.id, enabled: c.enabled !== false });
92
+ }
93
+ for (const id of ALL_COMPONENT_IDS) {
94
+ if (!seen.has(id)) components.push({ id, enabled: DEFAULT_ENABLED.has(id) });
95
+ }
96
+ return { separator, components };
97
+ }
98
+
99
+ export interface ConfigPaths {
100
+ /** <agent dir>/pi-title.json: read when there is no project file, and
101
+ * the only file written. */
102
+ global: string;
103
+ /** <cwd>/.pi/pi-title.json: read in place of the global file. */
104
+ project: string;
105
+ /** The pi-status.json beside each, read when it is missing. */
106
+ legacyGlobal: string;
107
+ legacyProject: string;
108
+ }
109
+
110
+ export function configPaths(cwd: string = process.cwd(), agentDir: string = getAgentDir()): ConfigPaths {
111
+ return {
112
+ global: path.join(agentDir, "pi-title.json"),
113
+ project: path.join(cwd, ".pi", "pi-title.json"),
114
+ legacyGlobal: path.join(agentDir, "pi-status.json"),
115
+ legacyProject: path.join(cwd, ".pi", "pi-status.json"),
116
+ };
117
+ }
118
+
119
+ /** The file at `filePath` if it is a JSON object, else undefined (missing,
120
+ * unreadable, malformed, or not an object). */
121
+ function readStored(filePath: string): StoredConfig | undefined {
122
+ try {
123
+ if (!existsSync(filePath)) return undefined;
124
+ const parsed: StoredConfig | null = JSON.parse(readFileSync(filePath, "utf-8"));
125
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
126
+ } catch {
127
+ return undefined;
128
+ }
129
+ }
130
+
131
+ /** The config in effect: the project file, else the global file, else the
132
+ * default; normalized. */
133
+ export function loadConfig(paths: ConfigPaths = configPaths()): PiTitleConfig {
134
+ return normalizeConfig(
135
+ readStored(paths.project) ??
136
+ readStored(paths.legacyProject) ??
137
+ readStored(paths.global) ??
138
+ readStored(paths.legacyGlobal),
139
+ );
140
+ }
141
+
142
+ /** Write `config` to the global file. */
143
+ export function saveConfig(config: PiTitleConfig, paths: ConfigPaths = configPaths()): void {
144
+ mkdirSync(path.dirname(paths.global), { recursive: true });
145
+ writeFileSync(paths.global, JSON.stringify(config, null, 2) + "\n", "utf-8");
146
+ }
147
+
148
+ export function isDisabledByEnv(env: NodeJS.ProcessEnv = process.env): boolean {
149
+ return [DISABLE_ENV, LEGACY_DISABLE_ENV].some((name) => {
150
+ const value = env[name]?.trim().toLowerCase();
151
+ return value === "1" || value === "true" || value === "yes" || value === "on";
152
+ });
153
+ }
package/src/index.ts ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * pi-title: the terminal title, built from configurable components.
3
+ *
4
+ * pi's events keep a TitleSnapshot current; the title (title.ts) is a pure
5
+ * function of it and the config (config.ts), set only when something in it
6
+ * changes. Busy state is pi's own terminal progress
7
+ * (terminal.showTerminalProgress), not part of the title.
8
+ */
9
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ DEFAULT_CONFIG,
12
+ MAX_SEPARATOR_LENGTH,
13
+ isDisabledByEnv,
14
+ loadConfig,
15
+ saveConfig,
16
+ type ComponentConfig,
17
+ type PiTitleConfig,
18
+ } from "./config.js";
19
+ import { EMPTY_SNAPSHOT, buildTitle, type TitleSnapshot } from "./title.js";
20
+ import { editComponents, showSettings, type MenuDeps } from "./menu.js";
21
+
22
+ export default function piTitle(pi: ExtensionAPI) {
23
+ let config: PiTitleConfig = loadConfig();
24
+ let enabled = !isDisabledByEnv();
25
+ let destroyed = false;
26
+ /** Whether the agent is working (the turn component shows only then). */
27
+ let running = false;
28
+ /** Event-fed parts of the snapshot; the rest is read when the title is
29
+ * built (see snapshot). */
30
+ const seen = { model: "", thinking: "", tokens: 0, turn: 1, gitBranch: "", currentTool: "" };
31
+ let reapplyTimer: ReturnType<typeof setTimeout> | undefined;
32
+
33
+ const safe = <T>(read: () => T, fallback: T): T => {
34
+ try {
35
+ return read() ?? fallback;
36
+ } catch {
37
+ return fallback;
38
+ }
39
+ };
40
+ seen.thinking = safe(() => pi.getThinkingLevel(), "");
41
+
42
+ function snapshot(ctx: ExtensionContext): TitleSnapshot {
43
+ return {
44
+ ...EMPTY_SNAPSHOT,
45
+ session: safe(() => pi.getSessionName(), "") ?? "",
46
+ cwd: ctx.cwd || process.cwd(),
47
+ model: seen.model,
48
+ thinking: seen.thinking,
49
+ tokens: seen.tokens,
50
+ turn: running ? seen.turn : null,
51
+ gitBranch: seen.gitBranch,
52
+ toolsCount: safe(() => pi.getActiveTools().length, 0),
53
+ currentTool: seen.currentTool,
54
+ };
55
+ }
56
+
57
+ function refresh(ctx: ExtensionContext): void {
58
+ if (destroyed || !enabled || !ctx.hasUI) return;
59
+ ctx.ui.setTitle(buildTitle(config, snapshot(ctx)));
60
+ }
61
+
62
+ /** Refresh again on the next tick: pi writes its own title around some
63
+ * events (after extensions' session_start, on a rename, on a model
64
+ * switch), so a title set inside the handler can be overwritten at once. */
65
+ function refreshSoon(ctx: ExtensionContext): void {
66
+ if (reapplyTimer) clearTimeout(reapplyTimer);
67
+ reapplyTimer = setTimeout(() => {
68
+ reapplyTimer = undefined;
69
+ refresh(ctx);
70
+ }, 0);
71
+ }
72
+
73
+ function cancelRefresh(): void {
74
+ if (reapplyTimer) clearTimeout(reapplyTimer);
75
+ reapplyTimer = undefined;
76
+ }
77
+
78
+ async function refreshGitBranch(): Promise<void> {
79
+ const result = await pi.exec("git", ["branch", "--show-current"], { timeout: 3000 }).catch(() => null);
80
+ seen.gitBranch = result?.code === 0 ? result.stdout.trim() : "";
81
+ }
82
+
83
+ /** Turn pi-title on or off for this session. Off leaves the title to pi's
84
+ * own format on its next update. */
85
+ function setEnabled(ctx: ExtensionContext, on: boolean): void {
86
+ enabled = on;
87
+ if (!on) return cancelRefresh();
88
+ refresh(ctx);
89
+ refreshSoon(ctx);
90
+ }
91
+
92
+ // ── Events ────────────────────────────────────────────────────────────
93
+
94
+ pi.on("session_start", async (_event, ctx) => {
95
+ if (destroyed) return;
96
+ config = loadConfig(); // may have changed between sessions
97
+ if (ctx.model) seen.model = ctx.model.id || ctx.model.provider;
98
+ seen.thinking = safe(() => pi.getThinkingLevel(), "");
99
+ await refreshGitBranch();
100
+ refresh(ctx);
101
+ refreshSoon(ctx);
102
+ });
103
+
104
+ pi.on("session_info_changed", async (_event, ctx) => {
105
+ if (!destroyed) refreshSoon(ctx);
106
+ });
107
+
108
+ pi.on("agent_start", async (_event, ctx) => {
109
+ if (destroyed) return;
110
+ running = true;
111
+ seen.turn = 1;
112
+ seen.currentTool = "";
113
+ refresh(ctx);
114
+ await refreshGitBranch();
115
+ seen.tokens = safe(() => ctx.getContextUsage()?.tokens ?? 0, 0);
116
+ refresh(ctx);
117
+ });
118
+
119
+ pi.on("agent_end", async (_event, ctx) => {
120
+ if (destroyed) return;
121
+ running = false;
122
+ seen.currentTool = "";
123
+ refresh(ctx);
124
+ refreshSoon(ctx);
125
+ });
126
+
127
+ pi.on("turn_start", async (event, ctx) => {
128
+ if (destroyed) return;
129
+ seen.turn = event.turnIndex;
130
+ refresh(ctx);
131
+ });
132
+
133
+ pi.on("tool_execution_start", async (event, ctx) => {
134
+ if (destroyed) return;
135
+ seen.currentTool = event.toolName;
136
+ refresh(ctx);
137
+ });
138
+
139
+ pi.on("tool_execution_end", async (_event, ctx) => {
140
+ if (destroyed) return;
141
+ seen.currentTool = "";
142
+ refresh(ctx);
143
+ });
144
+
145
+ pi.on("model_select", async (event, ctx) => {
146
+ if (destroyed) return;
147
+ seen.model = event.model.id || event.model.provider;
148
+ refreshSoon(ctx);
149
+ });
150
+
151
+ pi.on("thinking_level_select", async (event, ctx) => {
152
+ if (destroyed) return;
153
+ seen.thinking = event.level ?? "";
154
+ refresh(ctx);
155
+ });
156
+
157
+ pi.on("session_shutdown", async () => {
158
+ cancelRefresh();
159
+ running = false;
160
+ destroyed = true;
161
+ });
162
+
163
+ // ── /pi-title ────────────────────────────────────────────────────────
164
+
165
+ const menuDeps = (ctx: ExtensionCommandContext): MenuDeps => ({
166
+ components: () => config.components,
167
+ preview: (components: ComponentConfig[]) => buildTitle({ ...config, components }, snapshot(ctx)),
168
+ applyComponents: (components) => {
169
+ config = { ...config, components: components.map((c) => ({ ...c })) };
170
+ refresh(ctx);
171
+ },
172
+ saveComponents: (components) => {
173
+ config = { ...config, components: components.map((c) => ({ ...c })) };
174
+ saveConfig(config);
175
+ refresh(ctx);
176
+ },
177
+ separator: () => config.separator,
178
+ setSeparator: (separator) => {
179
+ config = { ...config, separator };
180
+ saveConfig(config);
181
+ refresh(ctx);
182
+ },
183
+ reset: () => {
184
+ config = structuredClone(DEFAULT_CONFIG);
185
+ saveConfig(config);
186
+ setEnabled(ctx, !isDisabledByEnv());
187
+ },
188
+ enabled: () => enabled,
189
+ disabledByEnv: () => isDisabledByEnv(),
190
+ setEnabled: (on) => setEnabled(ctx, on),
191
+ });
192
+
193
+ async function changeSeparator(ctx: ExtensionCommandContext): Promise<void> {
194
+ const entered = await ctx.ui.input(
195
+ `Current separator: "${config.separator}". Enter new separator:`,
196
+ config.separator,
197
+ );
198
+ if (entered === undefined || entered === null) {
199
+ ctx.ui.notify("Separator change cancelled", "warning");
200
+ return;
201
+ }
202
+ if (entered.length > MAX_SEPARATOR_LENGTH) {
203
+ ctx.ui.notify(
204
+ `Separator too long (max ${MAX_SEPARATOR_LENGTH} characters). Use a short string like '|', '·', ' - '`,
205
+ "error",
206
+ );
207
+ return;
208
+ }
209
+ if (entered) menuDeps(ctx).setSeparator(entered);
210
+ ctx.ui.notify(`Separator changed to "${config.separator}"`, "info");
211
+ }
212
+
213
+ async function reset(ctx: ExtensionCommandContext): Promise<void> {
214
+ const ok = await ctx.ui.confirm(
215
+ "Reset pi-title config?",
216
+ "This restores the default title components and separator. Continue?",
217
+ );
218
+ if (!ok) {
219
+ ctx.ui.notify("Reset cancelled", "warning");
220
+ return;
221
+ }
222
+ menuDeps(ctx).reset();
223
+ ctx.ui.notify("pi-title config reset to defaults", "info");
224
+ }
225
+
226
+ pi.registerCommand("pi-title", {
227
+ description:
228
+ "Configure the terminal title. Subcommands: on, off, components, separator, reset. " +
229
+ "No argument shows a menu.",
230
+ handler: async (args, ctx) => {
231
+ if (destroyed) return;
232
+ switch (args.trim().toLowerCase().split(/\s+/)[0]) {
233
+ case "on":
234
+ setEnabled(ctx, true);
235
+ return ctx.ui.notify("pi-title enabled", "info");
236
+ case "off":
237
+ setEnabled(ctx, false);
238
+ return ctx.ui.notify("pi-title disabled", "info");
239
+ case "components":
240
+ return editComponents(ctx, menuDeps(ctx));
241
+ case "separator":
242
+ return changeSeparator(ctx);
243
+ case "reset":
244
+ return reset(ctx);
245
+ default:
246
+ // Empty, "status" or unknown: the settings.
247
+ return showSettings(ctx, menuDeps(ctx));
248
+ }
249
+ },
250
+ });
251
+ }
252
+
253
+ // For config consumers.
254
+ export { loadConfig as readPiTitleConfig, DEFAULT_CONFIG, ALL_COMPONENT_IDS, COMPONENT_LABELS } from "./config.js";
255
+ export type { PiTitleConfig, ComponentConfig, ComponentId } from "./config.js";
package/src/menu.ts ADDED
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The /pi-title menus, built on pi's own settings components: a
3
+ * SettingsList (as in pi's /settings) for the main menu, with submenus for
4
+ * the components, the separator and reset. They reach the extension only
5
+ * through MenuDeps.
6
+ */
7
+ import {
8
+ getSelectListTheme,
9
+ getSettingsListTheme,
10
+ type ExtensionCommandContext,
11
+ } from "@earendil-works/pi-coding-agent";
12
+ import {
13
+ Container,
14
+ Input,
15
+ Key,
16
+ SelectList,
17
+ SettingsList,
18
+ Text,
19
+ matchesKey,
20
+ type Component,
21
+ type SettingItem,
22
+ } from "@earendil-works/pi-tui";
23
+ import {
24
+ COMPONENT_LABELS,
25
+ DISABLE_ENV,
26
+ MAX_SEPARATOR_LENGTH,
27
+ type ComponentConfig,
28
+ type ComponentId,
29
+ } from "./config.js";
30
+
31
+ type Theme = Parameters<Parameters<ExtensionCommandContext["ui"]["custom"]>[0]>[1];
32
+
33
+ /** What the menus need from the extension. */
34
+ export interface MenuDeps {
35
+ components(): ComponentConfig[];
36
+ /** The title these components would give now. */
37
+ preview(components: ComponentConfig[]): string;
38
+ /** Show these components in the title, without saving them. */
39
+ applyComponents(components: ComponentConfig[]): void;
40
+ /** Save these components and show them. */
41
+ saveComponents(components: ComponentConfig[]): void;
42
+ separator(): string;
43
+ /** Save and show a separator. */
44
+ setSeparator(separator: string): void;
45
+ /** Restore and save the default config. */
46
+ reset(): void;
47
+ enabled(): boolean;
48
+ /** Whether PI_TITLE_DISABLED (or PI_STATUS_DISABLED) turned pi-title off. */
49
+ disabledByEnv(): boolean;
50
+ setEnabled(enabled: boolean): void;
51
+ }
52
+
53
+ const ON = "enabled";
54
+ const OFF = "disabled";
55
+
56
+ /** The id of the row under a SettingsList's cursor. SettingsList offers
57
+ * selectItem(id) to move the cursor but no way to read it, which
58
+ * reordering needs; this reads its private state, and gives undefined
59
+ * (reordering is then skipped) if that ever changes shape. */
60
+ function selectedId(list: SettingsList): string | undefined {
61
+ // SAFETY: reads SettingsList's private selectedIndex and items (pi-tui
62
+ // 1.5). Both are checked before use, so a different shape yields
63
+ // undefined rather than a wrong row.
64
+ const internal = list as unknown as { selectedIndex?: unknown; items?: SettingItem[] };
65
+ return typeof internal.selectedIndex === "number" ? internal.items?.[internal.selectedIndex]?.id : undefined;
66
+ }
67
+
68
+ /** The component picker: Space/Enter toggles, Ctrl+↑/↓ reorders, a live
69
+ * preview above; Esc saves and closes. */
70
+ function componentPicker(theme: Theme, deps: MenuDeps, onClose: () => void): Component {
71
+ const comps = deps.components().map((c) => ({ ...c }));
72
+ const items: SettingItem[] = comps.map((c) => ({
73
+ id: c.id,
74
+ label: COMPONENT_LABELS[c.id],
75
+ currentValue: c.enabled ? ON : OFF,
76
+ values: [ON, OFF],
77
+ }));
78
+ const preview = new Text("", 1, 0);
79
+ const showPreview = () =>
80
+ preview.setText(theme.fg("dim", "Preview: ") + theme.fg("accent", theme.bold(deps.preview(comps) || "(empty)")));
81
+ const close = () => {
82
+ deps.saveComponents(comps);
83
+ onClose();
84
+ };
85
+ const list = new SettingsList(
86
+ items,
87
+ Math.min(items.length + 2, 15),
88
+ getSettingsListTheme(),
89
+ (id, value) => {
90
+ const c = comps.find((x) => x.id === id);
91
+ if (c) c.enabled = value === ON;
92
+ deps.applyComponents(comps);
93
+ showPreview();
94
+ },
95
+ close,
96
+ );
97
+ showPreview();
98
+ const container = new Container();
99
+ container.addChild(preview);
100
+ container.addChild(list);
101
+ container.addChild(new Text(theme.fg("dim", "Ctrl+↑/↓ reorder"), 1, 0));
102
+
103
+ const move = (by: -1 | 1): void => {
104
+ const id = selectedId(list);
105
+ const from = comps.findIndex((c) => c.id === id);
106
+ const to = from + by;
107
+ if (from < 0 || to < 0 || to >= comps.length) return;
108
+ [comps[from], comps[to]] = [comps[to]!, comps[from]!];
109
+ [items[from], items[to]] = [items[to]!, items[from]!];
110
+ list.selectItem(id as ComponentId);
111
+ deps.applyComponents(comps);
112
+ showPreview();
113
+ list.invalidate();
114
+ };
115
+
116
+ return {
117
+ render: (w: number) => container.render(w),
118
+ invalidate: () => container.invalidate(),
119
+ handleInput: (data: string) => {
120
+ if (matchesKey(data, Key.ctrl("up"))) return move(-1);
121
+ if (matchesKey(data, Key.ctrl("down"))) return move(1);
122
+ list.handleInput(data);
123
+ },
124
+ };
125
+ }
126
+
127
+ /** A single-line Input submenu for the separator. */
128
+ function separatorInput(theme: Theme, deps: MenuDeps, done: (value?: string) => void): Component {
129
+ const error = new Text("", 1, 0);
130
+ // Not prefilled: Input has no way to put its cursor at the end of a set
131
+ // value. The current separator is the placeholder; Enter on an empty
132
+ // field keeps it.
133
+ const input = new Input({ placeholder: `${JSON.stringify(deps.separator())} (current)` });
134
+ input.focused = true;
135
+ input.onSubmit = (value) => {
136
+ if (value.length > MAX_SEPARATOR_LENGTH) {
137
+ error.setText(theme.fg("error", `At most ${MAX_SEPARATOR_LENGTH} characters, e.g. '|', '·', ' - '`));
138
+ return;
139
+ }
140
+ if (value) deps.setSeparator(value);
141
+ done(JSON.stringify(deps.separator()));
142
+ };
143
+ input.onEscape = () => done();
144
+ const container = new Container();
145
+ container.addChild(new Text(theme.fg("dim", "New separator (Enter to save, Esc to cancel):"), 1, 0));
146
+ container.addChild(input);
147
+ container.addChild(error);
148
+ return {
149
+ render: (w: number) => container.render(w),
150
+ invalidate: () => container.invalidate(),
151
+ handleInput: (data: string) => input.handleInput(data),
152
+ };
153
+ }
154
+
155
+ const enabledCount = (deps: MenuDeps) => `${deps.components().filter((c) => c.enabled).length} on`;
156
+ const statusValue = (deps: MenuDeps) => (deps.enabled() ? ON : deps.disabledByEnv() ? `${OFF} (${DISABLE_ENV})` : OFF);
157
+
158
+ /** /pi-title: status, components, separator and reset in one settings list. */
159
+ export async function showSettings(ctx: ExtensionCommandContext, deps: MenuDeps): Promise<void> {
160
+ await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
161
+ const items: SettingItem[] = [
162
+ {
163
+ id: "status",
164
+ label: "Status",
165
+ description: "Whether pi-title sets the terminal title",
166
+ currentValue: statusValue(deps),
167
+ values: [ON, OFF],
168
+ },
169
+ {
170
+ id: "components",
171
+ label: "Components",
172
+ description: "What the title shows, and in which order",
173
+ currentValue: enabledCount(deps),
174
+ submenu: (_value, close) => componentPicker(theme, deps, () => close(enabledCount(deps))),
175
+ },
176
+ {
177
+ id: "separator",
178
+ label: "Separator",
179
+ description: "Placed between the components",
180
+ currentValue: JSON.stringify(deps.separator()),
181
+ submenu: (_value, close) => separatorInput(theme, deps, close),
182
+ },
183
+ {
184
+ id: "reset",
185
+ label: "Reset to defaults",
186
+ description: "Restore the default components and separator",
187
+ currentValue: "",
188
+ submenu: (_value, close) => {
189
+ const confirm = new SelectList(
190
+ [
191
+ { value: "reset", label: "Reset to defaults" },
192
+ { value: "cancel", label: "Cancel" },
193
+ ],
194
+ 2,
195
+ getSelectListTheme(),
196
+ );
197
+ confirm.onSelect = (item) => {
198
+ if (item.value === "reset") {
199
+ deps.reset();
200
+ list.updateValue("status", statusValue(deps));
201
+ list.updateValue("components", enabledCount(deps));
202
+ list.updateValue("separator", JSON.stringify(deps.separator()));
203
+ }
204
+ close();
205
+ };
206
+ confirm.onCancel = () => close();
207
+ return confirm;
208
+ },
209
+ },
210
+ ];
211
+ const list = new SettingsList(
212
+ items,
213
+ items.length + 2,
214
+ getSettingsListTheme(),
215
+ (id, value) => {
216
+ if (id === "status") deps.setEnabled(value === ON);
217
+ },
218
+ () => done(),
219
+ );
220
+ return list;
221
+ });
222
+ }
223
+
224
+ /** /pi-title components: the picker on its own. */
225
+ export async function editComponents(ctx: ExtensionCommandContext, deps: MenuDeps): Promise<void> {
226
+ await ctx.ui.custom<void>((_tui, theme, _kb, done) => componentPicker(theme, deps, () => done()));
227
+ ctx.ui.notify("Component settings updated", "info");
228
+ }
package/src/title.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The title: a pure function of the config and a snapshot of what the
3
+ * components show. The extension (index.ts) keeps the snapshot current from
4
+ * pi's events; nothing here talks to pi.
5
+ */
6
+ import type { ComponentId, PiTitleConfig } from "./config.js";
7
+
8
+ /** What the components show. An empty string or null means "nothing", and
9
+ * that component is left out of the title. */
10
+ export interface TitleSnapshot {
11
+ session: string;
12
+ /** The working directory (its basename is shown). */
13
+ cwd: string;
14
+ model: string;
15
+ thinking: string;
16
+ /** Context tokens in use (0 = unknown). */
17
+ tokens: number;
18
+ /** The current turn while the agent works, else null. */
19
+ turn: number | null;
20
+ gitBranch: string;
21
+ toolsCount: number;
22
+ currentTool: string;
23
+ }
24
+
25
+ export const EMPTY_SNAPSHOT: TitleSnapshot = {
26
+ session: "",
27
+ cwd: "",
28
+ model: "",
29
+ thinking: "",
30
+ tokens: 0,
31
+ turn: null,
32
+ gitBranch: "",
33
+ toolsCount: 0,
34
+ currentTool: "",
35
+ };
36
+
37
+ /** `1234` → `1.2k`; 0 → nothing. */
38
+ export function formatTokens(tokens: number): string {
39
+ if (!tokens) return "";
40
+ return tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : `${tokens}`;
41
+ }
42
+
43
+ function basename(dir: string): string {
44
+ const trimmed = dir.replace(/[\\/]+$/, "");
45
+ return trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")) + 1);
46
+ }
47
+
48
+ export function componentValue(id: ComponentId, s: TitleSnapshot): string {
49
+ switch (id) {
50
+ case "pi_symbol":
51
+ return "π";
52
+ case "session":
53
+ return s.session;
54
+ case "cwd":
55
+ return s.cwd ? basename(s.cwd) : "";
56
+ case "model":
57
+ return s.model;
58
+ case "thinking":
59
+ return s.thinking;
60
+ case "tokens":
61
+ return formatTokens(s.tokens);
62
+ case "turn":
63
+ return s.turn === null ? "" : `${s.turn}`;
64
+ case "git_branch":
65
+ return s.gitBranch;
66
+ case "tools_count":
67
+ return s.toolsCount ? `${s.toolsCount}t` : "";
68
+ case "current_tool":
69
+ return s.currentTool;
70
+ }
71
+ }
72
+
73
+ /** The enabled components with something to show, in order, joined by the
74
+ * separator. */
75
+ export function buildTitle(config: PiTitleConfig, s: TitleSnapshot): string {
76
+ return config.components
77
+ .filter((c) => c.enabled)
78
+ .map((c) => componentValue(c.id, s))
79
+ .filter(Boolean)
80
+ .join(config.separator);
81
+ }