pi-next-steps 1.1.6 → 1.2.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 CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 - 2026-11-18
4
+
5
+ - `/ns` can delete stale carried steps without leaving the picker. Ctrl+D on a stale row arms it in red, and a second Ctrl+D deletes it. Shift+Ctrl+D arms every stale row in red, and a second Shift+Ctrl+D deletes all of them. The current reply's rows stay untouched.
6
+
3
7
  ## 1.1.6 - 2026-11-18
4
8
 
5
9
  - Multiple blocks per reply: every `next_steps` call keeps its own options, so
@@ -16,4 +20,4 @@ never carried afterwards, and untouched siblings survive.
16
20
  - `/ns clear X` drops the steps collected in the last X posts.
17
21
  - Every selection travels as one user message.
18
22
 
19
- ## 1.1.5 - 2026-11-16
23
+ ## 1.1.5 - 2026-11-16
package/README.md CHANGED
@@ -36,6 +36,8 @@ The agent calls `next_steps` automatically when a reply ends with a choice. You
36
36
 
37
37
  A tabbed picker opens with one tab per collected reply, newest first. Space toggles a label, arrows move and switch tab, Enter sends. Every chosen step travels as one user message, so a pick that spans several tabs still costs one turn. Carried labels show how many offering replies back they came from.
38
38
 
39
+ Stale carried steps can be pruned from the picker. On an older tab, Ctrl+D turns the focused row red, then Ctrl+D again deletes it. Shift+Ctrl+D turns every stale row red, and a second Shift+Ctrl+D deletes all of them. The current reply's rows cannot be deleted this way. `/ns clear` remains the coarse option when you want whole older replies gone at once.
40
+
39
41
  Clear what you no longer want:
40
42
 
41
43
  ```
package/next-steps.ts CHANGED
@@ -1,502 +1,583 @@
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 { matchesKey } from "@earendil-works/pi-tui";
14
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
15
- import { join } from "node:path";
16
-
17
- interface NextStepsState {
18
- options: string[];
19
- multi: boolean;
20
- rec: string;
21
- risky: string;
22
- subtitles: string[];
23
- alternates: string;
24
- }
25
-
26
- interface Settings {
27
- markRisky: boolean;
28
- carryForward: boolean;
29
- steerOnClick: boolean;
30
- accentRecommended: boolean;
31
- rewriteProseOffers: boolean;
32
- }
33
-
34
- const SETTINGS_PATH = join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent", "next-steps.json");
35
-
36
- function loadSettings(): Settings {
37
- const defaults: Settings = { markRisky: false, carryForward: false, steerOnClick: false, accentRecommended: true, rewriteProseOffers: false };
38
- try {
39
- if (existsSync(SETTINGS_PATH)) {
40
- const raw = JSON.parse(readFileSync(SETTINGS_PATH, "utf8"));
41
- return { ...defaults, ...raw };
42
- }
43
- } catch {}
44
- // write defaults
45
- try {
46
- mkdirSync(join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent"), { recursive: true });
47
- writeFileSync(SETTINGS_PATH, JSON.stringify(defaults, null, 2));
48
- } catch {}
49
- return defaults;
50
- }
51
-
52
- export default function (pi: ExtensionAPI) {
53
- const settings = loadSettings();
54
- let states: NextStepsState[] = [];
55
- // carry-forward queue: array of { options, rec, risky, subtitles, age, reply }, newest first
56
- const queue: { options: string[]; rec: string; risky: string; subtitles: string[]; age: number; reply: number }[] = [];
57
- // Counts replies that offered steps, so `/ns clear X` can target the last X posts.
58
- let replyCounter = 0;
59
- const keyOf = (options: string[]) => options.join("\u0000");
60
- // Labels answered during their own turn; only what is left gets carried.
61
- const pickedThisTurn = new Set<string>();
62
-
63
- // Drop answered labels from a block and remap its tags so the indexes still line up.
64
- function withoutPicked(st: NextStepsState) {
65
- const keep: number[] = [];
66
- st.options.forEach((o, i) => {
67
- if (!pickedThisTurn.has(o)) keep.push(i);
68
- });
69
- const remap = (list: string) =>
70
- list
71
- .split(",")
72
- .map((s) => parseInt(s.trim(), 10))
73
- .filter((n) => !isNaN(n))
74
- .map((n) => keep.indexOf(n - 1) + 1)
75
- .filter((n) => n > 0)
76
- .join(",");
77
- return {
78
- options: keep.map((i) => st.options[i]),
79
- rec: remap(st.rec),
80
- risky: remap(st.risky),
81
- subtitles: keep.map((i) => st.subtitles[i] ?? ""),
82
- };
83
- }
84
-
85
- // Remove picked labels from every carried block; a block with nothing left is dropped.
86
- function retirePicked(picked: string[]) {
87
- const set = new Set(picked);
88
- for (let i = queue.length - 1; i >= 0; i--) {
89
- const rest = queue[i].options.filter((o) => !set.has(o));
90
- if (rest.length === 0) queue.splice(i, 1);
91
- else queue[i] = { ...queue[i], options: rest };
92
- }
93
- }
94
-
95
- pi.on("before_agent_start", async (event) => {
96
- const addition = `
97
- 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.`;
98
- let sp = (event.systemPrompt ?? "") + addition;
99
- if (settings.carryForward && queue.length > 0) {
100
- const carried = queue
101
- .map((q) => `[${q.age === 1 ? "1 reply" : `${q.age} replies`} back] ${q.options.join(" | ")}`)
102
- .join("\n");
103
- sp += `\n\nCarried unanswered options from earlier replies (youngest first):\n${carried}`;
104
- }
105
- return { systemPrompt: sp };
106
- });
107
-
108
- // Prose-offer parser: detect a trailing offer in the last assistant message.
109
- function planOffer(text: string): string[] | null {
110
- if (!text || !text.trim()) return null;
111
- const TRIGGER = /(?:want me to|should i|shall i|do you want|pick one|choose one)\b/i;
112
- const blocks = text.split("\n\n");
113
- let last = -1;
114
- for (let i = blocks.length - 1; i >= 0; i--) {
115
- if (blocks[i].trim()) { last = i; break; }
116
- }
117
- if (last < 0) return null;
118
- const lastBlock = blocks[last].trim();
119
- if (!TRIGGER.test(lastBlock)) return null;
120
- // extract bullets
121
- const bullets: string[] = [];
122
- for (const line of lastBlock.split("\n")) {
123
- const m = line.match(/^[-*•]\s+(.+)$/);
124
- if (m) bullets.push(m[1].trim());
125
- }
126
- if (bullets.length >= 2) return bullets.slice(0, 6);
127
- // single sentence option
128
- const sentence = lastBlock.replace(TRIGGER, "").trim();
129
- if (sentence.length > 0 && sentence.length < 120) return [sentence];
130
- return null;
131
- }
132
-
133
- pi.on("turn_end", async (event: any) => {
134
- // prose-offer rewrite
135
- if (settings.rewriteProseOffers && states.length === 0) {
136
- try {
137
- const msgs = event?.messages ?? [];
138
- const lastAssistant = [...msgs].reverse().find((m: any) => m?.role === "assistant");
139
- let text = "";
140
- if (typeof lastAssistant?.content === "string") {
141
- text = lastAssistant.content;
142
- } else if (Array.isArray(lastAssistant?.content)) {
143
- text = lastAssistant.content.map((c: any) => c?.text ?? "").join("");
144
- }
145
- const opts = planOffer(text);
146
- if (opts && opts.length >= 2) {
147
- states.push({ options: opts, multi: true, rec: "", risky: "", subtitles: [], alternates: "" });
148
- }
149
- } catch {
150
- // ignore
151
- }
152
- }
153
- if (states.length > 0) {
154
- // age existing queue
155
- for (const q of queue) q.age++;
156
- replyCounter++;
157
- for (const st of states) {
158
- const rest = withoutPicked(st);
159
- if (rest.options.length === 0) continue;
160
- const key = keyOf(rest.options);
161
- if (queue.some((q) => q.age === 0 && keyOf(q.options) === key)) continue;
162
- queue.unshift({ ...rest, age: 0, reply: replyCounter });
163
- }
164
- while (queue.length > 30) queue.pop();
165
- // States are per reply; the queue is the only place a block survives.
166
- states = [];
167
- pickedThisTurn.clear();
168
- }
169
- });
170
-
171
- pi.registerTool({
172
- name: "next_steps",
173
- label: "Next Steps",
174
- description:
175
- "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.",
176
- parameters: {
177
- type: "object",
178
- properties: {
179
- options: { type: "array", items: { type: "string" }, description: "The option labels to offer." },
180
- multi: { type: "boolean", description: "Allow picking multiple (default true)." },
181
- rec: { type: "string", description: "Comma-separated 1-based indices to mark recommended." },
182
- risky: { type: "string", description: "Comma-separated 1-based indices to mark risky." },
183
- subtitles: { type: "array", items: { type: "string" }, description: "Optional dim second lines, one per option." },
184
- alternates: { type: "string", description: "Groups of mutually exclusive indices, e.g. '1,3|2'." },
185
- carry: { type: "boolean", description: "Record this reply's options for carry-forward (default follows setting)." },
186
- },
187
- required: ["options"],
188
- },
189
- execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
190
- const args = (params ?? {}) as any;
191
- const opts = ((args.options as string[]) ?? []).map((s) => String(s).trim()).filter(Boolean);
192
- if (opts.length === 0) {
193
- ctx.ui.notify("next_steps: no options", "warning");
194
- return { content: [{ type: "text", text: "No options provided." }] };
195
- }
196
- let rec = (args.rec as string) ?? "";
197
- let risky = (args.risky as string) ?? "";
198
- // Auto-classify when not provided (best-effort, silent on failure)
199
- if (!rec && !risky && settings.markRisky && ctx?.model) {
200
- try {
201
- const model = ctx.model;
202
- const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
203
- if (auth.ok) {
204
- const context: any = {
205
- systemPrompt: "You are a classifier. Reply with JSON only.",
206
- messages: [
207
- {
208
- role: "user",
209
- 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")}`,
210
- timestamp: Date.now(),
211
- },
212
- ],
213
- };
214
- const stream = ctx.modelRegistry.streamSimple(model, context, { apiKey: auth.apiKey, headers: auth.headers, baseUrl: auth.baseUrl });
215
- let msg: any = null;
216
- for await (const ev of stream) {
217
- if (ev.type === "done") msg = ev.message;
218
- }
219
- if (!msg) msg = await stream.result();
220
- const text = Array.isArray(msg?.content)
221
- ? msg.content.map((c: any) => c?.text ?? "").join("")
222
- : String(msg?.content ?? "");
223
- const m = text.match(/\{[\s\S]*\}/);
224
- if (m) {
225
- try {
226
- const j = JSON.parse(m[0]);
227
- if (Array.isArray(j.rec)) rec = j.rec.join(",");
228
- if (Array.isArray(j.risky)) risky = j.risky.join(",");
229
- } catch {
230
- // ignore parse errors
231
- }
232
- }
233
- }
234
- } catch {
235
- // classification best-effort
236
- }
237
- }
238
- const alternates = (args.alternates as string) ?? "";
239
- const newState: NextStepsState = {
240
- options: opts,
241
- multi: args.multi !== false,
242
- rec,
243
- risky,
244
- subtitles: (args.subtitles as string[]) ?? [],
245
- alternates,
246
- };
247
- states.push(newState);
248
- if (args.carry === true) settings.carryForward = true;
249
- const recSet = new Set((states[0].rec || "").split(",").map((s) => s.trim()));
250
- const riskySet = new Set((states[0].risky || "").split(",").map((s) => s.trim()));
251
- const lines = newState.options.map((o, i) => {
252
- const n = i + 1;
253
- const tags = [
254
- settings.accentRecommended && recSet.has(String(n)) ? "★" : "",
255
- settings.markRisky && riskySet.has(String(n)) ? "▲" : "",
256
- ].filter(Boolean).join(" ");
257
- const sub = newState.subtitles[i] ? ` — ${newState.subtitles[i]}` : "";
258
- const tagPrefix = tags ? `${tags} ` : "";
259
- return `${n}. ${tagPrefix}${o}${sub}`;
260
- });
261
- // Render an interactive choice right away instead of forcing /ns.
262
- const choiceLabels = newState.options.map((o, i) => {
263
- const n = i + 1;
264
- const recTag = settings.accentRecommended && recSet.has(String(n)) ? " ★ RECOMMENDED" : "";
265
- const riskyTag = settings.markRisky && riskySet.has(String(n)) ? " ▲ RISKY" : "";
266
- const sub = newState.subtitles[i] ? ` — ${newState.subtitles[i]}` : "";
267
- return `${o}${sub}${recTag}${riskyTag}`;
268
- });
269
- try {
270
- const selected = new Set<number>();
271
- const result = await ctx.ui.custom<number[] | null>((tui, theme, _kb, done) => {
272
- let cursor = 0;
273
- const component = {
274
- focused: true,
275
- render(_width: number): string[] {
276
- const lines: string[] = [];
277
- lines.push(theme.fg("accent", "Next steps (space toggle, enter confirm):"));
278
- for (let i = 0; i < choiceLabels.length; i++) {
279
- const check = selected.has(i) ? "[x]" : "[ ]";
280
- const prefix = i === cursor ? theme.fg("accent", "> ") : " ";
281
- lines.push(`${prefix}${check} ${choiceLabels[i]}`);
282
- }
283
- lines.push(theme.fg("dim", "space toggle · ↑↓ move · enter/tab confirm · esc cancel"));
284
- return lines;
285
- },
286
- invalidate() {},
287
- handleInput(data: string) {
288
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
289
- cursor = (cursor - 1 + choiceLabels.length) % choiceLabels.length;
290
- tui.requestRender();
291
- } else if (matchesKey(data, "down") || matchesKey(data, "j")) {
292
- cursor = (cursor + 1) % choiceLabels.length;
293
- tui.requestRender();
294
- } else if (matchesKey(data, "space")) {
295
- if (selected.has(cursor)) selected.delete(cursor);
296
- else selected.add(cursor);
297
- tui.requestRender();
298
- } else if (matchesKey(data, "enter") || matchesKey(data, "tab")) {
299
- done(Array.from(selected).sort((a, b) => a - b));
300
- } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
301
- done(null);
302
- }
303
- },
304
- };
305
- return component;
306
- });
307
- if (result && result.length > 0) {
308
- const chosen = result.map((n) => newState.options[n]);
309
- const message = chosen.length === 1 ? chosen[0] : chosen.map((c) => `- ${c}`).join("\n");
310
- if (ctx.isIdle()) {
311
- pi.sendUserMessage(message);
312
- } else if (settings.steerOnClick) {
313
- pi.sendUserMessage(message, { deliverAs: "steer" });
314
- } else {
315
- pi.sendUserMessage(message, { deliverAs: "followUp" });
316
- }
317
- for (const c of chosen) pickedThisTurn.add(c);
318
- retirePicked(chosen);
319
- ctx.ui.notify(`Sent ${chosen.length} step(s)`, "info");
320
- } else if (result !== null) {
321
- // empty selection (enter with nothing toggled) — send nothing
322
- ctx.ui.notify("No selection", "info");
323
- }
324
- } catch {
325
- // Non-interactive mode or UI unavailable; fall back to /ns.
326
- }
327
- ctx.ui.notify(`Next steps registered.`, "info");
328
- return {
329
- content: [{ type: "text", text: `Registered ${opts.length} next steps:\n${lines.join("\n")}` }],
330
- };
331
- },
332
- });
333
-
334
- async function pickAndSend(ctx: any) {
335
- if (queue.length === 0) {
336
- ctx.ui.notify("No next steps registered. Ask the agent to call next_steps.", "warning");
337
- return;
338
- }
339
- // One tab per collected block, newest first. Carried blocks keep their real age.
340
- const blocks = queue.map((q) => {
341
- const recSet = new Set((q.rec || "").split(",").map((s) => s.trim()));
342
- const riskySet = new Set((q.risky || "").split(",").map((s) => s.trim()));
343
- return {
344
- age: q.age,
345
- items: q.options.map((o, i) => {
346
- const tags = [
347
- settings.accentRecommended && recSet.has(String(i + 1)) ? "★" : "",
348
- settings.markRisky && riskySet.has(String(i + 1)) ? "▲" : "",
349
- ].filter(Boolean).join(" ");
350
- return { option: o, text: `${tags ? tags + " " : ""}${o}` };
351
- }),
352
- };
353
- });
354
- const tabLabel = (i: number) =>
355
- i === 0 ? "this reply" : blocks[i].age === 1 ? "1 reply back" : `${blocks[i].age} replies back`;
356
- let chosen: string[] | null = null;
357
- try {
358
- chosen = await ctx.ui.custom<string[] | null>((tui, theme, _kb, done) => {
359
- let tab = 0;
360
- let cursor = 0;
361
- const picked = new Set<string>();
362
- const component = {
363
- focused: true,
364
- render(_width: number): string[] {
365
- const out: string[] = [];
366
- const head = blocks
367
- .map((_, i) =>
368
- i === tab ? theme.fg("accent", `[${tabLabel(i)}]`) : theme.fg("dim", ` ${tabLabel(i)} `),
369
- )
370
- .join(" · ");
371
- out.push(`${theme.fg("accent", "Next steps")} ${head}`);
372
- blocks[tab].items.forEach((item, i) => {
373
- const mark = picked.has(`${tab}:${i}`) ? "[x]" : "[ ]";
374
- const prefix = i === cursor ? theme.fg("accent", "> ") : " ";
375
- out.push(`${prefix}${mark} ${item.text}`);
376
- });
377
- out.push(theme.fg("dim", "space toggle · ↑↓ move · ←→ block · enter/tab confirm · esc cancel"));
378
- return out;
379
- },
380
- invalidate() {},
381
- handleInput(data: string) {
382
- const n = blocks[tab].items.length;
383
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
384
- cursor = (cursor - 1 + n) % n;
385
- } else if (matchesKey(data, "down") || matchesKey(data, "j")) {
386
- cursor = (cursor + 1) % n;
387
- } else if (matchesKey(data, "left") || matchesKey(data, "h")) {
388
- tab = (tab - 1 + blocks.length) % blocks.length;
389
- cursor = 0;
390
- } else if (matchesKey(data, "right") || matchesKey(data, "l")) {
391
- tab = (tab + 1) % blocks.length;
392
- cursor = 0;
393
- } else if (matchesKey(data, "space")) {
394
- const k = `${tab}:${cursor}`;
395
- if (picked.has(k)) picked.delete(k);
396
- else picked.add(k);
397
- } else if (matchesKey(data, "enter") || matchesKey(data, "tab")) {
398
- done(
399
- Array.from(picked).map((k) => {
400
- const [b, i] = k.split(":").map(Number);
401
- return blocks[b].items[i].option;
402
- }),
403
- );
404
- return;
405
- } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
406
- done(null);
407
- return;
408
- }
409
- tui.requestRender();
410
- },
411
- };
412
- return component;
413
- });
414
- } catch {
415
- ctx.ui.notify("Selection UI unavailable in this session.", "warning");
416
- return;
417
- }
418
- if (!chosen || chosen.length === 0) {
419
- ctx.ui.notify("No selection", "info");
420
- return;
421
- }
422
- // Every picked step travels as one user message, never one message per step.
423
- const message = chosen.length === 1 ? chosen[0] : chosen.map((c) => `- ${c}`).join("\n");
424
- if (ctx.isIdle()) {
425
- pi.sendUserMessage(message);
426
- } else if (settings.steerOnClick) {
427
- pi.sendUserMessage(message, { deliverAs: "steer" });
428
- } else {
429
- pi.sendUserMessage(message, { deliverAs: "followUp" });
430
- }
431
- retirePicked(chosen);
432
- ctx.ui.notify(`Sent ${chosen.length} step(s)`, "info");
433
- }
434
-
435
- // `/ns clear` drops everything older than the newest reply; `/ns clear X` drops the last X posts.
436
- async function clearSteps(arg: string, ctx: any) {
437
- const trimmed = arg.trim();
438
- if (queue.length === 0) {
439
- ctx.ui.notify("No collected next steps to clear.", "info");
440
- return;
441
- }
442
- if (/^clear$/i.test(trimmed)) {
443
- const before = queue.length;
444
- const newest = queue[0].reply;
445
- for (let i = queue.length - 1; i >= 0; i--) {
446
- if (queue[i].reply < newest) queue.splice(i, 1);
447
- }
448
- const dropped = before - queue.length;
449
- ctx.ui.notify(
450
- dropped > 0
451
- ? `Cleared ${dropped} stale step(s). Kept the newest reply.`
452
- : "Nothing stale to clear. Use /ns clear X for the last X posts.",
453
- "info",
454
- );
455
- return;
456
- }
457
- const m = trimmed.match(/^clear\s+(\d+)$/i);
458
- if (m) {
459
- const n = parseInt(m[1], 10);
460
- if (n < 1) {
461
- ctx.ui.notify("Usage: /ns clear [X]", "warning");
462
- return;
463
- }
464
- const cutoff = replyCounter - n + 1;
465
- const before = queue.length;
466
- for (let i = queue.length - 1; i >= 0; i--) {
467
- if (queue[i].reply >= cutoff) queue.splice(i, 1);
468
- }
469
- const dropped = before - queue.length;
470
- ctx.ui.notify(
471
- dropped > 0
472
- ? `Cleared ${dropped} step(s) from the last ${n} post(s).`
473
- : `No collected steps in the last ${n} post(s).`,
474
- "info",
475
- );
476
- return;
477
- }
478
- ctx.ui.notify("Usage: /ns clear (stale) or /ns clear X (last X posts)", "warning");
479
- }
480
-
481
- const runOrClear = async (args: string, ctx: any) => {
482
- const a = (args ?? "").trim();
483
- if (!a) return pickAndSend(ctx);
484
- if (/^clear\b/i.test(a) || /^clear$/i.test(a)) return clearSteps(a, ctx);
485
- ctx.ui.notify("Usage: /ns or /ns clear [X]", "warning");
486
- };
487
-
488
- pi.registerCommand("ns", {
489
- description: "Pick and send a registered next step, or /ns clear [X] to drop collected steps.",
490
- handler: async (args, ctx) => runOrClear(args, ctx),
491
- });
492
- pi.registerCommand("nextsteps", {
493
- description: "Pick and send a registered next step, or /nextsteps clear [X] to drop collected steps.",
494
- handler: async (args, ctx) => runOrClear(args, ctx),
495
- });
496
- pi.registerCommand("nextsteps-settings", {
497
- description: "Show next-steps settings path.",
498
- handler: async (_args, ctx) => {
499
- ctx.ui.notify(`Settings: ${SETTINGS_PATH}`, "info");
500
- },
501
- });
502
- }
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 { matchesKey } from "@earendil-works/pi-tui";
14
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
15
+ import { join } from "node:path";
16
+
17
+ interface NextStepsState {
18
+ options: string[];
19
+ multi: boolean;
20
+ rec: string;
21
+ risky: string;
22
+ subtitles: string[];
23
+ alternates: string;
24
+ }
25
+
26
+ interface QueueEntry {
27
+ options: string[];
28
+ rec: string;
29
+ risky: string;
30
+ subtitles: string[];
31
+ age: number;
32
+ reply: number;
33
+ }
34
+
35
+ interface Settings {
36
+ markRisky: boolean;
37
+ carryForward: boolean;
38
+ steerOnClick: boolean;
39
+ accentRecommended: boolean;
40
+ rewriteProseOffers: boolean;
41
+ }
42
+
43
+ const SETTINGS_PATH = join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent", "next-steps.json");
44
+
45
+ function loadSettings(): Settings {
46
+ const defaults: Settings = { markRisky: false, carryForward: false, steerOnClick: false, accentRecommended: true, rewriteProseOffers: false };
47
+ try {
48
+ if (existsSync(SETTINGS_PATH)) {
49
+ const raw = JSON.parse(readFileSync(SETTINGS_PATH, "utf8"));
50
+ return { ...defaults, ...raw };
51
+ }
52
+ } catch {}
53
+ // write defaults
54
+ try {
55
+ mkdirSync(join(process.env.HOME || process.env.USERPROFILE || ".", ".pi", "agent"), { recursive: true });
56
+ writeFileSync(SETTINGS_PATH, JSON.stringify(defaults, null, 2));
57
+ } catch {}
58
+ return defaults;
59
+ }
60
+
61
+ export default function (pi: ExtensionAPI) {
62
+ const settings = loadSettings();
63
+ let states: NextStepsState[] = [];
64
+ // carry-forward queue, newest first
65
+ const queue: QueueEntry[] = [];
66
+ // Counts replies that offered steps, so `/ns clear X` can target the last X posts.
67
+ let replyCounter = 0;
68
+ const keyOf = (options: string[]) => options.join("\u0000");
69
+ // Labels answered during their own turn; only what is left gets carried.
70
+ const pickedThisTurn = new Set<string>();
71
+
72
+ // Drop answered labels from a block and remap its tags so the indexes still line up.
73
+ function withoutPicked(st: NextStepsState) {
74
+ const keep: number[] = [];
75
+ st.options.forEach((o, i) => {
76
+ if (!pickedThisTurn.has(o)) keep.push(i);
77
+ });
78
+ const remap = (list: string) =>
79
+ list
80
+ .split(",")
81
+ .map((s) => parseInt(s.trim(), 10))
82
+ .filter((n) => !isNaN(n))
83
+ .map((n) => keep.indexOf(n - 1) + 1)
84
+ .filter((n) => n > 0)
85
+ .join(",");
86
+ return {
87
+ options: keep.map((i) => st.options[i]),
88
+ rec: remap(st.rec),
89
+ risky: remap(st.risky),
90
+ subtitles: keep.map((i) => st.subtitles[i] ?? ""),
91
+ };
92
+ }
93
+
94
+ // Remove one carried option and keep its recommendation, risk and subtitle indexes aligned.
95
+ function dropOption(q: QueueEntry, index: number) {
96
+ q.options.splice(index, 1);
97
+ q.subtitles.splice(index, 1);
98
+ const remap = (list: string) =>
99
+ list
100
+ .split(",")
101
+ .map((s) => parseInt(s.trim(), 10))
102
+ .filter((n) => !isNaN(n) && n !== index + 1)
103
+ .map((n) => (n > index + 1 ? n - 1 : n))
104
+ .join(",");
105
+ q.rec = remap(q.rec);
106
+ q.risky = remap(q.risky);
107
+ }
108
+
109
+ // Remove picked labels from every carried block; a block with nothing left is dropped.
110
+ function retirePicked(picked: string[]) {
111
+ const set = new Set(picked);
112
+ for (let i = queue.length - 1; i >= 0; i--) {
113
+ const rest = queue[i].options.filter((o) => !set.has(o));
114
+ if (rest.length === 0) queue.splice(i, 1);
115
+ else queue[i] = { ...queue[i], options: rest };
116
+ }
117
+ }
118
+
119
+ pi.on("before_agent_start", async (event) => {
120
+ const addition = `
121
+ 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.`;
122
+ let sp = (event.systemPrompt ?? "") + addition;
123
+ if (settings.carryForward && queue.length > 0) {
124
+ const carried = queue
125
+ .map((q) => `[${q.age === 1 ? "1 reply" : `${q.age} replies`} back] ${q.options.join(" | ")}`)
126
+ .join("\n");
127
+ sp += `\n\nCarried unanswered options from earlier replies (youngest first):\n${carried}`;
128
+ }
129
+ return { systemPrompt: sp };
130
+ });
131
+
132
+ // Prose-offer parser: detect a trailing offer in the last assistant message.
133
+ function planOffer(text: string): string[] | null {
134
+ if (!text || !text.trim()) return null;
135
+ const TRIGGER = /(?:want me to|should i|shall i|do you want|pick one|choose one)\b/i;
136
+ const blocks = text.split("\n\n");
137
+ let last = -1;
138
+ for (let i = blocks.length - 1; i >= 0; i--) {
139
+ if (blocks[i].trim()) { last = i; break; }
140
+ }
141
+ if (last < 0) return null;
142
+ const lastBlock = blocks[last].trim();
143
+ if (!TRIGGER.test(lastBlock)) return null;
144
+ // extract bullets
145
+ const bullets: string[] = [];
146
+ for (const line of lastBlock.split("\n")) {
147
+ const m = line.match(/^[-*•]\s+(.+)$/);
148
+ if (m) bullets.push(m[1].trim());
149
+ }
150
+ if (bullets.length >= 2) return bullets.slice(0, 6);
151
+ // single sentence option
152
+ const sentence = lastBlock.replace(TRIGGER, "").trim();
153
+ if (sentence.length > 0 && sentence.length < 120) return [sentence];
154
+ return null;
155
+ }
156
+
157
+ pi.on("turn_end", async (event: any) => {
158
+ // prose-offer rewrite
159
+ if (settings.rewriteProseOffers && states.length === 0) {
160
+ try {
161
+ const msgs = event?.messages ?? [];
162
+ const lastAssistant = [...msgs].reverse().find((m: any) => m?.role === "assistant");
163
+ let text = "";
164
+ if (typeof lastAssistant?.content === "string") {
165
+ text = lastAssistant.content;
166
+ } else if (Array.isArray(lastAssistant?.content)) {
167
+ text = lastAssistant.content.map((c: any) => c?.text ?? "").join("");
168
+ }
169
+ const opts = planOffer(text);
170
+ if (opts && opts.length >= 2) {
171
+ states.push({ options: opts, multi: true, rec: "", risky: "", subtitles: [], alternates: "" });
172
+ }
173
+ } catch {
174
+ // ignore
175
+ }
176
+ }
177
+ if (states.length > 0) {
178
+ // age existing queue
179
+ for (const q of queue) q.age++;
180
+ replyCounter++;
181
+ for (const st of states) {
182
+ const rest = withoutPicked(st);
183
+ if (rest.options.length === 0) continue;
184
+ const key = keyOf(rest.options);
185
+ if (queue.some((q) => q.age === 0 && keyOf(q.options) === key)) continue;
186
+ queue.unshift({ ...rest, age: 0, reply: replyCounter });
187
+ }
188
+ while (queue.length > 30) queue.pop();
189
+ // States are per reply; the queue is the only place a block survives.
190
+ states = [];
191
+ pickedThisTurn.clear();
192
+ }
193
+ });
194
+
195
+ pi.registerTool({
196
+ name: "next_steps",
197
+ label: "Next Steps",
198
+ description:
199
+ "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.",
200
+ parameters: {
201
+ type: "object",
202
+ properties: {
203
+ options: { type: "array", items: { type: "string" }, description: "The option labels to offer." },
204
+ multi: { type: "boolean", description: "Allow picking multiple (default true)." },
205
+ rec: { type: "string", description: "Comma-separated 1-based indices to mark recommended." },
206
+ risky: { type: "string", description: "Comma-separated 1-based indices to mark risky." },
207
+ subtitles: { type: "array", items: { type: "string" }, description: "Optional dim second lines, one per option." },
208
+ alternates: { type: "string", description: "Groups of mutually exclusive indices, e.g. '1,3|2'." },
209
+ carry: { type: "boolean", description: "Record this reply's options for carry-forward (default follows setting)." },
210
+ },
211
+ required: ["options"],
212
+ },
213
+ execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
214
+ const args = (params ?? {}) as any;
215
+ const opts = ((args.options as string[]) ?? []).map((s) => String(s).trim()).filter(Boolean);
216
+ if (opts.length === 0) {
217
+ ctx.ui.notify("next_steps: no options", "warning");
218
+ return { content: [{ type: "text", text: "No options provided." }] };
219
+ }
220
+ let rec = (args.rec as string) ?? "";
221
+ let risky = (args.risky as string) ?? "";
222
+ // Auto-classify when not provided (best-effort, silent on failure)
223
+ if (!rec && !risky && settings.markRisky && ctx?.model) {
224
+ try {
225
+ const model = ctx.model;
226
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
227
+ if (auth.ok) {
228
+ const context: any = {
229
+ systemPrompt: "You are a classifier. Reply with JSON only.",
230
+ messages: [
231
+ {
232
+ role: "user",
233
+ 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")}`,
234
+ timestamp: Date.now(),
235
+ },
236
+ ],
237
+ };
238
+ const stream = ctx.modelRegistry.streamSimple(model, context, { apiKey: auth.apiKey, headers: auth.headers, baseUrl: auth.baseUrl });
239
+ let msg: any = null;
240
+ for await (const ev of stream) {
241
+ if (ev.type === "done") msg = ev.message;
242
+ }
243
+ if (!msg) msg = await stream.result();
244
+ const text = Array.isArray(msg?.content)
245
+ ? msg.content.map((c: any) => c?.text ?? "").join("")
246
+ : String(msg?.content ?? "");
247
+ const m = text.match(/\{[\s\S]*\}/);
248
+ if (m) {
249
+ try {
250
+ const j = JSON.parse(m[0]);
251
+ if (Array.isArray(j.rec)) rec = j.rec.join(",");
252
+ if (Array.isArray(j.risky)) risky = j.risky.join(",");
253
+ } catch {
254
+ // ignore parse errors
255
+ }
256
+ }
257
+ }
258
+ } catch {
259
+ // classification best-effort
260
+ }
261
+ }
262
+ const alternates = (args.alternates as string) ?? "";
263
+ const newState: NextStepsState = {
264
+ options: opts,
265
+ multi: args.multi !== false,
266
+ rec,
267
+ risky,
268
+ subtitles: (args.subtitles as string[]) ?? [],
269
+ alternates,
270
+ };
271
+ states.push(newState);
272
+ if (args.carry === true) settings.carryForward = true;
273
+ const recSet = new Set((states[0].rec || "").split(",").map((s) => s.trim()));
274
+ const riskySet = new Set((states[0].risky || "").split(",").map((s) => s.trim()));
275
+ const lines = newState.options.map((o, i) => {
276
+ const n = i + 1;
277
+ const tags = [
278
+ settings.accentRecommended && recSet.has(String(n)) ? "★" : "",
279
+ settings.markRisky && riskySet.has(String(n)) ? "▲" : "",
280
+ ].filter(Boolean).join(" ");
281
+ const sub = newState.subtitles[i] ? ` — ${newState.subtitles[i]}` : "";
282
+ const tagPrefix = tags ? `${tags} ` : "";
283
+ return `${n}. ${tagPrefix}${o}${sub}`;
284
+ });
285
+ // Render an interactive choice right away instead of forcing /ns.
286
+ const choiceLabels = newState.options.map((o, i) => {
287
+ const n = i + 1;
288
+ const recTag = settings.accentRecommended && recSet.has(String(n)) ? " ★ RECOMMENDED" : "";
289
+ const riskyTag = settings.markRisky && riskySet.has(String(n)) ? " ▲ RISKY" : "";
290
+ const sub = newState.subtitles[i] ? ` — ${newState.subtitles[i]}` : "";
291
+ return `${o}${sub}${recTag}${riskyTag}`;
292
+ });
293
+ try {
294
+ const selected = new Set<number>();
295
+ const result = await ctx.ui.custom<number[] | null>((tui, theme, _kb, done) => {
296
+ let cursor = 0;
297
+ const component = {
298
+ focused: true,
299
+ render(_width: number): string[] {
300
+ const lines: string[] = [];
301
+ lines.push(theme.fg("accent", "Next steps (space toggle, enter confirm):"));
302
+ for (let i = 0; i < choiceLabels.length; i++) {
303
+ const check = selected.has(i) ? "[x]" : "[ ]";
304
+ const prefix = i === cursor ? theme.fg("accent", "> ") : " ";
305
+ lines.push(`${prefix}${check} ${choiceLabels[i]}`);
306
+ }
307
+ lines.push(theme.fg("dim", "space toggle · ↑↓ move · enter/tab confirm · esc cancel"));
308
+ return lines;
309
+ },
310
+ invalidate() {},
311
+ handleInput(data: string) {
312
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
313
+ cursor = (cursor - 1 + choiceLabels.length) % choiceLabels.length;
314
+ tui.requestRender();
315
+ } else if (matchesKey(data, "down") || matchesKey(data, "j")) {
316
+ cursor = (cursor + 1) % choiceLabels.length;
317
+ tui.requestRender();
318
+ } else if (matchesKey(data, "space")) {
319
+ if (selected.has(cursor)) selected.delete(cursor);
320
+ else selected.add(cursor);
321
+ tui.requestRender();
322
+ } else if (matchesKey(data, "enter") || matchesKey(data, "tab")) {
323
+ done(Array.from(selected).sort((a, b) => a - b));
324
+ } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
325
+ done(null);
326
+ }
327
+ },
328
+ };
329
+ return component;
330
+ });
331
+ if (result && result.length > 0) {
332
+ const chosen = result.map((n) => newState.options[n]);
333
+ const message = chosen.length === 1 ? chosen[0] : chosen.map((c) => `- ${c}`).join("\n");
334
+ if (ctx.isIdle()) {
335
+ pi.sendUserMessage(message);
336
+ } else if (settings.steerOnClick) {
337
+ pi.sendUserMessage(message, { deliverAs: "steer" });
338
+ } else {
339
+ pi.sendUserMessage(message, { deliverAs: "followUp" });
340
+ }
341
+ for (const c of chosen) pickedThisTurn.add(c);
342
+ retirePicked(chosen);
343
+ ctx.ui.notify(`Sent ${chosen.length} step(s)`, "info");
344
+ } else if (result !== null) {
345
+ // empty selection (enter with nothing toggled) — send nothing
346
+ ctx.ui.notify("No selection", "info");
347
+ }
348
+ } catch {
349
+ // Non-interactive mode or UI unavailable; fall back to /ns.
350
+ }
351
+ ctx.ui.notify(`Next steps registered.`, "info");
352
+ return {
353
+ content: [{ type: "text", text: `Registered ${opts.length} next steps:\n${lines.join("\n")}` }],
354
+ };
355
+ },
356
+ });
357
+
358
+ async function pickAndSend(ctx: any) {
359
+ if (queue.length === 0) {
360
+ ctx.ui.notify("No next steps registered. Ask the agent to call next_steps.", "warning");
361
+ return;
362
+ }
363
+ // One tab per collected block, newest first. Carried blocks keep their real age.
364
+ const blocks = queue.map((q) => {
365
+ const recSet = new Set((q.rec || "").split(",").map((s) => s.trim()));
366
+ const riskySet = new Set((q.risky || "").split(",").map((s) => s.trim()));
367
+ return {
368
+ age: q.age,
369
+ items: q.options.map((o, i) => {
370
+ const tags = [
371
+ settings.accentRecommended && recSet.has(String(i + 1)) ? "★" : "",
372
+ settings.markRisky && riskySet.has(String(i + 1)) ? "▲" : "",
373
+ ].filter(Boolean).join(" ");
374
+ return { option: o, text: `${tags ? tags + " " : ""}${o}` };
375
+ }),
376
+ };
377
+ });
378
+ const tabLabel = (i: number) =>
379
+ i === 0 ? "this reply" : blocks[i].age === 1 ? "1 reply back" : `${blocks[i].age} replies back`;
380
+ let chosen: string[] | null = null;
381
+ try {
382
+ chosen = await ctx.ui.custom<string[] | null>((tui, theme, _kb, done) => {
383
+ let tab = 0;
384
+ let cursor = 0;
385
+ let picked = new Set<string>();
386
+ let armed = new Set<string>();
387
+ const staleKeys = () => {
388
+ const keys: string[] = [];
389
+ blocks.forEach((block, b) => {
390
+ if (b > 0) block.items.forEach((_, i) => keys.push(`${b}:${i}`));
391
+ });
392
+ return keys;
393
+ };
394
+ const reindex = (set: Set<string>, block: number, item?: number) => {
395
+ const out = new Set<string>();
396
+ for (const key of set) {
397
+ const [b, i] = key.split(":").map(Number);
398
+ if (b === block && (item === undefined || i === item)) continue;
399
+ out.add(`${b > block ? b - 1 : b}:${b === block && item !== undefined && i > item ? i - 1 : i}`);
400
+ }
401
+ return out;
402
+ };
403
+ const deleteArmed = (keys: string[]) => {
404
+ const byBlock = new Map<number, number[]>();
405
+ for (const key of keys) {
406
+ const [b, i] = key.split(":").map(Number);
407
+ byBlock.set(b, [...(byBlock.get(b) ?? []), i]);
408
+ }
409
+ for (const b of [...byBlock.keys()].sort((x, y) => y - x)) {
410
+ const items = byBlock.get(b);
411
+ if (!items) continue;
412
+ for (const i of items.sort((x, y) => y - x)) {
413
+ blocks[b].items.splice(i, 1);
414
+ dropOption(queue[b], i);
415
+ picked = reindex(picked, b, i);
416
+ armed = reindex(armed, b, i);
417
+ }
418
+ if (blocks[b].items.length === 0) {
419
+ blocks.splice(b, 1);
420
+ queue.splice(b, 1);
421
+ picked = reindex(picked, b);
422
+ armed = reindex(armed, b);
423
+ }
424
+ }
425
+ tab = Math.min(tab, blocks.length - 1);
426
+ cursor = Math.min(cursor, Math.max(0, blocks[tab].items.length - 1));
427
+ armed.clear();
428
+ };
429
+ const component = {
430
+ focused: true,
431
+ render(_width: number): string[] {
432
+ const out: string[] = [];
433
+ const head = blocks
434
+ .map((_, i) =>
435
+ i === tab ? theme.fg("accent", `[${tabLabel(i)}]`) : theme.fg("dim", ` ${tabLabel(i)} `),
436
+ )
437
+ .join(" · ");
438
+ out.push(`${theme.fg("accent", "Next steps")} ${head}`);
439
+ blocks[tab].items.forEach((item, i) => {
440
+ const key = `${tab}:${i}`;
441
+ const mark = picked.has(key) ? "[x]" : "[ ]";
442
+ const prefix = i === cursor ? theme.fg("accent", "> ") : " ";
443
+ const text = armed.has(key) ? theme.fg("error", `[del] ${item.text}`) : item.text;
444
+ out.push(`${prefix}${mark} ${text}`);
445
+ });
446
+ out.push(theme.fg("dim", "space toggle · ↑↓ move · ←→ block · ctrl+d delete stale · shift+ctrl+d all stale · enter/tab confirm · esc cancel"));
447
+ return out;
448
+ },
449
+ invalidate() {},
450
+ handleInput(data: string) {
451
+ const all = matchesKey(data, "shift+ctrl+d");
452
+ if (all || matchesKey(data, "ctrl+d")) {
453
+ let targets: string[] = [];
454
+ if (all) targets = staleKeys();
455
+ else if (tab > 0) targets = [`${tab}:${cursor}`];
456
+ if (targets.length > 0) {
457
+ if (targets.every((key) => armed.has(key))) deleteArmed(targets);
458
+ else for (const key of targets) armed.add(key);
459
+ tui.requestRender();
460
+ return;
461
+ }
462
+ }
463
+ const n = blocks[tab].items.length;
464
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
465
+ cursor = (cursor - 1 + n) % n;
466
+ } else if (matchesKey(data, "down") || matchesKey(data, "j")) {
467
+ cursor = (cursor + 1) % n;
468
+ } else if (matchesKey(data, "left") || matchesKey(data, "h")) {
469
+ tab = (tab - 1 + blocks.length) % blocks.length;
470
+ cursor = 0;
471
+ } else if (matchesKey(data, "right") || matchesKey(data, "l")) {
472
+ tab = (tab + 1) % blocks.length;
473
+ cursor = 0;
474
+ } else if (matchesKey(data, "space")) {
475
+ const key = `${tab}:${cursor}`;
476
+ if (picked.has(key)) picked.delete(key);
477
+ else picked.add(key);
478
+ } else if (matchesKey(data, "enter") || matchesKey(data, "tab")) {
479
+ done(
480
+ Array.from(picked).map((key) => {
481
+ const [b, i] = key.split(":").map(Number);
482
+ return blocks[b].items[i].option;
483
+ }),
484
+ );
485
+ return;
486
+ } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
487
+ done(null);
488
+ return;
489
+ }
490
+ tui.requestRender();
491
+ },
492
+ };
493
+ return component;
494
+ });
495
+ } catch {
496
+ ctx.ui.notify("Selection UI unavailable in this session.", "warning");
497
+ return;
498
+ }
499
+ if (!chosen || chosen.length === 0) {
500
+ ctx.ui.notify("No selection", "info");
501
+ return;
502
+ }
503
+ // Every picked step travels as one user message, never one message per step.
504
+ const message = chosen.length === 1 ? chosen[0] : chosen.map((c) => `- ${c}`).join("\n");
505
+ if (ctx.isIdle()) {
506
+ pi.sendUserMessage(message);
507
+ } else if (settings.steerOnClick) {
508
+ pi.sendUserMessage(message, { deliverAs: "steer" });
509
+ } else {
510
+ pi.sendUserMessage(message, { deliverAs: "followUp" });
511
+ }
512
+ retirePicked(chosen);
513
+ ctx.ui.notify(`Sent ${chosen.length} step(s)`, "info");
514
+ }
515
+
516
+ // `/ns clear` drops everything older than the newest reply; `/ns clear X` drops the last X posts.
517
+ async function clearSteps(arg: string, ctx: any) {
518
+ const trimmed = arg.trim();
519
+ if (queue.length === 0) {
520
+ ctx.ui.notify("No collected next steps to clear.", "info");
521
+ return;
522
+ }
523
+ if (/^clear$/i.test(trimmed)) {
524
+ const before = queue.length;
525
+ const newest = queue[0].reply;
526
+ for (let i = queue.length - 1; i >= 0; i--) {
527
+ if (queue[i].reply < newest) queue.splice(i, 1);
528
+ }
529
+ const dropped = before - queue.length;
530
+ ctx.ui.notify(
531
+ dropped > 0
532
+ ? `Cleared ${dropped} stale step(s). Kept the newest reply.`
533
+ : "Nothing stale to clear. Use /ns clear X for the last X posts.",
534
+ "info",
535
+ );
536
+ return;
537
+ }
538
+ const m = trimmed.match(/^clear\s+(\d+)$/i);
539
+ if (m) {
540
+ const n = parseInt(m[1], 10);
541
+ if (n < 1) {
542
+ ctx.ui.notify("Usage: /ns clear [X]", "warning");
543
+ return;
544
+ }
545
+ const cutoff = replyCounter - n + 1;
546
+ const before = queue.length;
547
+ for (let i = queue.length - 1; i >= 0; i--) {
548
+ if (queue[i].reply >= cutoff) queue.splice(i, 1);
549
+ }
550
+ const dropped = before - queue.length;
551
+ ctx.ui.notify(
552
+ dropped > 0
553
+ ? `Cleared ${dropped} step(s) from the last ${n} post(s).`
554
+ : `No collected steps in the last ${n} post(s).`,
555
+ "info",
556
+ );
557
+ return;
558
+ }
559
+ ctx.ui.notify("Usage: /ns clear (stale) or /ns clear X (last X posts)", "warning");
560
+ }
561
+
562
+ const runOrClear = async (args: string, ctx: any) => {
563
+ const a = (args ?? "").trim();
564
+ if (!a) return pickAndSend(ctx);
565
+ if (/^clear\b/i.test(a) || /^clear$/i.test(a)) return clearSteps(a, ctx);
566
+ ctx.ui.notify("Usage: /ns or /ns clear [X]", "warning");
567
+ };
568
+
569
+ pi.registerCommand("ns", {
570
+ description: "Pick and send a registered next step, or /ns clear [X] to drop collected steps.",
571
+ handler: async (args, ctx) => runOrClear(args, ctx),
572
+ });
573
+ pi.registerCommand("nextsteps", {
574
+ description: "Pick and send a registered next step, or /nextsteps clear [X] to drop collected steps.",
575
+ handler: async (args, ctx) => runOrClear(args, ctx),
576
+ });
577
+ pi.registerCommand("nextsteps-settings", {
578
+ description: "Show next-steps settings path.",
579
+ handler: async (_args, ctx) => {
580
+ ctx.ui.notify(`Settings: ${SETTINGS_PATH}`, "info");
581
+ },
582
+ });
583
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-next-steps",
3
- "version": "1.1.6",
3
+ "version": "1.2.0",
4
4
  "description": "Next Steps extension for the Pi coding agent",
5
5
  "type": "module",
6
6
  "main": "next-steps.ts",