@blackbelt-technology/pi-dashboard-extension 0.5.3 → 0.5.4

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.
@@ -9,7 +9,7 @@ import type {
9
9
  ExtensionToServerMessage,
10
10
  } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
11
11
  import { killProcessByPgid } from "./process-scanner.js";
12
- import type { FileEntry, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
12
+ import type { FileEntry, ImageContent, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
13
  import { filterHiddenCommands } from "./bridge-context.js";
14
14
  import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
15
15
  import { tryDispatchExtensionCommand } from "./slash-dispatch.js";
@@ -169,7 +169,25 @@ export function createCommandHandler(
169
169
  * events emitted by the dispatch path arrive before this turn returns.
170
170
  * See change: fix-extension-slash-commands-in-dashboard.
171
171
  */
172
- sessionPrompt?: (text: string) => void | Promise<void>;
172
+ sessionPrompt?: (text: string, delivery?: "steer" | "followUp") => void | Promise<void>;
173
+ /**
174
+ * Bridge-shadow-queue hooks: called AFTER pi accepts the user message,
175
+ * gated by `isStreaming()` captured BEFORE the send. The capture order
176
+ * matters — `pi.sendUserMessage` on an idle session synchronously
177
+ * triggers `agent_start`, which flips bridge state to streaming. Checking
178
+ * AFTER the send would mis-record idle sends as chip entries.
179
+ * Pi doesn't expose `queue_update` to extensions, so the bridge is the
180
+ * source of truth. See change: add-followup-edit-and-steer-cancel.
181
+ */
182
+ onSteerSent?: (text: string) => void;
183
+ onFollowupSent?: (text: string) => void;
184
+ /**
185
+ * Returns true iff the agent was streaming at the moment of the call.
186
+ * Used to capture pre-send streaming state before `pi.sendUserMessage`
187
+ * runs (which may flip the flag synchronously via agent_start).
188
+ * See change: add-followup-edit-and-steer-cancel.
189
+ */
190
+ isStreaming?: () => boolean;
173
191
  },
174
192
  ): CommandHandler {
175
193
  const getSessionId = typeof sessionIdOrGetter === "function" ? sessionIdOrGetter : () => sessionIdOrGetter;
@@ -304,7 +322,7 @@ export function createCommandHandler(
304
322
  // extension-command dispatch. Do NOT emit completed here — would
305
323
  // duplicate the dispatch path's terminal event.
306
324
  // See change: fix-extension-slash-commands-in-dashboard.
307
- await options.sessionPrompt(parsed.text);
325
+ await options.sessionPrompt(parsed.text, msg.delivery);
308
326
  } else {
309
327
  // Test / non-bridge callers: apply the extension-command dispatch
310
328
  // branch inline before falling through to sendUserMessage. Keeps
@@ -314,12 +332,17 @@ export function createCommandHandler(
314
332
  parsed.text,
315
333
  sessionId,
316
334
  options?.eventSink,
335
+ undefined, // connection — absent in non-bridge path
336
+ msg.delivery,
317
337
  );
318
338
  if (!handled) {
319
339
  // sendUserMessage exempt from gating: only typed single-line
320
340
  // slashes that are NOT extension commands reach this — i.e.
321
341
  // skills, prompt templates, unrecognized slashes.
322
- pi.sendUserMessage(parsed.text);
342
+ // Forward delivery so steering on slash fallback honors the
343
+ // dashboard's keyboard contract. See change: add-steering-message.
344
+ const deliverAs = msg.delivery ?? ("followUp" as const);
345
+ (pi.sendUserMessage as any)(parsed.text, { deliverAs });
323
346
  }
324
347
  }
325
348
  return undefined;
@@ -339,11 +362,27 @@ export function createCommandHandler(
339
362
  if (outgoing.startsWith("/")) {
340
363
  outgoing = expandPromptTemplateFromDisk(outgoing, process.cwd(), pi);
341
364
  }
342
- sendUserMessageWithImages(pi, outgoing, msg.images);
365
+ // Pi owns the steering + follow-up queues natively. The helper enforces
366
+ // capacity-1 on follow-up by clearing pi's slot before sending. After
367
+ // pi accepts, notify the bridge so it updates its shadow queue — but
368
+ // only if the agent was already streaming BEFORE the send. Pi flips
369
+ // idle→streaming synchronously on the first user message, so checking
370
+ // after sendUserMessage gives false positives.
371
+ // See change: add-followup-edit-and-steer-cancel.
372
+ const wasStreaming = options?.isStreaming?.() ?? false;
373
+ sendUserMessageWithImages(pi, outgoing, msg.images, msg.delivery);
374
+ if (wasStreaming) {
375
+ const da = msg.delivery ?? "followUp";
376
+ if (da === "steer") options?.onSteerSent?.(outgoing);
377
+ else options?.onFollowupSent?.(outgoing);
378
+ }
343
379
  return undefined;
344
380
  }
345
381
 
346
382
  case "abort":
383
+ // Pi owns both queues now. abort() asks pi to halt the current turn;
384
+ // pi's native drain logic handles any remaining queue entries naturally.
385
+ // See change: add-followup-edit-and-steer-cancel.
347
386
  if (options?.abort) {
348
387
  options.abort();
349
388
  }
@@ -502,13 +541,20 @@ export function createCommandHandler(
502
541
  }
503
542
 
504
543
  /** Send a user message with optional image validation.
505
- * Uses deliverAs: "followUp" so messages queue properly when the agent is streaming. */
544
+ * Uses deliverAs: "followUp" by default so messages queue properly when the agent is streaming.
545
+ * Pass deliverAs: "steer" for steering messages (delivered after current turn).
546
+ * See change: add-steering-message. */
506
547
  function sendUserMessageWithImages(
507
548
  pi: ExtensionAPI,
508
549
  text: string,
509
550
  images?: Array<{ type: string; data: string; mimeType: string }>,
551
+ delivery?: "steer" | "followUp",
510
552
  ): void {
511
- const sendOptions = { deliverAs: "followUp" as const };
553
+ const deliverAs = delivery ?? ("followUp" as const);
554
+ const sendOptions = { deliverAs };
555
+ // v2: follow-up is a multi-entry queue. Sends APPEND — the cap-1 invariant
556
+ // is gone. See change: add-followup-edit-and-steer-cancel design.md Decision 8.
557
+ // (The bridge's shadow queue records the append via onFollowupSent.)
512
558
  if (images && images.length > 0) {
513
559
  const validMimeTypes = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
514
560
  const validImages = images.filter((img) => {
@@ -10,6 +10,11 @@ import type { PromptAdapter, PromptRequest, PromptResponse, PromptClaim } from "
10
10
 
11
11
  export class DashboardDefaultAdapter implements PromptAdapter {
12
12
  readonly name = "dashboard-default";
13
+ /**
14
+ * Last-resort fallback. Any plugin adapter with default priority (1000)
15
+ * or lower beats this. See change: route-flow-asks-to-upper-slot.
16
+ */
17
+ readonly priority = 9999;
13
18
 
14
19
  onRequest(_prompt: PromptRequest): PromptClaim {
15
20
  return {
package/src/prompt-bus.ts CHANGED
@@ -41,6 +41,14 @@ export interface PromptResponse {
41
41
 
42
42
  export interface PromptAdapter {
43
43
  name: string;
44
+ /**
45
+ * Routing priority. Lower numbers run first. Default 1000.
46
+ * `DashboardDefaultAdapter` uses 9999 so any plugin adapter with the
47
+ * default priority (1000) or lower beats it automatically.
48
+ *
49
+ * See change: route-flow-asks-to-upper-slot.
50
+ */
51
+ priority?: number;
44
52
  /**
45
53
  * Called when a new prompt arrives.
46
54
  * Return a PromptClaim to participate, or null/undefined to skip.
@@ -92,11 +100,18 @@ export class PromptBus {
92
100
  /**
93
101
  * Register an adapter. Returns an unsubscribe function.
94
102
  * Re-registering with the same name replaces the previous adapter.
103
+ *
104
+ * Adapters are kept sorted by `priority` (default 1000, lower first).
105
+ * `Array.prototype.sort` is stable in V8 ≥ ES2019 so equal priorities
106
+ * preserve insertion order. See change: route-flow-asks-to-upper-slot.
95
107
  */
96
108
  registerAdapter(adapter: PromptAdapter): () => void {
97
109
  // Replace existing adapter with same name
98
110
  this.adapters = this.adapters.filter(a => a.name !== adapter.name);
99
111
  this.adapters.push(adapter);
112
+ this.adapters.sort(
113
+ (a, b) => (a.priority ?? 1000) - (b.priority ?? 1000),
114
+ );
100
115
 
101
116
  return () => {
102
117
  this.adapters = this.adapters.filter(a => a !== adapter);
@@ -8,10 +8,14 @@
8
8
  * dashboard-spawned headless `pi --mode rpc` AND a `connection` is wired
9
9
  * → emit `dispatch_extension_command` to the server (server forwards to
10
10
  * the per-session RPC keeper UDS and emits the terminal command_feedback).
11
- * - Path D (stopgap, last resort): `pi.dispatchCommand` absent AND the bridge
12
- * is NOT headless (tmux / wt / unrecognized spawn shape) OR no `connection`
13
- * was supplied → emit `command_feedback {status:"error"}` with a pi-version
14
- * reminder.
11
+ * - Path D: `pi.dispatchCommand` absent AND the bridge is NOT headless
12
+ * (tmux / wt) OR no `connection` was supplied → emit
13
+ * `command_feedback {status:"error"}` with a hint to enable
14
+ * `useRpcKeeper: true` for headless sessions.
15
+ * Note: pi.sendUserMessage() hardcodes expandPromptTemplates: false, which
16
+ * skips _tryExecuteExtensionCommand; extension commands sent this way
17
+ * become regular LLM messages. This is a pi limitation — the bridge has
18
+ * no mechanism to dispatch extension commands outside the RPC path.
15
19
  *
16
20
  * If `text` is NOT an extension command, return `false` so the caller can
17
21
  * fall through to its existing template-expansion / sendUserMessage path.
@@ -21,7 +25,8 @@
21
25
  * Path C does NOT emit a terminal event — the server emits it.
22
26
  *
23
27
  * See change: fix-extension-slash-commands-in-dashboard,
24
- * add-rpc-stdin-dispatch-with-keeper-sidecar.
28
+ * add-rpc-stdin-dispatch-with-keeper-sidecar,
29
+ * fix-slash-dispatch-delivery.
25
30
  */
26
31
  import crypto from "node:crypto";
27
32
  import type { ExtensionToServerMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
@@ -38,9 +43,6 @@ export interface DispatchConnection {
38
43
  send(msg: ExtensionToServerMessage): void;
39
44
  }
40
45
 
41
- const PI_071_REQUIRED =
42
- "Extension slash commands cannot be dispatched from the dashboard yet — requires pi 0.71+ (`pi.dispatchCommand`). Invoke from the pi TUI, or use the extension's tools directly.";
43
-
44
46
  function emitFeedback(
45
47
  sink: FeedbackSink | undefined,
46
48
  sessionId: string,
@@ -64,8 +66,8 @@ function emitFeedback(
64
66
  * Try to dispatch a slash command as an extension command.
65
67
  *
66
68
  * @returns `true` if the helper handled the text (extension command detected;
67
- * dispatch attempted or stopgap emitted). The caller MUST NOT fall
68
- * through to template expansion or `sendUserMessage`.
69
+ * dispatch attempted or error feedback emitted). The caller MUST NOT
70
+ * fall through to template expansion or `sendUserMessage`.
69
71
  * @returns `false` if `text` is not an extension slash command. The caller
70
72
  * SHOULD continue with its existing fallback path.
71
73
  */
@@ -75,6 +77,7 @@ export async function tryDispatchExtensionCommand(
75
77
  sessionId: string,
76
78
  sink: FeedbackSink | undefined,
77
79
  connection?: DispatchConnection,
80
+ delivery?: "steer" | "followUp",
78
81
  ): Promise<boolean> {
79
82
  // Defensive: pi.getCommands() can throw on a stale ctx during dispose.
80
83
  let commands: Array<{ name: string; source?: string }> = [];
@@ -88,12 +91,13 @@ export async function tryDispatchExtensionCommand(
88
91
 
89
92
  if (!isExtensionSlashCommand(text, commands)) return false;
90
93
 
91
- emitFeedback(sink, sessionId, text, "started");
92
-
93
94
  // Path B (preferred when available): pi 0.71+ exposes dispatchCommand.
95
+ // Note: as of pi 0.74.1, dispatchCommand does NOT exist in the ExtensionAPI.
96
+ // This path is dead code until pi ships the API; preserved for future use.
94
97
  if (hasDispatchCommand(pi)) {
98
+ emitFeedback(sink, sessionId, text, "started");
95
99
  try {
96
- await (pi as any).dispatchCommand(text, { streamingBehavior: "followUp" });
100
+ await (pi as any).dispatchCommand(text, { streamingBehavior: delivery ?? "followUp" });
97
101
  emitFeedback(sink, sessionId, text, "completed");
98
102
  } catch (err: any) {
99
103
  const message = err instanceof Error ? err.message : String(err);
@@ -108,6 +112,7 @@ export async function tryDispatchExtensionCommand(
108
112
  // terminal event for this path — that would duplicate the reducer's
109
113
  // started→terminal upsert. See change: add-rpc-stdin-dispatch-with-keeper-sidecar.
110
114
  if (connection && isHeadlessRpcSession()) {
115
+ emitFeedback(sink, sessionId, text, "started");
111
116
  connection.send({
112
117
  type: "dispatch_extension_command",
113
118
  sessionId,
@@ -117,7 +122,17 @@ export async function tryDispatchExtensionCommand(
117
122
  return true;
118
123
  }
119
124
 
120
- // Path D (stopgap): no dispatchCommand and not headless (tmux / wt / unrecognized).
121
- emitFeedback(sink, sessionId, text, "error", PI_071_REQUIRED);
125
+ // Path D: No dispatchCommand, not headless (tmux / wt) or no connection.
126
+ // Extension commands can only be dispatched through the RPC keeper, which
127
+ // is available for headless sessions (`pi --mode rpc`). For tmux/wt sessions
128
+ // there is no injection channel — the command becomes a regular LLM message.
129
+ // To enable extension command dispatch for headless sessions:
130
+ // { "spawnStrategy": "headless", "useRpcKeeper": true }
131
+ // See change: fix-slash-dispatch-delivery.
132
+ const RPC_KEEPER_HINT =
133
+ "Extension slash commands cannot be dispatched from the dashboard for " +
134
+ "non-headless (tmux/wt) sessions. If you're using headless mode, add " +
135
+ '"useRpcKeeper": true to your dashboard config (~/.pi/dashboard/config.json).';
136
+ emitFeedback(sink, sessionId, text, "error", RPC_KEEPER_HINT);
122
137
  return true;
123
138
  }
@@ -11,16 +11,24 @@ import { readSessionMeta } from "@blackbelt-technology/pi-dashboard-shared/sessi
11
11
  * a .meta.json sidecar with source information.
12
12
  */
13
13
  export function detectSessionSource(hasUI?: boolean, sessionFile?: string): SessionSource {
14
- // Check for .meta.json sidecar written by the dashboard server
14
+ // A TUI is attached → the session is a CLI/TUI session, not headless,
15
+ // regardless of any .meta.json sidecar (which can be stamped "dashboard"
16
+ // by event-wiring's pendingDashboardSpawns by-cwd matcher when an
17
+ // unrelated dashboard Spawn for the same cwd happened around the same time).
18
+ if (hasUI) {
19
+ if (process.env.ZED_TERM) return "tui"; // pi TUI inside Zed's terminal
20
+ if (process.env.TMUX) return "tmux";
21
+ return "tui";
22
+ }
23
+
24
+ // No TUI attached → headless. Check for .meta.json sidecar written by
25
+ // the dashboard server when it spawned this session.
15
26
  if (sessionFile) {
16
27
  const meta = readSessionMeta(sessionFile);
17
28
  if (meta?.source === "dashboard") return "dashboard";
18
29
  }
19
30
 
20
- if (process.env.ZED_TERM) {
21
- if (hasUI) return "tui";
22
- return "zed";
23
- }
31
+ if (process.env.ZED_TERM) return "zed";
24
32
  if (process.env.TMUX) return "tmux";
25
33
  return "tui";
26
34
  }
@@ -11,8 +11,25 @@
11
11
  * See change: fix-provider-retry-infinite-loop.
12
12
  */
13
13
 
14
+ /**
15
+ * Matches terminal billing/quota error categories observed in production
16
+ * across providers. The orderer uses this to surface a synthesized
17
+ * `auto_retry_end{success:false}` BEFORE the bridge forwards `agent_end`,
18
+ * so the dashboard's `retryState` clears before `lastError` is set.
19
+ *
20
+ * Coverage (verified via fixture tests):
21
+ * - Codex / Anthropic / generic: usage_limit_reached, usage_not_included,
22
+ * quota_exceeded, credit_balance, insufficient_quota, monthly limit,
23
+ * daily limit, hourly limit, "reset after Nh|Nm|Ns".
24
+ * - Gemini / Google: "monthly spending cap", "spending cap",
25
+ * RESOURCE_EXHAUSTED.
26
+ * - Generic catch-all for "exceeded ... (quota|cap|spending)" within
27
+ * ~40 chars (avoids a string with no terminal-meaning context).
28
+ *
29
+ * See change: fix-retry-banner-stuck-on-limit-exceeded.
30
+ */
14
31
  export const USAGE_LIMIT_PATTERN =
15
- /usage[_ ]limit[_ ]reached|usage_not_included|quota[_ ]exceeded|monthly limit|hourly limit|reset after \d+[hms]/i;
32
+ /usage[_ ]limit[_ ]reached|usage_not_included|insufficient_quota|credit[_ ]balance|quota[_ ]exceeded|resource[_ ]exhausted|monthly[_ ]limit|monthly[_ ]spending[_ ]cap|hourly[_ ]limit|daily[_ ]limit|spending[_ ]cap|exceeded[^"]{0,40}(quota|cap|spending)|reset after \d+[hms]/i;
16
33
 
17
34
  export interface SyntheticEventEnvelope {
18
35
  eventType: "auto_retry_end";