@0xkahi/pi-qol 1.2.0 → 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 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 runs in the background and
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 on the very first real user turn of a session.
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
@@ -100,6 +104,7 @@ them (project overrides global):
100
104
  "$schema": "https://raw.githubusercontent.com/0xKahi/pi-qol/main/assets/config.schema.json",
101
105
  "auto_session_name": {
102
106
  "enabled": true,
107
+ "custom_message_whitelist": [],
103
108
  "model": {
104
109
  "provider": "opencode",
105
110
  "modelId": "gpt-5-nano",
@@ -146,10 +151,11 @@ them (project overrides global):
146
151
 
147
152
  #### `auto_session_name`
148
153
 
149
- | Key | Type | Default | Description |
150
- | --------- | --------- | ------- | ------------------------------------------------------------------ |
151
- | `enabled` | `boolean` | `false` | Turn the auto session naming feature on. |
152
- | `model` | `object` | — | Optional model used to generate titles. Falls back to the session model if omitted. |
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. |
153
159
 
154
160
 
155
161
  #### `model`
@@ -250,10 +256,17 @@ On `before_agent_start`, the `auto_session_name` extension checks a series of
250
256
  guards before doing any work. It only proceeds when **all** of the following hold:
251
257
 
252
258
  1. The feature is enabled in config.
253
- 2. The session does not already have a name.
254
- 3. The session is not a fork/child session.
255
- 4. It is the user's first turn.
256
- 5. The user prompt is non-empty.
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.
257
270
 
258
271
  If those pass, it resolves a model, generates a title via a dedicated
259
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
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.2.0",
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": "^0.99.2",
49
- "@earendil-works/pi-coding-agent": "^0.99.2",
50
- "@earendil-works/pi-tui": "^0.99.2",
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": "^5"
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 for a Pi session based on the user's first user turn. The extension runs once per session, only on the user's first turn, and only when no session name has already been set and the session is not 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.
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
- - This is the user's first turn (zero prior user messages in the branch).
25
- - The current user prompt is non-empty.
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 user turn and child sessions.
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 isUsersFirstTurn(sessionManager: Pick<SessionManagerForGuards, 'getBranch'>): boolean {
18
- // Pi emits before_agent_start before appending the current user message, so a fresh opening turn has zero prior user messages.
19
- const userMsgs = sessionManager.getBranch().filter(AutoSessionNameGuard.userEntryFilter);
20
- return userMsgs.length === 0;
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 isFirstCustomExtensionMessage(sessionManager: Pick<SessionManagerForGuards, 'getBranch'>, whitelist: Set<string>): boolean {
24
- const customMsg = sessionManager.getBranch().filter(entry => entry.type === 'custom_message' && whitelist.has(entry.customType));
25
- return customMsg.length === 0;
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.isUsersFirstTurn(ctx.sessionManager)) return;
77
+ if (!AutoSessionNameGuard.isFirstNamingTurn(ctx.sessionManager, whitelist)) return;
73
78
 
74
- const userText = event.prompt?.trim();
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
+ }
@@ -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
- // customMessageWhitelist: z.array(z.string()).describe('a list of pi custom_messages, customType to be used to trigger auto session name'),
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 = AutoSessionNameConfigSchema.partial();
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
- // customMessageWhitelist: [],
12
+ custom_message_whitelist: [],
13
13
  }),
14
14
  model_select: ModelSelectConfigSchema.default({
15
15
  enabled: false,