@0xkahi/pi-qol 1.1.3 → 1.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 +36 -14
- package/assets/config.schema.json +12 -19
- package/package.json +5 -5
- package/src/extensions/auto-session-name/codemap.md +5 -5
- package/src/extensions/auto-session-name/guards.ts +9 -18
- package/src/extensions/auto-session-name/index.ts +8 -32
- package/src/extensions/auto-session-name/naming-text.ts +17 -0
- package/src/extensions/custom-footer/codemap.md +5 -6
- package/src/extensions/custom-footer/constants.ts +0 -1
- package/src/extensions/custom-footer/footer-component.ts +10 -8
- package/src/extensions/custom-footer/index.ts +3 -1
- package/src/extensions/custom-footer/token-stats.ts +5 -6
- package/src/extensions/custom-footer/types.ts +3 -1
- package/src/extensions/model-select/codemap.md +8 -4
- package/src/extensions/model-select/index.ts +35 -29
- package/src/extensions/model-select/model-select-dialog.ts +9 -25
- package/src/extensions/model-select/model-select-modal.ts +66 -0
- package/src/extensions/model-select/usage-section/codemap.md +14 -0
- package/src/extensions/model-select/usage-section/index.ts +37 -0
- package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
- package/src/index.ts +7 -3
- package/src/libs/modal/README.md +46 -2
- package/src/libs/modal/codemap.md +4 -1
- package/src/libs/modal/index.ts +2 -0
- package/src/libs/modal/label-window.ts +32 -0
- package/src/libs/modal/modal-dialog.ts +16 -2
- package/src/libs/modal/section-strip.ts +33 -0
- package/src/libs/modal/sectioned-modal.ts +105 -0
- package/src/libs/modal/tab-strip.ts +2 -26
- package/src/libs/subscription-usage/codemap.md +10 -21
- package/src/libs/subscription-usage/credential-resolver.ts +44 -0
- package/src/libs/subscription-usage/index.ts +8 -0
- package/src/libs/subscription-usage/pace.ts +28 -0
- package/src/libs/subscription-usage/progress-bar.ts +13 -0
- package/src/libs/subscription-usage/provider-color.ts +10 -0
- package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +7 -15
- package/src/libs/subscription-usage/strategy/codemap.md +5 -41
- package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +8 -15
- package/src/libs/subscription-usage/subscription-usage-api.util.ts +44 -67
- package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
- package/src/schemas/auto-session-name.config.schema.ts +9 -2
- package/src/schemas/codemap.md +1 -1
- package/src/schemas/config.schema.ts +1 -1
- package/src/schemas/custom-footer-config.schema.ts +0 -4
- package/src/extensions/custom-footer/progress-bar.ts +0 -16
- package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
package/README.md
CHANGED
|
@@ -23,11 +23,15 @@ extension (see the `pi.extensions` field in `package.json`).
|
|
|
23
23
|
### `auto_session_name`
|
|
24
24
|
|
|
25
25
|
Automatically generates a short, human-readable title for a brand-new session from
|
|
26
|
-
its first user message, using a cheap model call that
|
|
27
|
-
never blocks your turn.
|
|
26
|
+
its first user prompt or whitelisted custom message, using a cheap model call that
|
|
27
|
+
runs in the background and never blocks your turn (Pi >=1.2).
|
|
28
28
|
|
|
29
29
|
- **Non-blocking** — titles are generated asynchronously while the agent responds.
|
|
30
|
-
- **Fires once, early** — only
|
|
30
|
+
- **Fires once, early** — only until the session branch contains a user message
|
|
31
|
+
or whitelisted custom message with text (image-only/blank messages don't count).
|
|
32
|
+
- **Custom triggers** — opt in to custom message types with
|
|
33
|
+
`custom_message_whitelist`; only messages sent with `triggerTurn: true` can
|
|
34
|
+
trigger naming. The default empty list allows only user prompts.
|
|
31
35
|
- **Smart guards** — skips sessions that already have a name, forked/child
|
|
32
36
|
sessions, and empty prompts.
|
|
33
37
|
- **Model-flexible** — use a configured cheap model, or fall back to the active
|
|
@@ -44,6 +48,16 @@ Favourites, ordered custom group tabs, provider filtering, and inline or overlay
|
|
|
44
48
|
- **shared filtering** across Favourites, group, and Search tabs
|
|
45
49
|
- **bidirectional tab navigation** with Tab and Shift+Tab
|
|
46
50
|
- **provider filtering** for Search without removing models from favourite tabs
|
|
51
|
+
- **sections**: opens on Select Model; `Ctrl+]` switches to the next section and
|
|
52
|
+
`Ctrl+[` to the previous (both wrap). Without the Kitty keyboard protocol,
|
|
53
|
+
`Ctrl+[` acts as Esc instead. Tab/Shift+Tab stay within the active section.
|
|
54
|
+
- **Usage**: `[Claude]` and `[Codex]` tabs show every subscription rate window,
|
|
55
|
+
separated by blank lines, with a progress bar, used percentage, reset time,
|
|
56
|
+
pace, and data freshness. Fixed provider colors match the custom footer. Missing
|
|
57
|
+
credentials and request failures are shown explicitly. Usage shares the footer
|
|
58
|
+
cache and fetches only when visited; press `r` to refresh the active provider.
|
|
59
|
+
Navigate rows with `j`/`k`, arrows, `gg`/`G`; `q` or Esc closes without changing
|
|
60
|
+
the model. In Select Model, `q` still types in the filter.
|
|
47
61
|
|
|
48
62
|
allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with eventId of `pi.vimKeys.event:pi-qol.model_select`
|
|
49
63
|
|
|
@@ -52,7 +66,8 @@ allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with
|
|
|
52
66
|
Replaces pi's built-in interactive footer with the same three-line layout, but
|
|
53
67
|
shows the current directory as an icon plus basename, supports hex color overrides,
|
|
54
68
|
can hide token/cache clusters, and adds an OAuth subscription-usage progress bar
|
|
55
|
-
for supported providers (Anthropic and OpenAI Codex).
|
|
69
|
+
for supported providers (Anthropic and OpenAI Codex). Usage colors are fixed:
|
|
70
|
+
Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
|
|
56
71
|
|
|
57
72
|
- **Directory line** — optional inverse-styled agent badge followed by the
|
|
58
73
|
directory icon + basename, with optional git branch and session name. The badge
|
|
@@ -89,6 +104,7 @@ them (project overrides global):
|
|
|
89
104
|
"$schema": "https://raw.githubusercontent.com/0xKahi/pi-qol/main/assets/config.schema.json",
|
|
90
105
|
"auto_session_name": {
|
|
91
106
|
"enabled": true,
|
|
107
|
+
"custom_message_whitelist": [],
|
|
92
108
|
"model": {
|
|
93
109
|
"provider": "opencode",
|
|
94
110
|
"modelId": "gpt-5-nano",
|
|
@@ -135,10 +151,11 @@ them (project overrides global):
|
|
|
135
151
|
|
|
136
152
|
#### `auto_session_name`
|
|
137
153
|
|
|
138
|
-
| Key
|
|
139
|
-
|
|
|
140
|
-
| `enabled`
|
|
141
|
-
| `
|
|
154
|
+
| Key | Type | Default | Description |
|
|
155
|
+
| -------------------------- | ---------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
156
|
+
| `enabled` | `boolean` | `false` | Turn the auto session naming feature on. |
|
|
157
|
+
| `custom_message_whitelist` | `string[]` | `[]` | Allowed `customType` values for `pi.sendMessage(..., { triggerTurn: true })` runs. Empty means only user prompts. |
|
|
158
|
+
| `model` | `object` | — | Optional model used to generate titles. Falls back to the session model if omitted. |
|
|
142
159
|
|
|
143
160
|
|
|
144
161
|
#### `model`
|
|
@@ -197,8 +214,6 @@ Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/
|
|
|
197
214
|
| `colors.directory` | `hex` | — | Color the directory icon and basename. |
|
|
198
215
|
| `colors.modelName` | `hex` | — | Color the right-aligned model name. |
|
|
199
216
|
| `colors.agentName` | `hex` | — | Agent badge foreground color before inversion. |
|
|
200
|
-
| `colors.anthropicUsage` | `hex` | `#D97706` | Color the Claude subscription usage segment (bar + percentage). |
|
|
201
|
-
| `colors.codexUsage` | `hex` | `#10B981` | Color the Codex subscription usage segment (bar + percentage). |
|
|
202
217
|
| `icons.directory` | `string` | nerd font | Glyph shown before the directory basename. |
|
|
203
218
|
| `icons.cache` | `string` | nerd font | Glyph for the cache cluster. |
|
|
204
219
|
| `icons.cacheRead` | `string` | nerd font | Glyph for cache-read tokens. |
|
|
@@ -241,10 +256,17 @@ On `before_agent_start`, the `auto_session_name` extension checks a series of
|
|
|
241
256
|
guards before doing any work. It only proceeds when **all** of the following hold:
|
|
242
257
|
|
|
243
258
|
1. The feature is enabled in config.
|
|
244
|
-
2. The
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
259
|
+
2. The run starts with a non-empty user prompt, or a custom message whose
|
|
260
|
+
`customType` is in `custom_message_whitelist` and whose text is non-empty
|
|
261
|
+
(image blocks are ignored).
|
|
262
|
+
3. The session does not already have a name and is not a fork/child session.
|
|
263
|
+
4. The branch has no prior user messages or whitelisted custom messages with
|
|
264
|
+
non-whitespace text. Blank or image-only messages are ignored, using the same
|
|
265
|
+
text rule as step 2, so they never block a later message from naming the session.
|
|
266
|
+
|
|
267
|
+
Pi >=1.2 emits this event for both user and custom runs, before appending the
|
|
268
|
+
starting message to the branch. Non-whitelisted custom runs are skipped before
|
|
269
|
+
session guards and their messages do not block later naming.
|
|
248
270
|
|
|
249
271
|
If those pass, it resolves a model, generates a title via a dedicated
|
|
250
272
|
title-generation prompt, cleans the result, and persists it with
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
},
|
|
11
11
|
"auto_session_name": {
|
|
12
12
|
"default": {
|
|
13
|
-
"enabled": false
|
|
13
|
+
"enabled": false,
|
|
14
|
+
"custom_message_whitelist": []
|
|
14
15
|
},
|
|
15
16
|
"type": "object",
|
|
16
17
|
"properties": {
|
|
@@ -44,6 +45,14 @@
|
|
|
44
45
|
"modelId",
|
|
45
46
|
"reasoning"
|
|
46
47
|
]
|
|
48
|
+
},
|
|
49
|
+
"custom_message_whitelist": {
|
|
50
|
+
"default": [],
|
|
51
|
+
"description": "customType values of pi custom messages (sent with triggerTurn) that may trigger auto session naming. Empty = only user prompts.",
|
|
52
|
+
"type": "array",
|
|
53
|
+
"items": {
|
|
54
|
+
"type": "string"
|
|
55
|
+
}
|
|
47
56
|
}
|
|
48
57
|
}
|
|
49
58
|
},
|
|
@@ -155,10 +164,7 @@
|
|
|
155
164
|
"custom_footer": {
|
|
156
165
|
"default": {
|
|
157
166
|
"enabled": false,
|
|
158
|
-
"colors": {
|
|
159
|
-
"anthropicUsage": "#D97706",
|
|
160
|
-
"codexUsage": "#10B981"
|
|
161
|
-
},
|
|
167
|
+
"colors": {},
|
|
162
168
|
"icons": {
|
|
163
169
|
"directory": " ",
|
|
164
170
|
"refresh": "",
|
|
@@ -180,10 +186,7 @@
|
|
|
180
186
|
"type": "boolean"
|
|
181
187
|
},
|
|
182
188
|
"colors": {
|
|
183
|
-
"default": {
|
|
184
|
-
"anthropicUsage": "#D97706",
|
|
185
|
-
"codexUsage": "#10B981"
|
|
186
|
-
},
|
|
189
|
+
"default": {},
|
|
187
190
|
"type": "object",
|
|
188
191
|
"properties": {
|
|
189
192
|
"directory": {
|
|
@@ -197,16 +200,6 @@
|
|
|
197
200
|
"agentName": {
|
|
198
201
|
"type": "string",
|
|
199
202
|
"pattern": "^#[0-9a-fA-F]{6}$"
|
|
200
|
-
},
|
|
201
|
-
"anthropicUsage": {
|
|
202
|
-
"default": "#D97706",
|
|
203
|
-
"type": "string",
|
|
204
|
-
"pattern": "^#[0-9a-fA-F]{6}$"
|
|
205
|
-
},
|
|
206
|
-
"codexUsage": {
|
|
207
|
-
"default": "#10B981",
|
|
208
|
-
"type": "string",
|
|
209
|
-
"pattern": "^#[0-9a-fA-F]{6}$"
|
|
210
203
|
}
|
|
211
204
|
}
|
|
212
205
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xkahi/pi-qol",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "quality of life pi extensions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -45,13 +45,13 @@
|
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@biomejs/biome": "^2.4.15",
|
|
47
47
|
"@changesets/cli": "^2.31.0",
|
|
48
|
-
"@earendil-works/pi-ai": "^
|
|
49
|
-
"@earendil-works/pi-coding-agent": "^
|
|
50
|
-
"@earendil-works/pi-tui": "^
|
|
48
|
+
"@earendil-works/pi-ai": "^1.3.0",
|
|
49
|
+
"@earendil-works/pi-coding-agent": "^1.3.0",
|
|
50
|
+
"@earendil-works/pi-tui": "^1.3.0",
|
|
51
51
|
"@types/bun": "latest",
|
|
52
52
|
"@types/node": "^24.0.0",
|
|
53
53
|
"bun-types": "latest",
|
|
54
|
-
"typescript": "^
|
|
54
|
+
"typescript": "^7"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
57
|
"@0xkahi/cli-dye": "^1.1.0",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
Generate and apply a short, descriptive name
|
|
5
|
+
Generate and apply a short, descriptive name from the first eligible user prompt or whitelisted custom-message run (Pi >=1.2). The branch must have no prior non-empty user messages or whitelisted custom messages, no session name may already be set, and the session must not be a child/fork. Generated titles are applied through the normal Pi session name API (`setSessionName`) so they appear in the UI and persist with the session.
|
|
6
6
|
|
|
7
7
|
## Design Patterns
|
|
8
8
|
|
|
@@ -21,8 +21,8 @@ Generate and apply a short, descriptive name for a Pi session based on the user'
|
|
|
21
21
|
- `auto_session_name` is enabled in config.
|
|
22
22
|
- No session name is currently set (`getSessionName() !== undefined`).
|
|
23
23
|
- The session is not a child/fork (`startReason !== 'fork'` and no `parentSession` header).
|
|
24
|
-
-
|
|
25
|
-
-
|
|
24
|
+
- `resolveNamingText` accepts a non-empty user prompt or custom message with a `customType` in `custom_message_whitelist`, extracting text and ignoring images. Ineligible runs return before session guards.
|
|
25
|
+
- `isFirstNamingTurn` finds no prior user or whitelisted custom messages with text in the branch (same `hasNamingText` rule as `resolveNamingText`, so blank/image-only entries never block naming). Pi emits the event before appending the starting message for both run types.
|
|
26
26
|
3. **Cancellation of stale request**: Any existing `titleController` is aborted and replaced with a fresh `AbortController` for this request.
|
|
27
27
|
4. **Model resolution**: `ModelResolver` resolves the configured title model (or the default fallback) into a concrete `ResolvedModel` (model, API key, headers, reasoning preference). Errors are surfaced via `ctx.ui.notify`.
|
|
28
28
|
5. **Title generation**: `AutoSessionNameTitleGenerator.generateAndApplyTitle` sends a single-turn completion to the LLM using the context from `buildTitleContext`. The call carries `maxRetries`, `maxTokens`, and the abort signal.
|
|
@@ -37,10 +37,10 @@ Generate and apply a short, descriptive name for a Pi session based on the user'
|
|
|
37
37
|
- Events: `session_start`, `session_shutdown`, `before_agent_start`.
|
|
38
38
|
- Methods: `getSessionName`, `setSessionName`.
|
|
39
39
|
- **Pi Context/session manager** (`ctx.sessionManager`):
|
|
40
|
-
- `getBranch()` and `getHeader()` are used to detect the first
|
|
40
|
+
- `getBranch()` and `getHeader()` are used to detect the first eligible naming turn and child sessions.
|
|
41
41
|
- **ConfigLoader** (`../../config-loader`):
|
|
42
42
|
- `isEnabled('auto_session_name')` toggles the feature.
|
|
43
|
-
- `getAutoSessionName()` supplies the optional per-feature model override.
|
|
43
|
+
- `getAutoSessionName()` supplies the optional per-feature model override and custom message whitelist (empty by default).
|
|
44
44
|
- **ModelResolver** (`../../utils/model-resolver.util`):
|
|
45
45
|
- Resolves the configured model string into a full `ResolvedModel` usable by `pi-ai`.
|
|
46
46
|
- **pi-ai compat** (`@earendil-works/pi-ai/compat`):
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, SessionEntry, SessionHeader } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { hasNamingText } from './naming-text';
|
|
2
3
|
|
|
3
4
|
type SessionManagerForGuards = {
|
|
4
5
|
getBranch(): SessionEntry[];
|
|
@@ -14,25 +15,15 @@ export class AutoSessionNameGuard {
|
|
|
14
15
|
return sessionOpts.startReason === 'fork' || Boolean(sessionOpts.manager.getHeader()?.parentSession);
|
|
15
16
|
}
|
|
16
17
|
|
|
17
|
-
static
|
|
18
|
-
// Pi emits before_agent_start before appending the
|
|
19
|
-
|
|
20
|
-
return
|
|
18
|
+
static isFirstNamingTurn(sessionManager: Pick<SessionManagerForGuards, 'getBranch'>, whitelist: ReadonlySet<string>): boolean {
|
|
19
|
+
// Pi emits before_agent_start before appending the starting message (user or custom).
|
|
20
|
+
// Only prior entries that could themselves have produced a name block naming.
|
|
21
|
+
return !sessionManager.getBranch().some(entry => AutoSessionNameGuard.isNamingEntry(entry, whitelist));
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
static
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
private static userEntryFilter(entry: SessionEntry) {
|
|
29
|
-
if (entry.type !== 'message') return false;
|
|
30
|
-
if (entry.message.role !== 'user') return false;
|
|
31
|
-
const { content } = entry.message;
|
|
32
|
-
if (typeof content === 'string') return content !== '';
|
|
33
|
-
if (content.length === 0) return false;
|
|
34
|
-
const onlyContent = content.length === 1 ? content[0] : undefined;
|
|
35
|
-
if (onlyContent?.type === 'text' && onlyContent.text === '') return false;
|
|
36
|
-
return true;
|
|
24
|
+
private static isNamingEntry(entry: SessionEntry, whitelist: ReadonlySet<string>): boolean {
|
|
25
|
+
if (entry.type === 'message') return entry.message.role === 'user' && hasNamingText(entry.message.content);
|
|
26
|
+
if (entry.type === 'custom_message') return whitelist.has(entry.customType) && hasNamingText(entry.content);
|
|
27
|
+
return false;
|
|
37
28
|
}
|
|
38
29
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import type { ConfigLoader } from '../../config-loader';
|
|
3
3
|
import { ModelResolver } from '../../utils/model-resolver.util';
|
|
4
|
-
// import { parseAgentContentToPrompt } from '../../utils/parse-agent-content.util';
|
|
5
4
|
import { AutoSessionNameGuard } from './guards';
|
|
5
|
+
import { resolveNamingText } from './naming-text';
|
|
6
6
|
import { AutoSessionNameTitleGenerator } from './title-generator';
|
|
7
7
|
|
|
8
8
|
export function registerAutoSessionName(pi: ExtensionAPI, deps: { config: ConfigLoader }) {
|
|
@@ -67,39 +67,15 @@ export function registerAutoSessionName(pi: ExtensionAPI, deps: { config: Config
|
|
|
67
67
|
|
|
68
68
|
pi.on('before_agent_start', (event, ctx) => {
|
|
69
69
|
if (!deps.config.isEnabled('auto_session_name')) return;
|
|
70
|
+
const cfg = deps.config.getAutoSessionName();
|
|
71
|
+
const whitelist = new Set(cfg.custom_message_whitelist);
|
|
72
|
+
const text = resolveNamingText(event, whitelist);
|
|
73
|
+
if (!text) return;
|
|
74
|
+
|
|
70
75
|
if (AutoSessionNameGuard.isSessionNameSet(pi)) return;
|
|
71
76
|
if (AutoSessionNameGuard.isChildSession({ startReason: lastSessionStartReason, manager: ctx.sessionManager })) return;
|
|
72
|
-
if (!AutoSessionNameGuard.
|
|
77
|
+
if (!AutoSessionNameGuard.isFirstNamingTurn(ctx.sessionManager, whitelist)) return;
|
|
73
78
|
|
|
74
|
-
|
|
75
|
-
if (!userText) return;
|
|
76
|
-
|
|
77
|
-
setAutoSessionName(ctx, userText);
|
|
79
|
+
setAutoSessionName(ctx, text);
|
|
78
80
|
});
|
|
79
|
-
|
|
80
|
-
// need fixing, currently does not work
|
|
81
|
-
// pi.on('message_start', (event, ctx) => {
|
|
82
|
-
// // ctx.ui.notify('hello0', 'info');
|
|
83
|
-
// if (!deps.config.isEnabled('auto_session_name')) return;
|
|
84
|
-
// const whitelist = new Set(deps.config.getAutoSessionName().customMessageWhitelist);
|
|
85
|
-
// // ctx.ui.notify(JSON.stringify(deps.config.getAutoSessionName()), 'warning');
|
|
86
|
-
// if (whitelist.size === 0) return;
|
|
87
|
-
// // ctx.ui.notify('hello1', 'info');
|
|
88
|
-
// const message = event.message;
|
|
89
|
-
// if (message.role !== 'custom' || !whitelist.has(message.customType)) {
|
|
90
|
-
// return;
|
|
91
|
-
// }
|
|
92
|
-
//
|
|
93
|
-
// ctx.ui.notify('hello2', 'info');
|
|
94
|
-
// if (AutoSessionNameGuard.isSessionNameSet(pi)) return;
|
|
95
|
-
// ctx.ui.notify('hello3', 'info');
|
|
96
|
-
// if (AutoSessionNameGuard.isChildSession({ startReason: lastSessionStartReason, manager: ctx.sessionManager })) return;
|
|
97
|
-
// ctx.ui.notify('hello4', 'info');
|
|
98
|
-
// if (!AutoSessionNameGuard.isFirstCustomExtensionMessage(ctx.sessionManager, whitelist)) return;
|
|
99
|
-
// ctx.ui.notify('hello5', 'info');
|
|
100
|
-
// const prompt = parseAgentContentToPrompt(message.content);
|
|
101
|
-
// ctx.ui.notify(prompt, 'info');
|
|
102
|
-
// if (!prompt) return;
|
|
103
|
-
// setAutoSessionName(ctx, prompt);
|
|
104
|
-
// });
|
|
105
81
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { BeforeAgentStartEvent } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { parseAgentContentToPrompt } from '../../utils/parse-agent-content.util';
|
|
3
|
+
|
|
4
|
+
type NamingEvent =
|
|
5
|
+
| Pick<Extract<BeforeAgentStartEvent, { messageType: 'user' }>, 'messageType' | 'prompt'>
|
|
6
|
+
| Pick<Extract<BeforeAgentStartEvent, { messageType: 'custom' }>, 'messageType' | 'message'>;
|
|
7
|
+
|
|
8
|
+
/** True when content has non-whitespace text (images ignored). Shared by current-run and branch-history checks. */
|
|
9
|
+
export function hasNamingText(content: Parameters<typeof parseAgentContentToPrompt>[0]): boolean {
|
|
10
|
+
return parseAgentContentToPrompt(content).trim() !== '';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resolveNamingText(event: NamingEvent, whitelist: ReadonlySet<string>): string | undefined {
|
|
14
|
+
if (event.messageType === 'user') return event.prompt.trim() || undefined;
|
|
15
|
+
if (!whitelist.has(event.message.customType)) return undefined;
|
|
16
|
+
return parseAgentContentToPrompt(event.message.content).trim() || undefined;
|
|
17
|
+
}
|
|
@@ -21,11 +21,10 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
21
21
|
- **Component pattern**: `CustomFooterComponent` implements the `Component` interface (`render`, `invalidate`, `dispose`) so the TUI can call it on every frame.
|
|
22
22
|
- **Dependency injection**: The component receives its dependencies (`tui`, `theme`, `footerData`, `ctx`, `config`, `getThinkingLevel`) in a single `CustomFooterComponentDeps` object, keeping rendering logic decoupled from construction.
|
|
23
23
|
- **Data provider abstraction**: `FooterDataProvider` isolates footer-specific data (git branch, extension statuses, provider count, branch-change notifications) from the broader `ExtensionContext`.
|
|
24
|
-
- **
|
|
25
|
-
- **Strategy pattern**: Provider-specific OAuth usage fetch strategies (`AnthropicOauthUsageStrategy`, `OpenAiCodexUsageStrategy`) are selected at runtime inside `SubscriptionUsageManager`.
|
|
24
|
+
- **Shared cache**: root injects one `SubscriptionUsageCache`; the component subscribes for renders and unsubscribes in `dispose`. Provider strategies and TTL/in-flight deduplication live in the shared library.
|
|
26
25
|
- **Provider normalization**: `resolveSupportedProvider` maps provider aliases (`codex`, `openai`, `chatgpt`) to the internal `SupportedProvider` union.
|
|
27
26
|
- **Window selection**: `pickSubscriptionUsageWindow` chooses the rate window with the nearest reset, falling back to the first window when no resets are available.
|
|
28
|
-
- **Pure formatting helpers**: `token-stats.ts` and `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, subscription segment construction, and progress-bar rendering, making them easy to test.
|
|
27
|
+
- **Pure formatting helpers**: `token-stats.ts` and the shared library's `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, subscription segment construction, and progress-bar rendering, making them easy to test.
|
|
29
28
|
|
|
30
29
|
## Data & Control Flow
|
|
31
30
|
|
|
@@ -38,8 +37,8 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
38
37
|
- Extension status line (only when statuses exist).
|
|
39
38
|
5. **Usage aggregation**: `calculateUsageTotals` in `token-stats.ts` sums assistant-message token counts and computes the latest cache hit rate from `sessionManager.getEntries()`.
|
|
40
39
|
6. **Stats composition**: `buildStatsLeft` receives the pre-computed totals, display toggles, context usage, context window, subscription segment, and theme; it returns the left-hand stats string.
|
|
41
|
-
7. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks `
|
|
42
|
-
8. **Async refresh**:
|
|
40
|
+
7. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks the injected `SubscriptionUsageCache.ensureFresh(provider)` for cached data (`ok` windows or last-success windows for temporary failures), picks the rate window with the nearest reset via `pickSubscriptionUsageWindow`, and builds a colored progress segment via `buildSubscriptionUsageSegment` in `token-stats.ts`.
|
|
41
|
+
8. **Async refresh**: the shared cache fetches asynchronously after its TTL. Completion notifications call `tui.requestRender()` through the component subscription; network/http-error/unavailable retain last-success windows, while no-auth/expired hide usage. Temporary failures without earlier successful windows also hide usage.
|
|
43
42
|
9. **Git branch updates**: `footerData.onBranchChange` registers a render request callback that is cleaned up in `dispose`.
|
|
44
43
|
|
|
45
44
|
## Integration Points
|
|
@@ -48,5 +47,5 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
48
47
|
- **`@earendil-works/pi-tui`**: Implements the `Component` contract and uses `truncateToWidth`, `visibleWidth`, and `TUI.requestRender`.
|
|
49
48
|
- **`../../config-loader`**: Reads the `custom_footer` feature flag and full footer config (colors, icons, display toggles) via `ConfigLoader`.
|
|
50
49
|
- **`../../schemas/config.schema`**: `CustomFooterConfig` is derived from the `Config` schema's `custom_footer` shape.
|
|
51
|
-
- **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text
|
|
50
|
+
- **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text and model name. Subscription labels, filled progress and percentages use fixed provider colors from the shared usage library; no footer usage-color configuration remains.
|
|
52
51
|
- **`../../libs/subscription-usage/**`**: Delegates OAuth usage fetching and reset formatting to `SubscriptionUsageApi` and provider-specific strategies.
|
|
@@ -2,7 +2,7 @@ import { basename } from 'node:path';
|
|
|
2
2
|
import { dye } from '@0xkahi/cli-dye';
|
|
3
3
|
import type { Component } from '@earendil-works/pi-tui';
|
|
4
4
|
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
5
|
-
import { pickSubscriptionUsageWindow, resolveSupportedProvider
|
|
5
|
+
import { pickSubscriptionUsageWindow, resolveSupportedProvider } from '../../libs/subscription-usage';
|
|
6
6
|
import { buildStatsLeft, buildSubscriptionUsageSegment, calculateUsageTotals } from './token-stats';
|
|
7
7
|
import type { CustomFooterComponentDeps, CustomFooterConfig } from './types';
|
|
8
8
|
|
|
@@ -16,14 +16,14 @@ function sanitizeStatusText(text: string): string {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export class CustomFooterComponent implements Component {
|
|
19
|
-
private readonly
|
|
19
|
+
private readonly unsubscribeUsage: () => void;
|
|
20
20
|
private readonly unsubscribeBranch: () => void;
|
|
21
21
|
private readonly unsubscribeAgentDisplay: () => void;
|
|
22
22
|
private restoredDefaultFooter = false;
|
|
23
23
|
private disposed = false;
|
|
24
24
|
|
|
25
25
|
constructor(private readonly deps: CustomFooterComponentDeps) {
|
|
26
|
-
this.
|
|
26
|
+
this.unsubscribeUsage = deps.usageCache.subscribe(() => {
|
|
27
27
|
if (!this.disposed) deps.tui.requestRender();
|
|
28
28
|
});
|
|
29
29
|
this.unsubscribeBranch = deps.footerData.onBranchChange(() => deps.tui.requestRender());
|
|
@@ -38,6 +38,7 @@ export class CustomFooterComponent implements Component {
|
|
|
38
38
|
|
|
39
39
|
dispose(): void {
|
|
40
40
|
this.disposed = true;
|
|
41
|
+
this.unsubscribeUsage();
|
|
41
42
|
this.unsubscribeBranch();
|
|
42
43
|
this.unsubscribeAgentDisplay();
|
|
43
44
|
}
|
|
@@ -187,14 +188,15 @@ export class CustomFooterComponent implements Component {
|
|
|
187
188
|
const provider = resolveSupportedProvider(model.provider);
|
|
188
189
|
if (!provider) return undefined;
|
|
189
190
|
|
|
190
|
-
const
|
|
191
|
-
|
|
191
|
+
const entry = this.deps.usageCache.ensureFresh(provider);
|
|
192
|
+
const response = entry?.result;
|
|
193
|
+
if (!response || response.status === 'no-auth' || response.status === 'expired') return undefined;
|
|
192
194
|
|
|
193
|
-
const
|
|
195
|
+
const windows = response.status === 'ok' ? response.windows : entry?.lastSuccess?.windows;
|
|
196
|
+
const window = pickSubscriptionUsageWindow(windows ?? []);
|
|
194
197
|
if (!window) return undefined;
|
|
195
198
|
|
|
196
199
|
return buildSubscriptionUsageSegment({
|
|
197
|
-
colors: config.colors,
|
|
198
200
|
icons: config.icons,
|
|
199
201
|
theme: this.deps.theme,
|
|
200
202
|
usage: {
|
|
@@ -202,7 +204,7 @@ export class CustomFooterComponent implements Component {
|
|
|
202
204
|
responseLabel: response.label,
|
|
203
205
|
windowLabel: window.label,
|
|
204
206
|
usedPercent: window.usedPercent,
|
|
205
|
-
resetDescription: window.resetAt ? this.
|
|
207
|
+
resetDescription: window.resetAt ? this.deps.usageCache.formatResetDescription(window.resetAt) : undefined,
|
|
206
208
|
},
|
|
207
209
|
});
|
|
208
210
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import type { ConfigLoader } from '../../config-loader';
|
|
3
3
|
import { SET_AGENT_NAME_EVENT_ID } from '../../constants';
|
|
4
|
+
import type { SubscriptionUsageCache } from '../../libs/subscription-usage';
|
|
4
5
|
import { AgentDisplayState } from './agent-display-state';
|
|
5
6
|
import { CustomFooterComponent } from './footer-component';
|
|
6
7
|
|
|
7
|
-
export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader }): void {
|
|
8
|
+
export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader; usageCache: SubscriptionUsageCache }): void {
|
|
8
9
|
let installed = false;
|
|
9
10
|
const agentDisplayState = new AgentDisplayState('DEFAULT');
|
|
10
11
|
|
|
@@ -25,6 +26,7 @@ export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoa
|
|
|
25
26
|
footerData,
|
|
26
27
|
ctx,
|
|
27
28
|
config: deps.config,
|
|
29
|
+
usageCache: deps.usageCache,
|
|
28
30
|
agentDisplayState,
|
|
29
31
|
getThinkingLevel: () => pi.getThinkingLevel(),
|
|
30
32
|
}),
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { dye } from '@0xkahi/cli-dye';
|
|
2
2
|
import type { Usage } from '@earendil-works/pi-ai';
|
|
3
3
|
import type { ContextUsage, SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
4
|
-
import { clampPercent, renderProgressBar } from '
|
|
5
|
-
import
|
|
4
|
+
import { clampPercent, providerUsageColor, renderProgressBar } from '../../libs/subscription-usage';
|
|
5
|
+
import { EMPTY_BAR_ICON, FILLED_BAR_ICON, SUBSCRIPTION_BAR_WIDTH } from './constants';
|
|
6
|
+
import type { CustomFooterDisplay, CustomFooterIcons, FooterTheme, SupportedProvider, UsageTotals } from './types';
|
|
6
7
|
|
|
7
8
|
export type SubscriptionUsageSegmentInput = {
|
|
8
9
|
provider: SupportedProvider;
|
|
@@ -66,20 +67,18 @@ function addUsageToTotals(totals: UsageTotals, usage: Usage): void {
|
|
|
66
67
|
}
|
|
67
68
|
|
|
68
69
|
export function buildSubscriptionUsageSegment({
|
|
69
|
-
colors,
|
|
70
70
|
icons,
|
|
71
71
|
theme,
|
|
72
72
|
usage,
|
|
73
73
|
}: {
|
|
74
|
-
colors: Pick<CustomFooterColors, 'anthropicUsage' | 'codexUsage'>;
|
|
75
74
|
icons: Pick<CustomFooterIcons, 'refresh'>;
|
|
76
75
|
theme: FooterTheme;
|
|
77
76
|
usage: SubscriptionUsageSegmentInput;
|
|
78
77
|
}): string {
|
|
79
|
-
const providerColor = usage.provider
|
|
78
|
+
const providerColor = providerUsageColor(usage.provider);
|
|
80
79
|
const pct = clampPercent(usage.usedPercent);
|
|
81
80
|
const roundedPercent = Math.round(pct).toString();
|
|
82
|
-
const bar = renderProgressBar(pct);
|
|
81
|
+
const bar = renderProgressBar(pct, SUBSCRIPTION_BAR_WIDTH, { filled: FILLED_BAR_ICON, empty: EMPTY_BAR_ICON });
|
|
83
82
|
const foreground = dye.hex(providerColor);
|
|
84
83
|
|
|
85
84
|
const resetParts = usage.resetDescription ? [icons.refresh, usage.resetDescription].filter(Boolean).join(' ') : '';
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import type { TUI } from '@earendil-works/pi-tui';
|
|
3
3
|
import type { ConfigLoader } from '../../config-loader';
|
|
4
|
+
import type { SubscriptionProvider, SubscriptionUsageCache } from '../../libs/subscription-usage';
|
|
4
5
|
import type { Config } from '../../schemas/config.schema';
|
|
5
6
|
import type { AgentDisplayState } from './agent-display-state';
|
|
6
7
|
|
|
7
|
-
export type SupportedProvider =
|
|
8
|
+
export type SupportedProvider = SubscriptionProvider;
|
|
8
9
|
|
|
9
10
|
export type CustomFooterConfig = Config['custom_footer'];
|
|
10
11
|
export type CustomFooterColors = CustomFooterConfig['colors'];
|
|
@@ -29,6 +30,7 @@ export type CustomFooterComponentDeps = {
|
|
|
29
30
|
ctx: ExtensionContext;
|
|
30
31
|
config: ConfigLoader;
|
|
31
32
|
agentDisplayState: AgentDisplayState;
|
|
33
|
+
usageCache: SubscriptionUsageCache;
|
|
32
34
|
getThinkingLevel: () => string;
|
|
33
35
|
};
|
|
34
36
|
|
|
@@ -13,10 +13,12 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
13
13
|
- `index.ts`: orchestrates activation, command handling, applying the selected model, setting default reasoning, and bridging registry errors into the dialog.
|
|
14
14
|
- `model-lists.ts`: queries the registry and prepares favourite, grouped favourite, and searchable model lists; validates favourite entries against the registry and configured auth.
|
|
15
15
|
- `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, token formatting, capability detection, and search-text generation.
|
|
16
|
-
- `model-select-dialog.ts`:
|
|
16
|
+
- `model-select-dialog.ts`: `createSelectModelSection` builds an embedded `ModalDialog` with one `ListTab` per tab (permanent Favourites, groups, Search), shared filter, warnings, and row/empty-state/footer hooks.
|
|
17
|
+
- `model-select-modal.ts`: `ModelSelectModal` composes Select Model (initial) and Usage through `SectionedModal`, uses the presenter frame typed as `SectionFrame`, subscribes to the shared usage cache, and starts a 1s interval that requests renders only while Usage is active. Completion from either section and host `dispose()` share idempotent interval/subscription cleanup; `scheduleTick` can be injected for tests.
|
|
18
|
+
- `usage-section/`: [usage section map](usage-section/codemap.md); Claude/Codex provider tabs, explicit status and freshness, all window rows with progress/reset/pace, retained Vim row navigation, and `r` refresh.
|
|
17
19
|
- `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
|
|
18
20
|
- `types.ts`: shared item, list, tab, and dialog option types.
|
|
19
|
-
- **Modal library delegation**: `
|
|
21
|
+
- **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+] and disambiguated Ctrl+[ wrap sections, bare Esc stays dismissal, and Tab stays inside the active section. Each dialog shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
|
|
20
22
|
- **Layout-aware presentation**: `showModelSelector` passes `model_select.layout` to the shared modal presenter, which coordinates the dialog's inline/bordered frame with normal or centered overlay mounting.
|
|
21
23
|
- **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
|
|
22
24
|
|
|
@@ -42,14 +44,15 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
42
44
|
- Favourites must exist in the registry and have configured auth; missing or unauthenticated entries are collected as warnings and omitted from the list.
|
|
43
45
|
- Accepted favourites retain exact group memberships; the ordered `groups` config defines the visible group tabs. Duplicate favourite models are deduplicated by provider/id, and duplicate group names are collapsed while preserving configured order.
|
|
44
46
|
- Any model-registry error is added to the dialog's `configWarnings` so it appears inside the picker.
|
|
45
|
-
- The shared `presentModal` helper creates a `
|
|
47
|
+
- The shared `presentModal` helper creates a `ModelSelectModal` with favourite/group/search lists, tab visibility controls, the current model, warnings, `initialSearch`, resolved frame, `defaultReasoning`, and an `onDone` callback. The overlay layout remains centered at 85% width with a one-cell margin.
|
|
46
48
|
- The dialog always creates a Favourites tab, adds visible group tabs and optional Search, and renders a width-aware tab strip, shared filter input, warnings, and help footer. If `initialSearch` is non-empty and Search is visible, the dialog starts on the Search tab and seeds the input.
|
|
47
49
|
|
|
48
50
|
5. **User interaction**
|
|
49
51
|
- Keyboard input is mapped through `keybindings.matches` for navigation, ordered tab cycling (`tab`/`shift+tab`), page up/down, confirmation, and cancellation.
|
|
50
52
|
- Typing updates one shared query and re-filters every visible tab via `fuzzyFilter`; each tab retains its own selection index.
|
|
51
53
|
- The Search tab displays the active `provider_filter` above the query input.
|
|
52
|
-
- Confirming a selection invokes `onDone` with the chosen `Model`; cancelling invokes `onDone(null)
|
|
54
|
+
- Confirming a selection invokes `onDone` with the chosen `Model`; cancelling from either section invokes `onDone(null)`, unsubscribing from usage cache updates first.
|
|
55
|
+
- Select Model alone makes no usage requests. First Usage activation calls `ensureFresh` for every supported provider; TTL and in-flight deduplication belong to the shared cache. Current provider preselection defaults to Claude when unsupported. Usage uses Vim navigation without a filter, and raw `r` forces active-provider refresh; cache completion requests re-render.
|
|
53
56
|
|
|
54
57
|
6. **Apply result**
|
|
55
58
|
- If a model is selected, `applySelectedModel` calls `pi.setModel`.
|
|
@@ -74,6 +77,7 @@ The `model_select` configuration is defined by `../../schemas/model-select.confi
|
|
|
74
77
|
- **`ExtensionAPI` (`@earendil-works/pi-coding-agent`)**: used to register the command, listen to `session_start`, set the active model (`pi.setModel`), set the thinking level (`pi.setThinkingLevel`), and access the shared event bus (`pi.events`).
|
|
75
78
|
- **`ExtensionContext` / `ExtensionCommandContext` (`@earendil-works/pi-coding-agent`)**: provides `modelRegistry`, `ui`, `hasUI`, `model`, `cwd`, and the optional `waitForIdle` guard.
|
|
76
79
|
- **`ModelRegistry`**: refreshed and queried for available models, configured auth, lookup by `provider` + `modelId`, and error state (`getError`).
|
|
80
|
+
- **`SubscriptionUsageCache` (`../../libs/subscription-usage`)**: injected from the root, shared with the footer; statuses and last-success windows drive Usage content, pace and progress helpers format its rows.
|
|
77
81
|
- **`ConfigLoader` (`../../config-loader`)**: provides feature toggle state (`isEnabled('model_select')`), the typed `model_select` configuration object, and merges global + project JSON config.
|
|
78
82
|
- **`@earendil-works/pi-ai`**: supplies the `Model<Api>` type, `modelsAreEqual` for stable identity comparisons, and `getSupportedThinkingLevels` for reasoning-level validation.
|
|
79
83
|
- **`@earendil-works/pi-tui`**: supplies the `Input` component, `fuzzyFilter`, `matchesKey`, theme helpers, and rendering utilities (`truncateToWidth`, `visibleWidth`) used by the dialog.
|