@nimanzik/pi-auto-title 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release as `@nimanzik/pi-auto-title`.
6
+
7
+ - Name sessions from their first request without blocking the conversation.
8
+ - Preserve skill prefixes and existing or manually edited titles.
9
+ - Support a pinned title model with fallback to the session model.
10
+ - Cancel pending title generation when switching sessions or shutting down.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nimanzik
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # pi-auto-title
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Pi extension that names a session from its first request. It sets a temporary
4
+ title immediately, then generates a short title in the background. Skill requests
5
+ keep their `[skill-name]` prefix. Existing or manually edited titles are preserved.
6
+
7
+ ## Installation
8
+
9
+ Install the published package with:
10
+
11
+ ```sh
12
+ pi install npm:@nimanzik/pi-auto-title
13
+ ```
14
+
15
+ The extension makes an additional model request to generate each new session
16
+ title, which may incur provider costs.
17
+
18
+ ## Model selection
19
+
20
+ By default, title generation follows the current session model. To use a different
21
+ model without changing the model answering your requests:
22
+
23
+ ```text
24
+ /auto-title model # show the effective model
25
+ /auto-title model <provider> <model> # validate and save a model pin
26
+ /auto-title model reset # follow the session model again
27
+ ```
28
+
29
+ The pinned model must exist in Pi's model registry and have credentials configured.
30
+ New pins that fail either check are rejected without changing the saved pin.
31
+
32
+ The pin applies across projects and sessions using the same agent directory.
33
+ It is stored in `<agent-dir>/auto-title.json`, usually
34
+ `~/.pi/agent/auto-title.json`. Pi's `PI_CODING_AGENT_DIR` setting is respected.
35
+ You can also edit the file directly:
36
+
37
+ ```json
38
+ {
39
+ "provider": "your-provider",
40
+ "model": "your-model-id"
41
+ }
42
+ ```
43
+
44
+ Configuration is read for each title request and model-status command. Changes
45
+ affect future title requests, not a request already running or an already named
46
+ session. Reset deletes the configuration file.
47
+
48
+ If the pinned model is unavailable or fails, the extension warns and tries the
49
+ session model once, unless it is the same model. Invalid configuration also warns
50
+ and uses the session model, without overwriting the file. Fallback can send the
51
+ request to a different provider, with that provider's costs and data policies.
52
+ Warnings appear through Pi's notification UI when supported.
53
+
54
+ Each model attempt has a 15-second timeout, allowing up to 30 seconds with fallback.
55
+ The conversation is not blocked. If generation fails, the temporary title remains.
56
+ Switching sessions or shutting down cancels pending title generation.
package/auto-title.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+
6
+ const skillPattern = /^\/skill:(\S+)\s*([\s\S]*)/;
7
+
8
+ const SUMMARY_PROMPT =
9
+ "Write a short title (5-8 words) for this request. Output only the title, no quotes, no trailing period.";
10
+
11
+ type ModelPin = { provider: string; model: string };
12
+
13
+ function readPin(path: string): ModelPin | undefined {
14
+ let text: string;
15
+ try {
16
+ text = readFileSync(path, "utf8");
17
+ } catch (error) {
18
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
19
+ throw error;
20
+ }
21
+ const pin = JSON.parse(text);
22
+ if (!pin || typeof pin.provider !== "string" || !pin.provider.trim() ||
23
+ typeof pin.model !== "string" || !pin.model.trim()) {
24
+ throw new Error(`Invalid model pin in ${path}: expected provider and model strings`);
25
+ }
26
+ return { provider: pin.provider.trim(), model: pin.model.trim() };
27
+ }
28
+
29
+ export default function (pi: ExtensionAPI) {
30
+ let named = false;
31
+ let pending: AbortController | undefined;
32
+ const configPath = join(getAgentDir(), "auto-title.json");
33
+
34
+ pi.registerCommand("auto-title", {
35
+ description: "Show, pin, or reset the title-generation model",
36
+ handler: async (args, ctx) => {
37
+ const parts = args.trim().split(/\s+/);
38
+ try {
39
+ if (parts.length === 1 && parts[0] === "model") {
40
+ let pin: ModelPin | undefined;
41
+ try {
42
+ pin = readPin(configPath);
43
+ } catch {
44
+ ctx.ui.notify(`Auto-title: cannot read ${configPath}; using the session model`, "warning");
45
+ }
46
+ const model = pin ? ctx.modelRegistry.find(pin.provider, pin.model) : ctx.model;
47
+ const available = model && ctx.modelRegistry.hasConfiguredAuth(model);
48
+ ctx.ui.notify(pin
49
+ ? `Auto-title pinned: ${pin.provider}/${pin.model}${available ? "" : `; unavailable, session model: ${ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "none"}`}`
50
+ : `Auto-title follows session model: ${model ? `${model.provider}/${model.id}` : "none"}`, "info");
51
+ } else if (parts.length === 2 && parts[0] === "model" && parts[1] === "reset") {
52
+ rmSync(configPath, { force: true });
53
+ ctx.ui.notify("Auto-title now follows the session model", "info");
54
+ } else if (parts.length === 3 && parts[0] === "model") {
55
+ const [, provider, id] = parts;
56
+ const model = ctx.modelRegistry.find(provider, id);
57
+ if (!model) throw new Error(`Unknown model: ${provider}/${id}`);
58
+ if (!ctx.modelRegistry.hasConfiguredAuth(model)) throw new Error(`No credentials configured for ${provider}/${id}`);
59
+ mkdirSync(getAgentDir(), { recursive: true });
60
+ const temporaryPath = `${configPath}.${randomUUID()}.tmp`;
61
+ try {
62
+ writeFileSync(temporaryPath, JSON.stringify({ provider, model: id }, null, 2) + "\n", { flag: "wx" });
63
+ renameSync(temporaryPath, configPath);
64
+ } finally {
65
+ rmSync(temporaryPath, { force: true });
66
+ }
67
+ ctx.ui.notify(`Auto-title pinned to ${provider}/${id}`, "info");
68
+ } else {
69
+ ctx.ui.notify("Usage: /auto-title model [<provider> <model> | reset]", "info");
70
+ }
71
+ } catch (error) {
72
+ ctx.ui.notify(`Auto-title: ${error instanceof Error ? error.message : String(error)}`, "error");
73
+ }
74
+ },
75
+ });
76
+
77
+ pi.on("session_start", () => {
78
+ pending?.abort();
79
+ pending = undefined;
80
+ named = !!pi.getSessionName();
81
+ });
82
+
83
+ pi.on("session_shutdown", () => {
84
+ pending?.abort();
85
+ pending = undefined;
86
+ });
87
+
88
+ pi.on("input", (event, ctx) => {
89
+ if (named || pi.getSessionName()) return;
90
+
91
+ const match = event.text.match(skillPattern);
92
+ const prefix = match ? `[${match[1]}] ` : "";
93
+ const userPrompt = (match ? match[2] : event.text).trim();
94
+
95
+ if (!userPrompt && !match) return;
96
+ named = true;
97
+
98
+ if (!userPrompt) {
99
+ pi.setSessionName(prefix.trim());
100
+ return;
101
+ }
102
+
103
+ pi.setSessionName(`${prefix}${userPrompt.slice(0, 60)}`);
104
+ const temporaryName = pi.getSessionName();
105
+
106
+ const sessionId = ctx.sessionManager.getSessionId();
107
+ const task = new AbortController();
108
+ pending = task;
109
+
110
+ // Pi awaits input handlers, so do not return this promise.
111
+ void (async () => {
112
+ try {
113
+ let pin: ModelPin | undefined;
114
+ try {
115
+ pin = readPin(configPath);
116
+ } catch {
117
+ ctx.ui.notify(`Auto-title: cannot read ${configPath}; using the session model`, "warning");
118
+ }
119
+ const sessionModel = ctx.model;
120
+ const models = pin ? [ctx.modelRegistry.find(pin.provider, pin.model)] : [];
121
+ if (!pin || sessionModel?.provider !== pin.provider || sessionModel?.id !== pin.model) {
122
+ models.push(sessionModel);
123
+ }
124
+ for (const [index, model] of models.entries()) {
125
+ if (task.signal.aborted) return;
126
+ const signal = AbortSignal.any([task.signal, AbortSignal.timeout(15_000)]);
127
+ let onAbort: (() => void) | undefined;
128
+ let summary: string;
129
+ // Generation failures can recover with the session model or the temporary title.
130
+ try {
131
+ if (!model) throw new Error("Model unavailable");
132
+ signal.throwIfAborted();
133
+ const response = await Promise.race([
134
+ ctx.modelRegistry.streamSimple(
135
+ model,
136
+ {
137
+ systemPrompt: SUMMARY_PROMPT,
138
+ messages: [{ role: "user", content: [{ type: "text", text: userPrompt }], timestamp: Date.now() }],
139
+ },
140
+ { signal, maxTokens: 64 },
141
+ ).result(),
142
+ new Promise<never>((_, reject) => {
143
+ onAbort = () => reject(signal.reason);
144
+ signal.addEventListener("abort", onAbort, { once: true });
145
+ if (signal.aborted) onAbort();
146
+ }),
147
+ ]);
148
+ signal.throwIfAborted();
149
+ if (response.stopReason !== "stop") throw new Error("Title generation failed");
150
+ summary = response.content
151
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
152
+ .map((c) => c.text)
153
+ .join("")
154
+ .replace(/\s+/g, " ")
155
+ .trim();
156
+ if (!summary) throw new Error("Empty title");
157
+ } catch (error) {
158
+ if (task.signal.aborted) return;
159
+ if (pin && index === 0) {
160
+ ctx.ui.notify(`Auto-title: pinned model ${pin.provider}/${pin.model} failed; ${models.length > 1 && sessionModel ? "trying the session model" : "keeping the temporary title"}`, "warning");
161
+ } else {
162
+ throw error;
163
+ }
164
+ continue;
165
+ } finally {
166
+ if (onAbort) signal.removeEventListener("abort", onAbort);
167
+ }
168
+
169
+ if (pending === task && ctx.sessionManager.getSessionId() === sessionId &&
170
+ pi.getSessionName() === temporaryName) {
171
+ pi.setSessionName(`${prefix}${summary}`.slice(0, 80).trim());
172
+ }
173
+ return;
174
+ }
175
+ } catch (error) {
176
+ // Detached-task boundary: report failures instead of losing rejected promises.
177
+ ctx.ui.notify(`Auto-title failed: ${error instanceof Error ? error.message : String(error)}`, "error");
178
+ } finally {
179
+ if (pending === task) pending = undefined;
180
+ }
181
+ })();
182
+ });
183
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@nimanzik/pi-auto-title",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Automatically name Pi sessions from their first request.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "readme": "README.md",
8
+ "author": {
9
+ "name": "Nima Nooshiri"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/nimanzik/pi-kit.git",
14
+ "directory": "extensions/pi-auto-title"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/nimanzik/pi-kit/issues"
18
+ },
19
+ "homepage": "https://github.com/nimanzik/pi-kit/tree/main/extensions/pi-auto-title#readme",
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "files": ["auto-title.ts", "CHANGELOG.md", "README.md", "LICENSE"],
24
+ "keywords": ["pi-package", "pi-extension"],
25
+ "pi": {
26
+ "extensions": ["./auto-title.ts"]
27
+ },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-coding-agent": "*"
30
+ },
31
+ "scripts": {
32
+ "test": "node --experimental-vm-modules --test auto-title.test.mjs",
33
+ "typecheck": "tsc"
34
+ },
35
+ "devDependencies": {
36
+ "@earendil-works/pi-coding-agent": "^1.5.0",
37
+ "@types/node": "^26.6.6",
38
+ "typescript": "^7.0.2"
39
+ }
40
+ }