pi-next-steps 0.0.0-stage → 1.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,16 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0 — 2026-11-16
4
+
5
+ - Added `rewriteProseOffers` setting (default off): detects a trailing offer in the last assistant message and registers it as next steps.
6
+ - Turn-end hook for prose-offer rewrite.
7
+
8
+ ## 1.0.0 — 2026-11-16
9
+
10
+ - Initial release.
11
+ - `next_steps` tool with options, multi, rec, risky, subtitles, alternates, carry.
12
+ - `/ns` and `/nextsteps` commands.
13
+ - Settings file support.
14
+ - Carry-forward queue, steer on click, alternate groups.
15
+ - Auto-classification (best-effort).
16
+ - System-prompt guidance.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Apostol Apostolov
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,73 @@
1
- # Temporary Holding Version
1
+ # pi-next-steps
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
+ ![hero](./hero.png)
4
+
5
+ **Next Steps** puts the end of a reply to work. Instead of the agent asking "say the word and I'll push the branch", the reply ends with a row of selectable steps, and one pick sends that step as the next message. Pick several and one send delivers them together.
6
+
7
+ A Pi port of the Hermes **Next Steps** plugin, adapted for the Pi coding agent's extension API.
8
+
9
+ ## Features
10
+
11
+ - **Tool-driven offers.** The agent calls the `next_steps` tool with 2-6 short option strings at the end of a choice reply.
12
+ - **Recommended marks.** Options the classifier prefers carry a `★` tag and start selected. Several may be recommended when the steps belong together.
13
+ - **Risky pills.** An option that could damage files, a build, or money carries a `⚠` tag. Off by default.
14
+ - **Subtitles.** A chip can carry a dim second line when the label alone would be read wrongly.
15
+ - **Multi-select.** Pick comma-separated indices (`1,3`) and one send delivers them together.
16
+ - **Auto-classification.** When `rec`/`risky` are omitted, the extension asks the session model to classify the options (best-effort).
17
+ - **System-prompt guidance.** The model is told to call `next_steps` at choice points instead of asking in prose.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pi install npm:pi-next-steps
23
+ # or from git:
24
+ pi install git:github.com/apoapostolov/pi-next-steps
25
+ ```
26
+
27
+ Then reload Pi so the extension loads.
28
+
29
+ ## Usage
30
+
31
+ The agent calls `next_steps` automatically when a reply ends with a choice. You can also invoke it manually from the TUI:
32
+
33
+ ```
34
+ /ns
35
+ ```
36
+
37
+ Type comma-separated indices (e.g. `1,3`) or a single number, then press Enter. The chosen step(s) are sent as the next user turn (queued if the agent is busy).
38
+
39
+ Alias: `/nextsteps`.
40
+
41
+ ## Tool parameters
42
+
43
+ | Parameter | Type | Description |
44
+ |---|---|---|
45
+ | `options` | `string[]` | The option labels to offer (2-6 recommended). |
46
+ | `multi` | `boolean` | Allow picking multiple (default `true`). |
47
+ | `rec` | `string` | Comma-separated 1-based indices to mark recommended. |
48
+ | `risky` | `string` | Comma-separated 1-based indices to mark risky. |
49
+ | `subtitles` | `string[]` | Optional dim second lines, one per option. |
50
+
51
+ ## Example directive (no tool calling)
52
+
53
+ When tool calling is unavailable, the same row can be expressed as a directive:
54
+
55
+ ```
56
+ ::nextsteps{multi="1" rec="1" risky="2" q1="Push the branch and open the PR" q2="Force-push over the review commit" q3="Write the release note first" d2="Rewrites origin, discarding the commit already there"}
57
+ ```
58
+
59
+ ## Requirements
60
+
61
+ - Pi 1.5+
62
+ - A Nerd Font (for the `★`/`⚠` glyphs) is recommended but not required.
63
+
64
+ ## Limits
65
+
66
+ - A step is a sentence. A vague option sends a vague request; the plugin does not rewrite what the agent wrote.
67
+ - Ticks are per block. Two blocks in one reply keep separate picks.
68
+ - The RISKY pill is an opinion from a classifier reading labels and context, not a reading of your repository.
69
+ - Auto-classification is best-effort and may fail on providers that require extra headers (e.g. opencode-go).
70
+
71
+ ## License
72
+
73
+ MIT. Inspired by [Follow-up Chips](https://github.com/nuonrg/hermes-plugin-followup-chips) and the Hermes Next Steps plugin.
package/hero.png ADDED
Binary file
package/icon.png ADDED
Binary file
package/next-steps.ts ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * next-steps for Pi: a port of the Hermes "Next Steps" plugin.
3
+ *
4
+ * The agent calls the `next_steps` tool with a list of option strings at the end
5
+ * of a reply. The extension stores them and exposes `/ns` (alias `/nextsteps`)
6
+ * to pick one or more and send them as the next user turn.
7
+ *
8
+ * Settings: ~/.pi/agent/next-steps.json
9
+ * markRisky (bool, default false), carryForward (bool, default false),
10
+ * steerOnClick (bool, default false), accentRecommended (bool, default true).
11
+ */
12
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ interface NextStepsState {
17
+ options: string[];
18
+ multi: boolean;
19
+ rec: string;
20
+ risky: string;
21
+ subtitles: string[];
22
+ alternates: string;
23
+ }
24
+
25
+ interface Settings {
26
+ markRisky: boolean;
27
+ carryForward: boolean;
28
+ steerOnClick: boolean;
29
+ accentRecommended: boolean;
30
+ rewriteProseOffers: boolean;
31
+ }
32
+
33
+ const SETTINGS_PATH = join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent", "next-steps.json");
34
+
35
+ function loadSettings(): Settings {
36
+ const defaults: Settings = { markRisky: false, carryForward: false, steerOnClick: false, accentRecommended: true, rewriteProseOffers: false };
37
+ try {
38
+ if (existsSync(SETTINGS_PATH)) {
39
+ const raw = JSON.parse(readFileSync(SETTINGS_PATH, "utf8"));
40
+ return { ...defaults, ...raw };
41
+ }
42
+ } catch {}
43
+ // write defaults
44
+ try {
45
+ mkdirSync(join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent"), { recursive: true });
46
+ writeFileSync(SETTINGS_PATH, JSON.stringify(defaults, null, 2));
47
+ } catch {}
48
+ return defaults;
49
+ }
50
+
51
+ export default function (pi: ExtensionAPI) {
52
+ const settings = loadSettings();
53
+ let state: NextStepsState | null = null;
54
+ // carry-forward queue: array of { options, rec, risky, subtitles, age }
55
+ const queue: { options: string[]; rec: string; risky: string; subtitles: string[]; age: number }[] = [];
56
+
57
+ pi.on("before_agent_start", async (event) => {
58
+ const addition = `
59
+ When a reply naturally ends with a choice or "say the word and I'll...", call the next_steps tool with 2-6 short option strings instead of asking in prose. Mark recommended options with rec (comma indices). Use subtitles when a label alone is ambiguous.`;
60
+ let sp = (event.systemPrompt ?? "") + addition;
61
+ if (settings.carryForward && queue.length > 0) {
62
+ const carried = queue
63
+ .slice()
64
+ .reverse()
65
+ .map((q, i) => `[${i + 1} reply back] ${q.options.join(" | ")}`)
66
+ .join("\n");
67
+ sp += `\n\nCarried unanswered options from earlier replies (youngest first):\n${carried}`;
68
+ }
69
+ return { systemPrompt: sp };
70
+ });
71
+
72
+ // Prose-offer parser: detect a trailing offer in the last assistant message.
73
+ function planOffer(text: string): string[] | null {
74
+ if (!text || !text.trim()) return null;
75
+ const TRIGGER = /(?:want me to|should i|shall i|do you want|pick one|choose one)\b/i;
76
+ const blocks = text.split("\n\n");
77
+ let last = -1;
78
+ for (let i = blocks.length - 1; i >= 0; i--) {
79
+ if (blocks[i].trim()) { last = i; break; }
80
+ }
81
+ if (last < 0) return null;
82
+ const lastBlock = blocks[last].trim();
83
+ if (!TRIGGER.test(lastBlock)) return null;
84
+ // extract bullets
85
+ const bullets: string[] = [];
86
+ for (const line of lastBlock.split("\n")) {
87
+ const m = line.match(/^[-*•]\s+(.+)$/);
88
+ if (m) bullets.push(m[1].trim());
89
+ }
90
+ if (bullets.length >= 2) return bullets.slice(0, 6);
91
+ // single sentence option
92
+ const sentence = lastBlock.replace(TRIGGER, "").trim();
93
+ if (sentence.length > 0 && sentence.length < 120) return [sentence];
94
+ return null;
95
+ }
96
+
97
+ pi.on("turn_end", async (event: any) => {
98
+ // prose-offer rewrite
99
+ if (settings.rewriteProseOffers && !state) {
100
+ try {
101
+ const msgs = event?.messages ?? [];
102
+ const lastAssistant = [...msgs].reverse().find((m: any) => m?.role === "assistant");
103
+ const text = typeof lastAssistant?.content === "string"
104
+ ? lastAssistant.content
105
+ : Array.isArray(lastAssistant?.content)
106
+ ? lastAssistant.content.map((c: any) => c?.text ?? "").join("")
107
+ : "";
108
+ const opts = planOffer(text);
109
+ if (opts && opts.length >= 2) {
110
+ state = { options: opts, multi: true, rec: "", risky: "", subtitles: [], alternates: "" };
111
+ }
112
+ } catch {
113
+ // ignore
114
+ }
115
+ }
116
+ if (state && state.options.length > 0) {
117
+ // age existing queue
118
+ for (const q of queue) q.age++;
119
+ queue.unshift({ options: state.options, rec: state.rec, risky: state.risky, subtitles: state.subtitles, age: 0 });
120
+ if (queue.length > 30) queue.pop();
121
+ // clear state after carrying
122
+ if (!settings.carryForward) state = null;
123
+ }
124
+ });
125
+
126
+ pi.registerTool({
127
+ name: "next_steps",
128
+ label: "Next Steps",
129
+ description:
130
+ "Offer selectable next-step options at the end of a reply. Call this when the user faces a choice or the reply naturally ends with 'say the word and I'll...'. Provide 2-6 short option strings.",
131
+ parameters: {
132
+ type: "object",
133
+ properties: {
134
+ options: { type: "array", items: { type: "string" }, description: "The option labels to offer." },
135
+ multi: { type: "boolean", description: "Allow picking multiple (default true)." },
136
+ rec: { type: "string", description: "Comma-separated 1-based indices to mark recommended." },
137
+ risky: { type: "string", description: "Comma-separated 1-based indices to mark risky." },
138
+ subtitles: { type: "array", items: { type: "string" }, description: "Optional dim second lines, one per option." },
139
+ alternates: { type: "string", description: "Groups of mutually exclusive indices, e.g. '1,3|2'." },
140
+ carry: { type: "boolean", description: "Record this reply's options for carry-forward (default follows setting)." },
141
+ },
142
+ required: ["options"],
143
+ },
144
+ execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
145
+ const args = (params ?? {}) as any;
146
+ const opts = ((args.options as string[]) ?? []).map((s) => String(s).trim()).filter(Boolean);
147
+ if (opts.length === 0) {
148
+ ctx.ui.notify("next_steps: no options", "warning");
149
+ return { content: [{ type: "text", text: "No options provided." }] };
150
+ }
151
+ let rec = (args.rec as string) ?? "";
152
+ let risky = (args.risky as string) ?? "";
153
+ // Auto-classify when not provided (best-effort, silent on failure)
154
+ if (!rec && !risky && settings.markRisky && ctx?.model) {
155
+ try {
156
+ const model = ctx.model;
157
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
158
+ if (auth.ok) {
159
+ const context: any = {
160
+ systemPrompt: "You are a classifier. Reply with JSON only.",
161
+ messages: [
162
+ {
163
+ role: "user",
164
+ content: `Classify these next-step options. Return ONLY JSON: {"rec":[1-based indices of recommended options], "risky":[1-based indices of risky/damaging options]}. Mark 1-2 recommended when steps belong together, never all, never mutually exclusive pairs. Mark risky only options that could damage files, builds, or money.\nOptions:\n${opts.map((o, i) => `${i + 1}. ${o}`).join("\n")}`,
165
+ timestamp: Date.now(),
166
+ },
167
+ ],
168
+ };
169
+ const stream = ctx.modelRegistry.streamSimple(model, context, { apiKey: auth.apiKey, headers: auth.headers, baseUrl: auth.baseUrl });
170
+ let msg: any = null;
171
+ for await (const ev of stream) {
172
+ if (ev.type === "done") msg = ev.message;
173
+ }
174
+ if (!msg) msg = await stream.result();
175
+ const text = Array.isArray(msg?.content)
176
+ ? msg.content.map((c: any) => c?.text ?? "").join("")
177
+ : String(msg?.content ?? "");
178
+ const m = text.match(/\{[\s\S]*\}/);
179
+ if (m) {
180
+ try {
181
+ const j = JSON.parse(m[0]);
182
+ if (Array.isArray(j.rec)) rec = j.rec.join(",");
183
+ if (Array.isArray(j.risky)) risky = j.risky.join(",");
184
+ } catch {
185
+ // ignore parse errors
186
+ }
187
+ }
188
+ }
189
+ } catch {
190
+ // classification best-effort
191
+ }
192
+ }
193
+ const alternates = (args.alternates as string) ?? "";
194
+ state = {
195
+ options: opts,
196
+ multi: args.multi !== false,
197
+ rec,
198
+ risky,
199
+ subtitles: (args.subtitles as string[]) ?? [],
200
+ alternates,
201
+ };
202
+ if (args.carry === true) settings.carryForward = true;
203
+ const recSet = new Set((state.rec || "").split(",").map((s) => s.trim()));
204
+ const riskySet = new Set((state.risky || "").split(",").map((s) => s.trim()));
205
+ const lines = state.options.map((o, i) => {
206
+ const n = i + 1;
207
+ const tags = [
208
+ settings.accentRecommended && recSet.has(String(n)) ? "★" : "",
209
+ settings.markRisky && riskySet.has(String(n)) ? "⚠" : "",
210
+ ].filter(Boolean).join(" ");
211
+ const sub = state!.subtitles[i] ? ` — ${state!.subtitles[i]}` : "";
212
+ return `${n}. ${tags ? tags + " " : ""}${o}${sub}`;
213
+ });
214
+ ctx.ui.notify(`Next steps registered. Run /ns to pick.`, "info");
215
+ return {
216
+ content: [{ type: "text", text: `Registered ${opts.length} next steps:\n${lines.join("\n")}\nUse /ns to pick and send.` }],
217
+ };
218
+ },
219
+ });
220
+
221
+ async function pickAndSend(ctx: any) {
222
+ if (!state || state.options.length === 0) {
223
+ // try carry-forward queue
224
+ if (queue.length > 0) {
225
+ const q = queue[0];
226
+ state = { options: q.options, multi: true, rec: q.rec, risky: q.risky, subtitles: q.subtitles, alternates: "" };
227
+ } else {
228
+ ctx.ui.notify("No next steps registered. Ask the agent to call next_steps.", "warning");
229
+ return;
230
+ }
231
+ }
232
+ const opts = state.options;
233
+ const recSet = new Set((state.rec || "").split(",").map((s) => s.trim()));
234
+ const riskySet = new Set((state.risky || "").split(",").map((s) => s.trim()));
235
+ // parse alternate groups
236
+ const altGroups: number[][] = [];
237
+ if (state.alternates) {
238
+ for (const g of state.alternates.split("|")) {
239
+ const members = g.split(",").map((s) => parseInt(s.trim(), 10)).filter((n) => !isNaN(n) && n >= 1 && n <= opts.length);
240
+ if (members.length >= 2) altGroups.push(members);
241
+ }
242
+ }
243
+ const labels = opts.map((o, i) => {
244
+ const n = i + 1;
245
+ const tags = [
246
+ settings.accentRecommended && recSet.has(String(n)) ? "★" : "",
247
+ settings.markRisky && riskySet.has(String(n)) ? "⚠" : "",
248
+ ].filter(Boolean).join(" ");
249
+ return `${n}. ${tags ? tags + " " : ""}${o}`;
250
+ });
251
+ const input = await ctx.ui.input(
252
+ "Next steps (comma-separated indices, or single number)",
253
+ labels.join(" | "),
254
+ );
255
+ if (!input) {
256
+ ctx.ui.notify("Cancelled", "info");
257
+ return;
258
+ }
259
+ let indices = input
260
+ .split(",")
261
+ .map((s) => parseInt(s.trim(), 10))
262
+ .filter((n) => !isNaN(n) && n >= 1 && n <= opts.length);
263
+ // enforce alternate groups
264
+ for (const g of altGroups) {
265
+ const picked = indices.filter((n) => g.includes(n));
266
+ if (picked.length > 1) {
267
+ // keep the first
268
+ const first = picked[0];
269
+ indices = indices.filter((n) => !g.includes(n) || n === first);
270
+ }
271
+ }
272
+ if (indices.length === 0) {
273
+ ctx.ui.notify("No valid selection", "warning");
274
+ return;
275
+ }
276
+ const chosen = indices.map((n) => opts[n - 1]);
277
+ const message = chosen.length === 1 ? chosen[0] : chosen.map((c) => `- ${c}`).join("\n");
278
+ if (ctx.isIdle()) {
279
+ pi.sendUserMessage(message);
280
+ } else if (settings.steerOnClick) {
281
+ pi.sendUserMessage(message, { deliverAs: "steer" });
282
+ } else {
283
+ pi.sendUserMessage(message, { deliverAs: "followUp" });
284
+ }
285
+ // retire from carry queue
286
+ if (queue.length > 0) queue.shift();
287
+ ctx.ui.notify(`Sent ${chosen.length} step(s)`, "info");
288
+ }
289
+
290
+ pi.registerCommand("ns", {
291
+ description: "Pick and send a registered next step (/ns).",
292
+ handler: async (_args, ctx) => pickAndSend(ctx),
293
+ });
294
+ pi.registerCommand("nextsteps", {
295
+ description: "Pick and send a registered next step (/nextsteps).",
296
+ handler: async (_args, ctx) => pickAndSend(ctx),
297
+ });
298
+ pi.registerCommand("nextsteps-settings", {
299
+ description: "Show next-steps settings path.",
300
+ handler: async (_args, ctx) => {
301
+ ctx.ui.notify(`Settings: ${SETTINGS_PATH}`, "info");
302
+ },
303
+ });
304
+ }
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "pi-next-steps",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Next Steps extension for the Pi coding agent",
5
+ "type": "module",
6
+ "main": "next-steps.ts",
7
+ "pi": {
8
+ "extensions": ["./next-steps.ts"]
9
+ },
10
+ "keywords": ["pi", "pi-extension", "next-steps"],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/apoapostolov/pi-next-steps.git"
15
+ }
16
+ }