@andares/pi-toolkits 1.2.3 → 1.2.5

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.
@@ -22,7 +22,13 @@ import { readFileSync } from "node:fs";
22
22
  import { isAbsolute, relative, resolve } from "node:path";
23
23
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
24
  import { Type } from "typebox";
25
- import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
25
+ import type {
26
+ ExtensionAPI,
27
+ ExtensionContext,
28
+ InputEvent,
29
+ InputEventResult,
30
+ ToolCallEvent,
31
+ } from "@earendil-works/pi-coding-agent";
26
32
  import type { GateHub } from "../../lib/gates.js";
27
33
  import { getPermissionControl, type PermissionSnapshot } from "../../lib/permission-control.js";
28
34
  import { getAskControl } from "../../lib/ask-control.js";
@@ -33,7 +39,12 @@ import { canonicalize, isWithin } from "../permission/paths.js";
33
39
  import { parseCommandUnits } from "../permission/units.js";
34
40
  import { buildFeedbackMarkdown } from "./feedback.js";
35
41
  import { openInBrowser } from "../../lib/opener.js";
36
- import { buildSpecKickoff, buildSpecSystemPrompt } from "./prompt.js";
42
+ import {
43
+ buildSpecKickoff,
44
+ buildSpecKickoffFromBrief,
45
+ buildSpecSystemPrompt,
46
+ specTitleFromBrief,
47
+ } from "./prompt.js";
37
48
  import { renderBlockHtml } from "../review-page/render.js";
38
49
  import { buildSpecState, startSpecServer, type SpecServerHandle } from "./server.js";
39
50
  import {
@@ -46,7 +57,6 @@ import {
46
57
  } from "./store.js";
47
58
 
48
59
  export const SPEC_COMMAND = "ask-spec";
49
- export const SPEC_COMMAND_ALIAS = "ask-plan";
50
60
  export const SPEC_SUBMIT_TOOL = SPEC_PHASE_TOOL;
51
61
 
52
62
  /** Files the spec-review phase may write: project markdown, nothing else. */
@@ -115,6 +125,12 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
115
125
  let cwd = process.cwd();
116
126
  let ctxRef: ExtensionContext | undefined;
117
127
  let specSessionId: string | undefined;
128
+ /**
129
+ * The bare command arms the phase instead of starting it: the requirement is
130
+ * a message the operator has not typed yet. Until it arrives the phase is off
131
+ * (no gates, no tools, no permission change) — only this flag is set.
132
+ */
133
+ let armedForBrief = false;
118
134
 
119
135
  function closeServer(): void {
120
136
  if (!server) return;
@@ -161,6 +177,54 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
161
177
  return { handle, started: true };
162
178
  }
163
179
 
180
+ /** Target file and kickoff for a brief that arrives as a message. */
181
+ function briefPlan(brief: string): { path: string; kickoff: string } {
182
+ const path = `specs/${specSlug(specTitleFromBrief(brief))}.md`;
183
+ return { path, kickoff: buildSpecKickoffFromBrief(brief, path) };
184
+ }
185
+
186
+ /**
187
+ * Turn spec review on. Shared by both entries: `/ask-spec <topic>` and the
188
+ * armed bare command whose brief arrives as the next message. Sending the
189
+ * kickoff stays with the caller — the two paths deliver it differently (a new
190
+ * message vs. the transformed input that is already on its way).
191
+ */
192
+ function enterPhase(target: ExtensionContext, plan: { path: string; kickoff: string }): void {
193
+ // Entering through a topic replaces a pending bare-command brief. Leaving
194
+ // the flag set would make `off` cancel the wait instead of the active
195
+ // phase, and would consume a later, unrelated message as another brief.
196
+ armedForBrief = false;
197
+ const readiness = frameworkReadiness(resolveProjectRoot(cwd));
198
+ if (!readiness.ready) {
199
+ target.ui.notify(
200
+ `ask-spec: no complete agent framework (missing: ${readiness.missing.join(", ")}). The spec still works, but record_change and /ask-uat stay unavailable until /ask-init.`,
201
+ "info",
202
+ );
203
+ }
204
+ specPath = plan.path;
205
+ session = undefined;
206
+ specSessionId = sessionIdOf(target);
207
+ const permission = getPermissionControl();
208
+ permissionBefore = permission?.snapshot();
209
+ permission?.enableDefaults(target);
210
+ permissionDuring = permission?.snapshot();
211
+ // Spec mode is intentionally less restrictive than ask mode. Let ask
212
+ // restore its own tool snapshot before we add spec_submit.
213
+ if (getAskControl()?.isActive()) getAskControl()?.exit(target);
214
+ active = true;
215
+ pi.setActiveTools(toolSetWithSubmit());
216
+ target.ui.notify(
217
+ `ask-spec: reviewing. Write the spec to ${plan.path}, then call ${SPEC_SUBMIT_TOOL}.`,
218
+ "info",
219
+ );
220
+ }
221
+
222
+ /** True only for a command the host actually knows, not any `/path`-like text. */
223
+ function isRegisteredCommand(text: string): boolean {
224
+ const name = /^\/([^\s]+)/.exec(text)?.[1];
225
+ return name !== undefined && pi.getCommands().some((command) => command.name === name);
226
+ }
227
+
164
228
  function toolSetWithSubmit(): string[] {
165
229
  const tools = pi
166
230
  .getActiveTools()
@@ -259,13 +323,18 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
259
323
 
260
324
  const specCommand = {
261
325
  description:
262
- "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. Run without arguments again, or use `off`, to leave the phase; `open` re-opens the review.",
326
+ "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. Without arguments it arms the phase and your next message (multi-line paste included) becomes the brief; run the bare command again or use `off` to leave or cancel, and `open` re-opens the review.",
263
327
  handler: async (args: string, ctx: ExtensionContext) => {
264
328
  const arg = args.trim();
265
329
  ctxRef = ctx;
266
330
  cwd = canonicalize(ctx.cwd || process.cwd());
267
331
 
268
332
  if (arg === "off") {
333
+ if (armedForBrief) {
334
+ armedForBrief = false;
335
+ ctx.ui.notify("ask-spec: pending requirement cancelled.", "info");
336
+ return;
337
+ }
269
338
  if (!active) {
270
339
  ctx.ui.notify("ask-spec: not in spec mode.", "info");
271
340
  return;
@@ -313,40 +382,80 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
313
382
  return;
314
383
  }
315
384
 
316
- const readiness = frameworkReadiness(resolveProjectRoot(cwd));
317
- if (!readiness.ready) {
385
+ // Bare command: arm and wait for the brief instead of starting from a
386
+ // topic that has to be squeezed onto the command line. A pasted
387
+ // multi-paragraph requirement is the whole point of this entry.
388
+ if (arg === "") {
389
+ if (armedForBrief) {
390
+ armedForBrief = false;
391
+ ctx.ui.notify("ask-spec: pending requirement cancelled.", "info");
392
+ return;
393
+ }
394
+ armedForBrief = true;
318
395
  ctx.ui.notify(
319
- `ask-spec: no complete agent framework (missing: ${readiness.missing.join(", ")}). The spec still works, but record_change and /ask-uat stay unavailable until /ask-init.`,
396
+ "ask-spec: armed — send the requirement as your next message (multi-line and pasted text are fine); spec review starts from it. /ask-spec again cancels.",
320
397
  "info",
321
398
  );
399
+ return;
322
400
  }
323
401
 
324
- const slug = specSlug(arg || "spec");
325
- specPath = `specs/${slug}.md`;
326
- session = undefined;
327
- specSessionId = sessionIdOf(ctx);
328
- const permission = getPermissionControl();
329
- permissionBefore = permission?.snapshot();
330
- permission?.enableDefaults(ctx);
331
- permissionDuring = permission?.snapshot();
332
- // Spec mode is intentionally less restrictive than ask mode. Let ask
333
- // restore its own tool snapshot before we add spec_submit.
334
- if (getAskControl()?.isActive()) getAskControl()?.exit(ctx);
335
- active = true;
336
- pi.setActiveTools(toolSetWithSubmit());
337
- ctx.ui.notify(
338
- `ask-spec: reviewing. Write the spec to ${specPath}, then call ${SPEC_SUBMIT_TOOL}.`,
339
- "info",
340
- );
341
- pi.sendUserMessage(buildSpecKickoff(arg || undefined));
402
+ const plan = { path: `specs/${specSlug(arg)}.md`, kickoff: buildSpecKickoff(arg) };
403
+ enterPhase(ctx, plan);
404
+ pi.sendUserMessage(plan.kickoff);
342
405
  },
343
406
  };
344
407
 
345
- // `/ask-plan` stays as an alias: the workflow predates the rename, and a
346
- // half-remembered command must not drop the operator into a plain chat.
347
- for (const command of [SPEC_COMMAND, SPEC_COMMAND_ALIAS]) {
348
- pi.registerCommand(command, specCommand);
349
- }
408
+ /**
409
+ * The armed bare command: the next message is the brief.
410
+ *
411
+ * The input runs before the model sees anything, so the phase is turned on
412
+ * here — `before_agent_start` then injects the spec banner and re-asserts the
413
+ * tool set for this very turn — and the message is transformed into the
414
+ * kickoff with the requirement embedded verbatim. Nothing is dropped or sent
415
+ * twice: it is still the operator's one message.
416
+ *
417
+ * Commands and extension-dispatched messages are not the brief: built-in
418
+ * slash commands never reach here, but a registered `/cmd` can, and
419
+ * autostart sends its whole list through `sendUserMessage` with source
420
+ * `extension` — neither should be eaten as a requirement.
421
+ */
422
+ pi.on("input", (event: InputEvent, ctx: ExtensionContext): InputEventResult | undefined => {
423
+ if (!armedForBrief || active) return undefined;
424
+ if (event.source === "extension") return undefined;
425
+ const brief = event.text.trim();
426
+ if (brief === "" || isRegisteredCommand(brief)) return undefined;
427
+ // The command enforces these before arming, but either state can change
428
+ // while the operator is composing the brief. Re-check at the moment the
429
+ // phase would really start: entering during a stream would mutate the
430
+ // current run's tools, and entering over UAT would stack the two phases.
431
+ if (event.streamingBehavior !== undefined || !ctx.isIdle()) {
432
+ armedForBrief = false;
433
+ ctx.ui.notify(
434
+ "ask-spec: the agent is still running — pending requirement cancelled; finish or abort first.",
435
+ "warning",
436
+ );
437
+ return undefined;
438
+ }
439
+ if (pi.getActiveTools().includes(UAT_PHASE_TOOL)) {
440
+ armedForBrief = false;
441
+ ctx.ui.notify(
442
+ "ask-spec: ask-uat is open — pending requirement cancelled; /ask-uat off first.",
443
+ "warning",
444
+ );
445
+ return undefined;
446
+ }
447
+ ctxRef = ctx;
448
+ cwd = canonicalize(ctx.cwd || process.cwd());
449
+ const plan = briefPlan(brief);
450
+ enterPhase(ctx, plan);
451
+ return { action: "transform", text: plan.kickoff };
452
+ });
453
+
454
+ // One name only. The pre-rename `/ask-plan` alias was removed 2026-11-27
455
+ // (it had been undocumented since the rename; autostart entries still
456
+ // spelled that way are skipped by the pre-flight and reported, so they are
457
+ // not sent to the model as chat).
458
+ pi.registerCommand(SPEC_COMMAND, specCommand);
350
459
 
351
460
  // ── Tool ───────────────────────────────────────────────────────────────
352
461
 
@@ -501,6 +610,7 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
501
610
  });
502
611
 
503
612
  pi.on("session_shutdown", () => {
613
+ armedForBrief = false;
504
614
  closeServer();
505
615
  });
506
616
 
@@ -511,6 +621,7 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
511
621
  // or permission snapshot. Permission's own session_start has already reset
512
622
  // its state, so do not restore the old snapshot here.
513
623
  active = false;
624
+ armedForBrief = false;
514
625
  session = undefined;
515
626
  permissionBefore = undefined;
516
627
  permissionDuring = undefined;
@@ -1,10 +1,12 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
3
  buildSpecKickoff,
4
+ buildSpecKickoffFromBrief,
4
5
  buildSpecSystemPrompt,
5
6
  INTERVIEW_GUIDE,
6
7
  SPEC_MODE_BANNER,
7
8
  SPEC_FRAMEWORK_GUIDE,
9
+ specTitleFromBrief,
8
10
  } from "./prompt.js";
9
11
 
10
12
  describe("spec review prompt", () => {
@@ -89,3 +91,21 @@ describe("buildSpecKickoff", () => {
89
91
  expect(buildSpecKickoff(" ")).toContain("the work we have been discussing in this session");
90
92
  });
91
93
  });
94
+
95
+ describe("brief-shaped kickoff", () => {
96
+ it("keeps the requirement byte for byte, blank lines and lists included", () => {
97
+ const brief = "Renew the watcher\n\nWhy: the current one drops events.\n\n- keep the API\n- add a test";
98
+ const kickoff = buildSpecKickoffFromBrief(brief, "specs/renew-the-watcher.md");
99
+ expect(kickoff).toContain(brief);
100
+ expect(kickoff).toContain("Target file: `specs/renew-the-watcher.md`");
101
+ expect(kickoff).toContain("Do not implement anything yet.");
102
+ });
103
+
104
+ it("takes the file title from the first real line", () => {
105
+ expect(specTitleFromBrief("## Add a queue\n\ndetail")).toBe("Add a queue");
106
+ expect(specTitleFromBrief("\n\n 1. Fix the export\nmore")).toBe("Fix the export");
107
+ expect(specTitleFromBrief("```ts\nconst a = 1;\n```\nTop level ask")).toBe("Top level ask");
108
+ expect(specTitleFromBrief("### ")).toBe("spec");
109
+ expect(specTitleFromBrief(" ")).toBe("spec");
110
+ });
111
+ });
@@ -108,3 +108,49 @@ export function buildSpecKickoff(topic: string | undefined): string {
108
108
  "submit it with spec_submit. Do not implement anything yet.",
109
109
  ].join("\n");
110
110
  }
111
+
112
+ /**
113
+ * First line of a message-shaped brief, stripped of markdown markers, for the
114
+ * default file name. A requirement usually opens with the line that names the
115
+ * work; the rest is detail that makes a poor file name and would be truncated
116
+ * anyway.
117
+ */
118
+ export function specTitleFromBrief(brief: string): string {
119
+ let inFence = false;
120
+ for (const raw of brief.split(/\r?\n/)) {
121
+ const line = raw.trim();
122
+ if (line.startsWith("```") || line.startsWith("~~~")) {
123
+ inFence = !inFence;
124
+ continue;
125
+ }
126
+ if (inFence || line === "") continue;
127
+ const stripped = line
128
+ .replace(/^#{1,6}\s*/, "")
129
+ .replace(/^([-*+>]|\d+[.)])\s+/, "")
130
+ .trim();
131
+ // A line that is nothing but list/quote markers names nothing.
132
+ if (stripped === "" || /^[-*+>#]+$/.test(stripped)) continue;
133
+ return stripped;
134
+ }
135
+ return "spec";
136
+ }
137
+
138
+ /**
139
+ * Kickoff for the armed bare command. Here the requirement is the operator's
140
+ * whole message, so it is embedded verbatim instead of being compressed into a
141
+ * one-line topic: the point of that entry is that a long, pasted, multi-paragraph
142
+ * brief arrives intact.
143
+ */
144
+ export function buildSpecKickoffFromBrief(brief: string, specPath: string): string {
145
+ return [
146
+ "Start spec review.",
147
+ `Target file: \`${specPath}\`.`,
148
+ "",
149
+ "## Operator's requirement",
150
+ "",
151
+ brief.trim(),
152
+ "",
153
+ "Explore the code before writing, ask me what you cannot infer, then write the spec file and",
154
+ "submit it with spec_submit. Do not implement anything yet.",
155
+ ].join("\n");
156
+ }
@@ -21,8 +21,8 @@ import type { KeyId } from "@earendil-works/pi-tui";
21
21
  /**
22
22
  * Stash hotkey.
23
23
  *
24
- * Compatibility rationale (verified against pi 0.99.0–1.5.1 keybindings, live
25
- * matchesKey probes and terminal/OS behavior):
24
+ * Compatibility rationale (keybinding tables audited across pi 1.0.0–1.7.0;
25
+ * matchesKey probes and terminal/OS behavior verified separately):
26
26
  * - pi: no default binding for ctrl+alt+<letter> (only ctrl+alt+] is taken);
27
27
  * extension shortcuts dispatch first while the editor is focused
28
28
  * - terminals: alt encodes as ESC-prefix, so ctrl+alt+y arrives as "\x1b\x19"
package/src/index.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * - ask — read-only Q&A mode (/ask)
9
9
  * - favorites — model favorites (ctrl+A/ctrl+J in /model, favorites-only cycling)
10
10
  * - stash — prompt stash (ctrl+alt+y swap / double-press stash-and-clear)
11
- * - review — third-party code review with a configured review model (/ask-review, alias /third-review)
11
+ * - review — third-party code review with a configured review model (/ask-review)
12
12
  * - compact — dedicated compact model for /compact + auto-compact summaries
13
13
  * - autostart — replay project-declared slash commands at session start (/add-dir persistence)
14
14
  * - permission — session-scoped boundary permission checks (/ask-perm)
package/src/lib/gates.ts CHANGED
@@ -18,9 +18,9 @@
18
18
  * promise. The queue serializes our own presentations; the host slot is
19
19
  * still shared with other extensions (pi does not arbitrate globally).
20
20
  * pi 1.4.0 stacks extension dialogs so a second one no longer strands the
21
- * first (#11166), but the 1.2–1.3 hosts in the supported window still
22
- * replace it — the queue stays, and it also keeps one confirmation visible
23
- * at a time instead of a pile of stacked dialogs on later hosts.
21
+ * first (#11166), but the 1.2–1.3 hosts covered by the declared floor
22
+ * still replace it — the queue stays, and it also keeps one confirmation
23
+ * visible at a time instead of a pile of stacked dialogs on later hosts.
24
24
  * - A gate that throws blocks the call (fail closed), matching pi's own
25
25
  * `tool_call` handler contract.
26
26
  *