@0xkahi/pi-qol 1.2.0 → 1.4.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 +37 -19
- package/assets/config.schema.json +10 -1
- 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/footer-component.ts +1 -1
- package/src/extensions/model-select/codemap.md +1 -1
- package/src/libs/modal/README.md +4 -3
- package/src/libs/modal/codemap.md +1 -1
- package/src/libs/modal/sectioned-modal.ts +3 -3
- package/src/libs/subscription-usage/codemap.md +4 -3
- package/src/libs/subscription-usage/credential-resolver.ts +12 -4
- package/src/libs/subscription-usage/index.ts +1 -0
- package/src/libs/subscription-usage/provider-color.ts +1 -0
- package/src/libs/subscription-usage/strategy/opencode-go-usage.strategy.ts +45 -0
- package/src/libs/subscription-usage/subscription-usage-api.util.ts +4 -1
- package/src/libs/subscription-usage/subscription-usage-cache.ts +11 -1
- package/src/schemas/auto-session-name.config.schema.ts +9 -2
- package/src/schemas/config.schema.ts +1 -1
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,10 +48,11 @@ 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
|
|
47
|
-
- **sections**: opens on Select Model; `Ctrl+
|
|
48
|
-
`Ctrl+
|
|
49
|
-
|
|
50
|
-
|
|
51
|
+
- **sections**: opens on Select Model; `Ctrl+L` switches to the next section and
|
|
52
|
+
`Ctrl+H` to the previous (both wrap). `Ctrl+H` needs a terminal that reports it
|
|
53
|
+
distinctly (Kitty, CSI-u, or modifyOtherKeys); otherwise it acts as Backspace.
|
|
54
|
+
`Ctrl+L` works everywhere. Tab/Shift+Tab stay within the active section.
|
|
55
|
+
- **Usage**: `[Claude]` `[Codex]` `[OC-GO]` tabs show every subscription rate window,
|
|
51
56
|
separated by blank lines, with a progress bar, used percentage, reset time,
|
|
52
57
|
pace, and data freshness. Fixed provider colors match the custom footer. Missing
|
|
53
58
|
credentials and request failures are shown explicitly. Usage shares the footer
|
|
@@ -61,9 +66,13 @@ allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with
|
|
|
61
66
|
|
|
62
67
|
Replaces pi's built-in interactive footer with the same three-line layout, but
|
|
63
68
|
shows the current directory as an icon plus basename, supports hex color overrides,
|
|
64
|
-
can hide token/cache clusters, and adds
|
|
65
|
-
for supported providers (Anthropic
|
|
66
|
-
|
|
69
|
+
can hide token/cache clusters, and adds a subscription-usage progress bar
|
|
70
|
+
for supported providers (Anthropic, OpenAI Codex, and OpenCode Go via model provider
|
|
71
|
+
`opencode-go`, not OpenCode Zen `opencode`). Usage colors are fixed: Claude
|
|
72
|
+
`#D97706`, Codex `#10B981`, and OC-GO `#00ADD8`; former usage-color overrides are ignored.
|
|
73
|
+
OpenCode Go shows `5h`, `Week`, and `Month` windows and requires an `opencode-go`
|
|
74
|
+
entry of type `api_key` in `~/.pi/agent/auth.json`, with the secret in `key`;
|
|
75
|
+
`OPENCODE_API_KEY` alone is not used. Claude and Codex require OAuth entries.
|
|
67
76
|
|
|
68
77
|
- **Directory line** — optional inverse-styled agent badge followed by the
|
|
69
78
|
directory icon + basename, with optional git branch and session name. The badge
|
|
@@ -73,7 +82,7 @@ Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
|
|
|
73
82
|
right-aligned model name (with provider prefix when multiple providers are
|
|
74
83
|
available).
|
|
75
84
|
- **Subscription usage** — a colored progress bar plus percentage and reset time
|
|
76
|
-
for the active
|
|
85
|
+
for the active subscription provider. Usage is fetched lazily and cached, refreshing
|
|
77
86
|
at most once every 60 seconds per provider; auth/network failures simply hide
|
|
78
87
|
the segment.
|
|
79
88
|
|
|
@@ -100,6 +109,7 @@ them (project overrides global):
|
|
|
100
109
|
"$schema": "https://raw.githubusercontent.com/0xKahi/pi-qol/main/assets/config.schema.json",
|
|
101
110
|
"auto_session_name": {
|
|
102
111
|
"enabled": true,
|
|
112
|
+
"custom_message_whitelist": [],
|
|
103
113
|
"model": {
|
|
104
114
|
"provider": "opencode",
|
|
105
115
|
"modelId": "gpt-5-nano",
|
|
@@ -146,10 +156,11 @@ them (project overrides global):
|
|
|
146
156
|
|
|
147
157
|
#### `auto_session_name`
|
|
148
158
|
|
|
149
|
-
| Key
|
|
150
|
-
|
|
|
151
|
-
| `enabled`
|
|
152
|
-
| `
|
|
159
|
+
| Key | Type | Default | Description |
|
|
160
|
+
| -------------------------- | ---------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
161
|
+
| `enabled` | `boolean` | `false` | Turn the auto session naming feature on. |
|
|
162
|
+
| `custom_message_whitelist` | `string[]` | `[]` | Allowed `customType` values for `pi.sendMessage(..., { triggerTurn: true })` runs. Empty means only user prompts. |
|
|
163
|
+
| `model` | `object` | — | Optional model used to generate titles. Falls back to the session model if omitted. |
|
|
153
164
|
|
|
154
165
|
|
|
155
166
|
#### `model`
|
|
@@ -250,10 +261,17 @@ On `before_agent_start`, the `auto_session_name` extension checks a series of
|
|
|
250
261
|
guards before doing any work. It only proceeds when **all** of the following hold:
|
|
251
262
|
|
|
252
263
|
1. The feature is enabled in config.
|
|
253
|
-
2. The
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
264
|
+
2. The run starts with a non-empty user prompt, or a custom message whose
|
|
265
|
+
`customType` is in `custom_message_whitelist` and whose text is non-empty
|
|
266
|
+
(image blocks are ignored).
|
|
267
|
+
3. The session does not already have a name and is not a fork/child session.
|
|
268
|
+
4. The branch has no prior user messages or whitelisted custom messages with
|
|
269
|
+
non-whitespace text. Blank or image-only messages are ignored, using the same
|
|
270
|
+
text rule as step 2, so they never block a later message from naming the session.
|
|
271
|
+
|
|
272
|
+
Pi >=1.2 emits this event for both user and custom runs, before appending the
|
|
273
|
+
starting message to the branch. Non-whitelisted custom runs are skipped before
|
|
274
|
+
session guards and their messages do not block later naming.
|
|
257
275
|
|
|
258
276
|
If those pass, it resolves a model, generates a title via a dedicated
|
|
259
277
|
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
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xkahi/pi-qol",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.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
|
+
}
|
|
@@ -160,7 +160,7 @@ export class CustomFooterComponent implements Component {
|
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
private isUsingSubscription(model: NonNullable<CustomFooterComponentDeps['ctx']['model']>): boolean {
|
|
163
|
-
if (model.provider === 'kimi-coding') return true;
|
|
163
|
+
if (model.provider === 'kimi-coding' || model.provider === 'opencode-go') return true;
|
|
164
164
|
|
|
165
165
|
return (
|
|
166
166
|
this.deps.ctx.modelRegistry.isUsingOAuth(model) && this.deps.ctx.modelRegistry.getProvider(model.provider)?.auth?.oauth?.isSubscription === true
|
|
@@ -18,7 +18,7 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
18
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.
|
|
19
19
|
- `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
|
|
20
20
|
- `types.ts`: shared item, list, tab, and dialog option types.
|
|
21
|
-
- **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+
|
|
21
|
+
- **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+L and disambiguated Ctrl+H 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.
|
|
22
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.
|
|
23
23
|
- **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
|
|
24
24
|
|
package/src/libs/modal/README.md
CHANGED
|
@@ -86,9 +86,10 @@ Wire every dialog's `onComplete` to the same host `done` callback and choose its
|
|
|
86
86
|
`cancelValue`. Section state survives switches, and natural height follows the
|
|
87
87
|
active section. `onActivate` runs once per section, including the initial section.
|
|
88
88
|
|
|
89
|
-
Input routing: `Ctrl+
|
|
90
|
-
(both wrap); all other input goes to the active dialog.
|
|
91
|
-
|
|
89
|
+
Input routing: `Ctrl+L` goes forward and disambiguated `Ctrl+H` goes backward
|
|
90
|
+
(both wrap); all other input goes to the active dialog. A raw `0x08` byte is always
|
|
91
|
+
Backspace for the active dialog, so `Ctrl+H` needs a terminal that reports it
|
|
92
|
+
distinctly. Bare Esc always dismisses through that dialog (layers close first).
|
|
92
93
|
Tab/Shift+Tab stay inside the section. Switching clears pending navigation chords.
|
|
93
94
|
Only the active dialog receives focus. Multiple sections add a footer hint.
|
|
94
95
|
|
|
@@ -16,7 +16,7 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
|
|
|
16
16
|
- `tabs/list-tab.ts` — `ListTab<T>` generic picker tab: items + row renderer + confirm callback, optional fuzzy filtering (`filterText`) wired to the dialog filter, dynamic count labels, filter captions, footer hook (rendered below the list in all states), empty/no-match messages, fixed or height-driven window, clamp (default) or wrap selection.
|
|
17
17
|
- `preview-layer.ts` — `PreviewLayer`: title + right-aligned meta header, `PreviewScroller`-windowed body, overflow counter, optional pinned description; dismissal is shell-owned (pops the layer).
|
|
18
18
|
- `list-navigator.ts` — `ListNavigator` (selection + scroll window; clamp default, `wrap` option; `setRowCount` for filtered lists) and `PreviewScroller` (scroll-only window over wrapped lines). Forked from `pi-context-view`.
|
|
19
|
-
- `sectioned-modal.ts` — Exports `SectionFrame` (`inline` | `bordered`) for section host framing. `SectionedModal<TResult>` hosts retained `ModalSection` dialogs with `frame: 'none'`, draws the frame, routes Ctrl+
|
|
19
|
+
- `sectioned-modal.ts` — Exports `SectionFrame` (`inline` | `bordered`) for section host framing. `SectionedModal<TResult>` hosts retained `ModalSection` dialogs with `frame: 'none'`, draws the frame, routes Ctrl+L/disambiguated Ctrl+H (raw `0x08` stays Backspace) before dialog input, resets outgoing navigation, propagates active-only focus, and runs first-activation callbacks. Callers wire every dialog completion to the same host sink and own resource cleanup (for example an idempotent `dispose()` on a consumer subclass). Bare Esc stays dialog input; Tab stays within sections; natural height follows the active dialog.
|
|
20
20
|
- `section-strip.ts` — `renderSectionRule` draws active/inactive section labels in the top rule or rounded border, adding no height.
|
|
21
21
|
- `label-window.ts` — Shared active-centered overflow window computation for tab and section strips.
|
|
22
22
|
- `tab-strip.ts` — Width-aware tab strip: active label highlighted; overflow keeps a window around the active tab with `…` omission indicators. Labels are re-read each render.
|
|
@@ -29,7 +29,7 @@ export class SectionedModal<TResult> implements Component, Focusable {
|
|
|
29
29
|
this.activeIndex = Math.min(Math.max(0, options.initialSectionIndex ?? 0), options.sections.length - 1);
|
|
30
30
|
for (const section of options.sections) {
|
|
31
31
|
section.dialog.focused = false;
|
|
32
|
-
if (options.sections.length > 1) section.dialog.setExtraHints([['^
|
|
32
|
+
if (options.sections.length > 1) section.dialog.setExtraHints([['^L/^H', 'Section']]);
|
|
33
33
|
}
|
|
34
34
|
this.activate();
|
|
35
35
|
}
|
|
@@ -48,9 +48,9 @@ export class SectionedModal<TResult> implements Component, Focusable {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
public handleInput(data: string): void {
|
|
51
|
-
if (matchesKey(data, 'ctrl+
|
|
51
|
+
if (matchesKey(data, 'ctrl+l')) {
|
|
52
52
|
this.switchSection(1);
|
|
53
|
-
} else if (data !== '\
|
|
53
|
+
} else if (data !== '\x08' && matchesKey(data, 'ctrl+h')) {
|
|
54
54
|
this.switchSection(-1);
|
|
55
55
|
} else {
|
|
56
56
|
this.activeDialog().handleInput(data);
|
|
@@ -2,15 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
Shared subscription data pipeline for Claude and
|
|
5
|
+
Shared subscription data pipeline for Claude, Codex, and OpenCode Go (`opencode-go`, not Zen `opencode`), exported through `index.ts`.
|
|
6
6
|
|
|
7
7
|
- `subscription-usage-api.util.ts`: provider/auth/window types, supported-provider labels derived from strategies, shared fetch timeout and TTL constants, status-discriminated `UsageResult`, injectable API. Classifies no-auth, expired, HTTP errors, network/timeout, unavailable and ok; owns fetch timeout and error catching. Malformed JSON is unavailable; fetch and abort failures remain network.
|
|
8
|
-
- `credential-resolver.ts`:
|
|
8
|
+
- `credential-resolver.ts`: requires an auth.json entry and checks per-provider accepted auth types through PathUtil and RawDataParser: `anthropic`/`openai-codex` accept `oauth` (missing type defaults to `oauth`); `opencode-go` accepts `api_key`. Asks the latest host context for credentials, falls back to stored access for OAuth or stored key for API keys; env-only credentials are not used. Codex account id comes from stored accountId or defensive JWT decoding.
|
|
9
9
|
- `subscription-usage-cache.ts`: shared injected cache with TTL, per-provider in-flight deduplication, forced refresh, retained last-success windows/timestamp, and completion subscribers. Includes provider aliases and soonest-reset window selection.
|
|
10
10
|
- `pace.ts`: pure elapsed-window pace and relative reset formatting.
|
|
11
11
|
- `progress-bar.ts`: pure percentage clamp and glyph-configurable bar (defaults █/░).
|
|
12
|
-
- `provider-color.ts`: fixed shared provider colors (Claude #D97706, Codex #10B981), exported as PROVIDER_USAGE_COLORS and providerUsageColor; no configuration dependency.
|
|
12
|
+
- `provider-color.ts`: fixed shared provider colors (Claude #D97706, Codex #10B981, OC-GO #00ADD8), exported as PROVIDER_USAGE_COLORS and providerUsageColor; no configuration dependency.
|
|
13
13
|
- `strategy/`: pure request construction and JSON normalization; no network I/O.
|
|
14
|
+
- `strategy/opencode-go-usage.strategy.ts`: OpenCode Go bearer-key status request and meter normalization into `5h`, `Week`, and `Month` windows.
|
|
14
15
|
|
|
15
16
|
## Flow
|
|
16
17
|
|
|
@@ -2,7 +2,13 @@ import { readFileSync } from 'node:fs';
|
|
|
2
2
|
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
3
3
|
import { PathUtil } from '../../utils/path.util';
|
|
4
4
|
import { RawDataParser } from '../../utils/raw-data-parser.util';
|
|
5
|
-
import type { CredentialResolver } from './subscription-usage-api.util';
|
|
5
|
+
import type { CredentialResolver, SubscriptionProvider } from './subscription-usage-api.util';
|
|
6
|
+
|
|
7
|
+
const ACCEPTED_AUTH_TYPES: Record<SubscriptionProvider, readonly string[]> = {
|
|
8
|
+
anthropic: ['oauth'],
|
|
9
|
+
'openai-codex': ['oauth'],
|
|
10
|
+
'opencode-go': ['api_key'],
|
|
11
|
+
};
|
|
6
12
|
|
|
7
13
|
function jwtAccountId(token: string): string | undefined {
|
|
8
14
|
try {
|
|
@@ -23,15 +29,17 @@ export function createHostCredentialResolver(getCtx: () => ExtensionContext | un
|
|
|
23
29
|
if (!path.exists) return undefined;
|
|
24
30
|
const config = RawDataParser.asRecord(JSON.parse(readFileSync(path.path, 'utf8')));
|
|
25
31
|
const stored = RawDataParser.asRecord(config?.[provider]);
|
|
26
|
-
if (!stored
|
|
32
|
+
if (!stored) return undefined;
|
|
33
|
+
const authType = stored.type === undefined ? 'oauth' : stored.type;
|
|
34
|
+
if (typeof authType !== 'string' || !ACCEPTED_AUTH_TYPES[provider].includes(authType)) return undefined;
|
|
27
35
|
let token: string | undefined;
|
|
28
36
|
try {
|
|
29
37
|
const resolved = await getCtx()?.modelRegistry.getProviderAuth(provider);
|
|
30
38
|
token = RawDataParser.stringValue(resolved?.auth?.apiKey);
|
|
31
39
|
} catch {
|
|
32
|
-
//
|
|
40
|
+
// The stored secret is the verified fallback when host resolution fails.
|
|
33
41
|
}
|
|
34
|
-
token ||= RawDataParser.stringValue(stored.access);
|
|
42
|
+
token ||= RawDataParser.stringValue(authType === 'api_key' ? stored.key : stored.access);
|
|
35
43
|
if (!token) return undefined;
|
|
36
44
|
return {
|
|
37
45
|
token,
|
|
@@ -4,5 +4,6 @@ export * from './progress-bar';
|
|
|
4
4
|
export * from './provider-color';
|
|
5
5
|
export * from './strategy/anthropic-oauth-usage.strategy';
|
|
6
6
|
export * from './strategy/openai-codex-usage.strategy';
|
|
7
|
+
export * from './strategy/opencode-go-usage.strategy';
|
|
7
8
|
export * from './subscription-usage-api.util';
|
|
8
9
|
export * from './subscription-usage-cache';
|
|
@@ -3,6 +3,7 @@ import type { SubscriptionProvider } from './subscription-usage-api.util';
|
|
|
3
3
|
export const PROVIDER_USAGE_COLORS: Readonly<Record<SubscriptionProvider, string>> = {
|
|
4
4
|
anthropic: '#D97706',
|
|
5
5
|
'openai-codex': '#10B981',
|
|
6
|
+
'opencode-go': '#00ADD8',
|
|
6
7
|
};
|
|
7
8
|
|
|
8
9
|
export function providerUsageColor(provider: SubscriptionProvider): string {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { RawDataParser } from '../../../utils/raw-data-parser.util';
|
|
2
|
+
import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
|
|
3
|
+
|
|
4
|
+
export class OpenCodeGoUsageStrategy implements SubscriptionUsageStrategy {
|
|
5
|
+
readonly provider = 'opencode-go';
|
|
6
|
+
readonly label = 'OC-GO';
|
|
7
|
+
|
|
8
|
+
parse(json: unknown): RateWindow[] {
|
|
9
|
+
const access = RawDataParser.asRecord(RawDataParser.asRecord(json)?.access);
|
|
10
|
+
const meters = RawDataParser.asRecord(access?.meters);
|
|
11
|
+
if (!meters) return [];
|
|
12
|
+
|
|
13
|
+
const windows: RateWindow[] = [];
|
|
14
|
+
for (const [key, label, fallbackSeconds] of [
|
|
15
|
+
['fiveHour', '5h', 18000],
|
|
16
|
+
['week', 'Week', 604800],
|
|
17
|
+
['month', 'Month', undefined],
|
|
18
|
+
] as const) {
|
|
19
|
+
const meter = RawDataParser.asRecord(meters[key]);
|
|
20
|
+
const limit = RawDataParser.numberValue(meter?.limitMicroCents);
|
|
21
|
+
const rawUsed = meter?.usedMicroCents;
|
|
22
|
+
if (typeof rawUsed !== 'number' && !RawDataParser.stringValue(rawUsed)) continue;
|
|
23
|
+
const used = RawDataParser.numberValue(rawUsed);
|
|
24
|
+
const reset = RawDataParser.stringValue(meter?.resetsAt);
|
|
25
|
+
const resetAt = reset ? new Date(reset) : undefined;
|
|
26
|
+
if (limit === undefined || limit <= 0 || used === undefined || !resetAt || !Number.isFinite(resetAt.getTime())) continue;
|
|
27
|
+
const start = RawDataParser.stringValue(key === 'month' ? access?.startsAt : meter?.startsAt);
|
|
28
|
+
const duration = start ? (resetAt.getTime() - new Date(start).getTime()) / 1000 : NaN;
|
|
29
|
+
windows.push({
|
|
30
|
+
label,
|
|
31
|
+
usedPercent: (used / limit) * 100,
|
|
32
|
+
resetAt,
|
|
33
|
+
windowSeconds: Number.isFinite(duration) && duration > 0 ? duration : fallbackSeconds,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return windows;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
request(auth: ProviderAuth): Request {
|
|
40
|
+
return new Request('https://opencode.ai/console/api/go/status', {
|
|
41
|
+
method: 'GET',
|
|
42
|
+
headers: { Authorization: `Bearer ${auth.token}` },
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
|
|
2
2
|
import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
|
|
3
3
|
|
|
4
|
+
import { OpenCodeGoUsageStrategy } from './strategy/opencode-go-usage.strategy';
|
|
5
|
+
|
|
4
6
|
export const SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS = 10_000;
|
|
5
7
|
export const SUBSCRIPTION_USAGE_TTL_MS = 60_000;
|
|
6
8
|
|
|
7
|
-
export type SubscriptionProvider = 'anthropic' | 'openai-codex';
|
|
9
|
+
export type SubscriptionProvider = 'anthropic' | 'openai-codex' | 'opencode-go';
|
|
8
10
|
export const SUBSCRIPTION_PROVIDERS: readonly { provider: SubscriptionProvider; label: string }[] = [
|
|
9
11
|
{ provider: 'anthropic', label: new AnthropicOauthUsageStrategy().label },
|
|
10
12
|
{ provider: 'openai-codex', label: new OpenAiCodexUsageStrategy().label },
|
|
13
|
+
{ provider: 'opencode-go', label: new OpenCodeGoUsageStrategy().label },
|
|
11
14
|
];
|
|
12
15
|
export type ProviderAuth = { token: string; accountId?: string };
|
|
13
16
|
export type CredentialResolver = (provider: SubscriptionProvider) => Promise<ProviderAuth | undefined>;
|
|
@@ -1,19 +1,29 @@
|
|
|
1
1
|
import { formatResetDescription } from './pace';
|
|
2
2
|
import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
|
|
3
3
|
import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
|
|
4
|
+
import { OpenCodeGoUsageStrategy } from './strategy/opencode-go-usage.strategy';
|
|
4
5
|
import {
|
|
5
6
|
type RateWindow,
|
|
6
7
|
SUBSCRIPTION_USAGE_TTL_MS,
|
|
7
8
|
type SubscriptionProvider,
|
|
8
9
|
SubscriptionUsageApi,
|
|
9
10
|
type SubscriptionUsageApiLike,
|
|
11
|
+
type SubscriptionUsageStrategy,
|
|
10
12
|
type UsageResult,
|
|
11
13
|
} from './subscription-usage-api.util';
|
|
12
14
|
|
|
15
|
+
const STRATEGIES: Record<SubscriptionProvider, SubscriptionUsageStrategy> = {
|
|
16
|
+
anthropic: new AnthropicOauthUsageStrategy(),
|
|
17
|
+
'openai-codex': new OpenAiCodexUsageStrategy(),
|
|
18
|
+
'opencode-go': new OpenCodeGoUsageStrategy(),
|
|
19
|
+
};
|
|
20
|
+
|
|
13
21
|
export type UsageCacheEntry = { result?: UsageResult; lastSuccess?: { windows: RateWindow[]; fetchedAt: number }; inFlight: boolean };
|
|
14
22
|
|
|
15
23
|
export function resolveSupportedProvider(provider?: string): SubscriptionProvider | undefined {
|
|
16
24
|
switch (provider?.toLowerCase()) {
|
|
25
|
+
case 'opencode-go':
|
|
26
|
+
return 'opencode-go';
|
|
17
27
|
case 'anthropic':
|
|
18
28
|
return 'anthropic';
|
|
19
29
|
case 'openai-codex':
|
|
@@ -64,7 +74,7 @@ export class SubscriptionUsageCache {
|
|
|
64
74
|
const entry: UsageCacheEntry = { ...this.get(provider), inFlight: true };
|
|
65
75
|
this.entries.set(provider, entry);
|
|
66
76
|
this.lastAttemptAt.set(provider, this.now());
|
|
67
|
-
const strategy = provider
|
|
77
|
+
const strategy = STRATEGIES[provider];
|
|
68
78
|
void Promise.resolve()
|
|
69
79
|
.then(() => this.api.fetchUsage(strategy))
|
|
70
80
|
.catch((): UsageResult => ({ status: 'network', label: strategy.label }))
|
|
@@ -4,9 +4,16 @@ import { ModelConfigSchema } from './shared-config.schema';
|
|
|
4
4
|
export const AutoSessionNameConfigSchema = z.object({
|
|
5
5
|
enabled: z.boolean().default(false),
|
|
6
6
|
model: ModelConfigSchema.optional(),
|
|
7
|
-
|
|
7
|
+
custom_message_whitelist: z
|
|
8
|
+
.array(z.string())
|
|
9
|
+
.default([])
|
|
10
|
+
.describe('customType values of pi custom messages (sent with triggerTurn) that may trigger auto session naming. Empty = only user prompts.'),
|
|
8
11
|
});
|
|
9
12
|
export type AutoSessionNameConfig = z.infer<typeof AutoSessionNameConfigSchema>;
|
|
10
13
|
|
|
11
|
-
export const PartialAutoSessionNameConfigSchema =
|
|
14
|
+
export const PartialAutoSessionNameConfigSchema = z.object({
|
|
15
|
+
enabled: z.boolean().optional(),
|
|
16
|
+
model: ModelConfigSchema.optional(),
|
|
17
|
+
custom_message_whitelist: z.array(z.string()).optional(),
|
|
18
|
+
});
|
|
12
19
|
export type PartialAutoSessionNameConfig = z.infer<typeof PartialAutoSessionNameConfigSchema>;
|
|
@@ -9,7 +9,7 @@ export const ConfigSchema = z.object({
|
|
|
9
9
|
$schema: z.string().optional(),
|
|
10
10
|
auto_session_name: AutoSessionNameConfigSchema.default({
|
|
11
11
|
enabled: false,
|
|
12
|
-
|
|
12
|
+
custom_message_whitelist: [],
|
|
13
13
|
}),
|
|
14
14
|
model_select: ModelSelectConfigSchema.default({
|
|
15
15
|
enabled: false,
|