pi-next-steps 1.1.0 → 1.1.1

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.
Files changed (2) hide show
  1. package/next-steps.ts +304 -304
  2. package/package.json +1 -1
package/next-steps.ts CHANGED
@@ -1,304 +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
- }
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: type indices (e.g. 1,3) then Enter",
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,6 @@
1
1
  {
2
2
  "name": "pi-next-steps",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Next Steps extension for the Pi coding agent",
5
5
  "type": "module",
6
6
  "main": "next-steps.ts",