/** * Handles server→extension messages by dispatching to pi API. */ import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, isAbsolute, join, relative, resolve } from "node:path"; import { resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js"; import { imageBlockData, imageBlockMime } from "@blackbelt-technology/pi-dashboard-shared/image-block.js"; import { diffOr } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js"; import type { ExtensionToServerMessage, InboundDropClass, ServerToExtensionMessage, } from "@blackbelt-technology/pi-dashboard-shared/protocol.js"; import { buildSkillBlock, parseSkillCommand } from "@blackbelt-technology/pi-dashboard-shared/skill-block-parser.js"; import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js"; import type { FileEntry, ImageContent, MissingToolError, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { filterHiddenCommands } from "./bridge-context.js"; import { draftCommitMessage } from "./commit-draft.js"; import { createInboundLimits, type InboundLimits } from "./inbound-limits.js"; import { errText, reportRefresh } from "./model-refresh.js"; import { killProcessByPgid } from "./process-scanner.js"; import { expandPromptTemplateFromDisk, loadPromptTemplate, readTemplate } from "./prompt-expander.js"; import { buildProviderCatalogue, toModelInfo } from "./provider-register.js"; import { resolveServerCliPath } from "./server-launcher.js"; import { filterByEnabledModels } from "./session-sync.js"; import { tryDispatchExtensionCommand } from "./slash-dispatch.js"; const IGNORE_DIRS = new Set([".git", "node_modules", ".next", "dist", "build", ".cache", "__pycache__", ".venv"]); const MAX_RESULTS = 50; /** Entries scanned budget — decoupled from the result cap so a deep first * subtree no longer starves shallow sibling matches. Softened from 4000 so * matches in later top-level subtrees of a large monorepo are no longer * dropped at the horizon; `.gitignore` pruning keeps the real per-walk cost * low despite the higher ceiling. * See change: fix-file-mention-search-ranking, split-editor-workspace. */ const MAX_VISITS = 20000; /** Depth guard, relaxed from 6 so deeply-nested source is reachable. * See change: split-editor-workspace. */ const MAX_DEPTH = 12; /** * Translate one `.gitignore` pattern into a matcher regex (best-effort — not * full gitignore semantics). Bare names match a path segment anywhere; slashed * patterns anchor at the root. `*`/`?` become segment-scoped globs. Negations * and comments are filtered before this is called. Mirrored in the server * content-grep JS fallback (`packages/server/src/lib/grep.ts`) — kept inline * rather than shared because the worktree resolves the shared package to the * main checkout. See change: split-editor-workspace. */ export function gitignoreToRegex(pattern: string): RegExp | null { let p = pattern.trim(); if (!p || p.startsWith("#") || p.startsWith("!")) return null; const anchored = p.startsWith("/"); p = p.replace(/^\/+/, "").replace(/\/+$/, ""); if (!p) return null; const esc = p .replace(/[.+^${}()|[\]\\]/g, "\\$&") .replace(/\*/g, "[^/]*") .replace(/\?/g, "[^/]"); const hasSlash = p.includes("/"); try { const body = anchored || hasSlash ? `^${esc}(/|$)` : `(^|/)${esc}(/|$)`; return new RegExp(body, "i"); } catch { return null; } } /** * Build a `.gitignore`-backed pruning predicate for `cwd`. Best-effort: a * missing or unreadable `.gitignore` yields a predicate that ignores nothing. * The returned fn receives a slash-normalised rel-path (no trailing slash). * See change: split-editor-workspace. */ export function loadGitignoreMatcher(cwd: string): (relPath: string) => boolean { let regexes: RegExp[] = []; try { const raw = readFileSync(join(cwd, ".gitignore"), "utf-8"); regexes = raw .split(/\r?\n/) .map((l) => gitignoreToRegex(l)) .filter((r): r is RegExp => r !== null); } catch { return () => false; } return (relPath: string) => regexes.some((re) => re.test(relPath)); } /** Score a leaf against a candidate using a precompiled regex (flat tiers). */ export function scoreRegexMatch(relPath: string, re: RegExp): number { const lower = relPath.toLowerCase(); const trimmed = lower.endsWith("/") ? lower.slice(0, -1) : lower; const base = trimmed.slice(trimmed.lastIndexOf("/") + 1); if (re.test(base)) return 2; if (re.test(trimmed)) return 1; return 0; } /** * Split a (lowercased) query at the LAST slash. The prefix (up to and * including that slash) scopes candidates; the leaf is ranked as a basename. * A query without a slash yields an empty prefix and the whole query as leaf. * See change: fix-file-mention-search-ranking. */ export function splitQuery(lowerQuery: string): { prefix: string; leaf: string } { const idx = lowerQuery.lastIndexOf("/"); if (idx === -1) return { prefix: "", leaf: lowerQuery }; return { prefix: lowerQuery.slice(0, idx + 1), leaf: lowerQuery.slice(idx + 1) }; } /** * Score `leaf` (lowercased) against a candidate `relPath`. Tiers, highest * first: 4 exact basename, 3 basename prefix, 2 basename substring, * 1 path substring (fallback). Empty leaf → 0 (depth tie-break decides). * Returns 0 for a non-empty leaf absent from both basename and path → dropped. * See change: fix-file-mention-search-ranking. */ export function scoreMatch(relPath: string, leaf: string): number { if (leaf === "") return 0; const lower = relPath.toLowerCase(); const trimmed = lower.endsWith("/") ? lower.slice(0, -1) : lower; const base = trimmed.slice(trimmed.lastIndexOf("/") + 1); if (base === leaf) return 4; if (base.startsWith(leaf)) return 3; if (base.includes(leaf)) return 2; if (lower.includes(leaf)) return 1; return 0; } /** * Walk `cwd` BREADTH-FIRST up to MAX_VISITS entries (depth ≤ 6, IGNORE_DIRS * skipped), collect every candidate that survives the slash-aware prefix * filter + leaf scoring, rank them (score desc, depth asc, pathLen asc, * alpha asc), and return at most MAX_RESULTS — the highest-ranked, not the * first reached. * * BFS (level-order queue) is load-bearing: it visits shallowest entries * first, so when MAX_VISITS bounds a large tree the budget spends on shallow * matches before deep ones. A depth-first walk would drain the budget inside * an early subtree (e.g. a huge `openspec/changes/archive/`) and starve * shallow siblings like root `package.json` — the exact failure the * file-autocomplete anti-starvation requirement forbids. * See change: fix-file-mention-search-ranking. */ export function searchFiles(cwd: string, query: string, opts?: { regex?: boolean }): FileEntry[] { const lowerQuery = query?.toLowerCase() ?? ""; const { prefix, leaf } = splitQuery(lowerQuery); // Optional regexp leaf: compile once, degrade to substring on an invalid // pattern so a half-typed regex never errors the walk. See change: // split-editor-workspace. let leafRe: RegExp | null = null; if (opts?.regex && leaf !== "") { try { leafRe = new RegExp(leaf, "i"); } catch { leafRe = null; } } const isIgnored = loadGitignoreMatcher(cwd); const candidates: Array<{ path: string; isDirectory: boolean; depth: number; score: number }> = []; let visits = 0; const queue: Array<{ dir: string; depth: number }> = [{ dir: cwd, depth: 0 }]; while (queue.length > 0 && visits < MAX_VISITS) { const { dir, depth } = queue.shift()!; if (depth > MAX_DEPTH) continue; let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; } for (const entry of entries) { if (visits >= MAX_VISITS) break; if (IGNORE_DIRS.has(entry.name)) continue; const fullPath = join(dir, entry.name); const isDirectory = entry.isDirectory(); const relNoSlash = relative(cwd, fullPath).replace(/\\/g, "/"); // `.gitignore` pruning: skip ignored files and do not descend ignored // dirs, so the visit budget is spent on real source. if (isIgnored(relNoSlash)) continue; visits++; const relPath = relNoSlash + (isDirectory ? "/" : ""); const inScope = !prefix || relPath.toLowerCase().includes(prefix); if (inScope) { const score = leafRe ? scoreRegexMatch(relPath, leafRe) : scoreMatch(relPath, leaf); if (leaf === "" || score > 0) { candidates.push({ path: relPath, isDirectory, depth, score }); } } if (isDirectory) queue.push({ dir: fullPath, depth: depth + 1 }); } } // Empty leaf (bare `@`): every entry scores 0, so order by depth then // alphabetically per the bare-@ requirement (pathLen tie-break omitted). // Non-empty leaf: full ranking tie-break score→depth→pathLen→alpha. candidates.sort((a, b) => b.score - a.score || a.depth - b.depth || (leaf === "" ? 0 : a.path.length - b.path.length) || a.path.localeCompare(b.path) ); return candidates.slice(0, MAX_RESULTS).map((c) => ({ path: c.path, isDirectory: c.isDirectory })); } /** * Outcome of a bridge-side `/reload` attempt. * * `ok: false` carries the operator-facing reason so the terminal * `command_feedback` says WHY nothing reloaded instead of claiming success. * `handedOff` means the terminal feedback is owned by someone else — the * bridge instance loaded by an in-process reload reports `completed` after it * re-registers — so the requesting side must emit nothing. * * See change: fix-out-of-band-reload, fix-terminal-session-dashboard-reload. */ export type ReloadOutcome = | { ok: true; handedOff?: false } | { ok: true; handedOff: true } | { ok: false; reason: string }; /** Reason emitted when the bridge has no reload path for this session. */ const NO_RELOAD_PATH_REASON = "No dashboard reload path for this session — run /reload in the pi TUI."; /** A dashboard reload for this session is still in flight. */ export const RELOAD_IN_PROGRESS_REASON = "A reload is already in progress for this session."; /** The self-dispatched reload command never reached its handler. */ export const RELOAD_DID_NOT_RUN_REASON = "The reload command did not run — is the dashboard extension still loaded? See the pi terminal."; /** `ctx.reload()` settled without pi re-running `session_start{reason:"reload"}`. */ export const PI_DID_NOT_RELOAD_REASON = "pi did not reload — session busy or reload failed; see the pi terminal."; /** The pending-reload slot vanished or was replaced before completion was proven. */ export const RELOAD_SUPERSEDED_REASON = "The reload was superseded before completion could be confirmed — see the pi terminal."; /** The reload did not finish within the bridge's bound. */ export const RELOAD_TIMEOUT_REASON = "The reload did not finish within 60 s — see the pi terminal."; /** Parsed result from parseSendPrompt */ export type ParsedPrompt = | { type: "bash"; command: string; excludeFromContext: boolean } | { type: "compact"; customInstructions: string | undefined } | { type: "model"; provider: string; modelId: string } | { type: "shutdown" } | { type: "reload" } | { type: "new" } | { type: "retry" } | { type: "mgmt"; event: string; data: Record } | { type: "slash"; text: string } | { type: "passthrough"; text: string }; /** pi-flows management commands with known event mappings. * These are dispatched via pi.events instead of flow:run. * Flow management commands (flows:new, flows:edit, flows:delete) are * handled in bridge.ts sessionPrompt callback which passes cachedCtx * as fallback context for headless sessions. */ const MANAGEMENT_COMMAND_EVENTS: Record Record; }> = {}; /** * Team sessions (add-team-plugin D7): the guard extension confines TOOL calls, but a prompt the bridge * turns into a host action (`!cmd` bash, `/slash` extension commands, reload, new, model, shutdown, * management) never reaches `tool_call`. Such a session's owner could run unconfined bash by typing * `!id`. The spawn projects `PI_EXT_TEAM_TOOLS` into the pi process, so the bridge refuses those routes * there; plain prompts, `/compact` and the dashboard-internal retry stay available. */ export function isTeamConfinedSession(env: NodeJS.ProcessEnv = process.env): boolean { return typeof env.PI_EXT_TEAM_TOOLS === "string"; } const TEAM_ALLOWED_PARSED: ReadonlySet = new Set(["passthrough", "compact", "retry"]); /** * Outcome of the team-session `/skill:` resolution (design D12, * add-team-skill-access): the text is not a skill command, it expands to the * standard skill envelope, or it is refused. */ type TeamSkillResolution = | { kind: "not-skill" } | { kind: "envelope"; text: string } | { kind: "refused" }; /** * Parse the effective team skill set from `PI_EXT_TEAM_SKILLS` — the JSON * string `[{name, root}]` the team-plugin spawn always projects (design D7, * add-team-skill-access), `"[]"` when the persona has no skills. Missing, * unparseable or wrong-shaped input ⇒ the empty set (fail closed), matching * the team guard's `policyFromEnv`. */ function teamSkillPolicy(env: NodeJS.ProcessEnv = process.env): Array<{ name: string; root: string }> { let parsed: unknown; try { parsed = JSON.parse(env.PI_EXT_TEAM_SKILLS ?? ""); } catch { return []; } if (!Array.isArray(parsed)) return []; const skills: Array<{ name: string; root: string }> = []; for (const entry of parsed) { if (!entry || typeof entry !== "object") return []; const { name, root } = entry as Record; if (typeof name !== "string" || !name || typeof root !== "string" || !root) return []; skills.push({ name, root }); } return skills; } /** A granted SKILL.md larger than this is refused rather than read unbounded (audit F6). */ const TEAM_SKILL_MD_MAX_BYTES = 256 * 1024; /** * Resolve a `/skill:` command in a team-confined session (design D12, * add-team-skill-access). A granted name expands from its own granted root — * `readTemplate` + `buildSkillBlock` on `/SKILL.md` — into the standard * envelope, byte-identical to the non-team `expandPromptTemplateFromDisk` * expansion of the same file, so `parseSkillBlock` and the skill card keep * working. Anything else — an ungranted name, an unreadable `SKILL.md`, one * swapped for a symlink that leaves the granted root (audit F2), or one above * the read cap (audit F6) — is refused: the caller settles the prompt with an * error and never queues it. Never consults the local cwd scan or the pi * command registry. */ function resolveTeamSkill(text: string, env: NodeJS.ProcessEnv = process.env): TeamSkillResolution { const cmd = parseSkillCommand(text); if (!cmd) return { kind: "not-skill" }; const granted = teamSkillPolicy(env).find((e) => e.name === cmd.name); if (!granted) return { kind: "refused" }; try { const skillMdPath = join(granted.root, "SKILL.md"); // The file may have been swapped for a symlink after the grant: resolve both and refuse // unless SKILL.md still canonicalises INSIDE the canonical root (audit F2). const rootReal = realpathSync.native(granted.root); const mdReal = realpathSync.native(skillMdPath); const rel = relative(rootReal, mdReal); if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("team: skill file left the granted root"); // Unbounded reads are refused, not truncated (audit F6). if (statSync(mdReal).size > TEAM_SKILL_MD_MAX_BYTES) throw new Error("team: skill file too large"); // `readTemplate` strips frontmatter + trims exactly like pi's own // `_expandSkillCommand`; `buildSkillBlock` reproduces its envelope bytes. const { body } = readTemplate(skillMdPath); return { kind: "envelope", text: buildSkillBlock({ name: cmd.name, filePath: skillMdPath, baseDir: dirname(skillMdPath), body, userArgs: cmd.args || undefined, }), }; } catch { // Granted file deleted after spawn — no fallback, refuse. return { kind: "refused" }; } } /** Parse input text to detect pi internal command prefixes */ export function parseSendPrompt(text: string): ParsedPrompt { // 1. Check !! (must check before !) if (text.startsWith("!!")) { const command = text.slice(2).trim(); if (!command) return { type: "passthrough", text }; return { type: "bash", command, excludeFromContext: true }; } // 2. Check ! if (text.startsWith("!")) { const command = text.slice(1).trim(); if (!command) return { type: "passthrough", text }; return { type: "bash", command, excludeFromContext: false }; } // 3. Check /compact if (text === "/compact" || text.startsWith("/compact ")) { const args = text.startsWith("/compact ") ? text.slice(9).trim() : undefined; return { type: "compact", customInstructions: args || undefined }; } // 4. Check /quit and /exit if (text === "/quit" || text === "/exit") { return { type: "shutdown" }; } // 4b. Check /reload if (text === "/reload") { return { type: "reload" }; } // 4c. Check /new if (text === "/new") { return { type: "new" }; } // 4d. Dashboard-internal settled-error retry. Hidden from command lists; // triggers a non-user custom turn through pi.sendMessage. if (text === "/__dashboard_retry") { return { type: "retry" }; } // 4e. Check /model if (text.startsWith("/model ")) { const modelStr = text.slice(7).trim(); const slashIdx = modelStr.indexOf("/"); if (slashIdx > 0) { return { type: "model", provider: modelStr.slice(0, slashIdx), modelId: modelStr.slice(slashIdx + 1) }; } } // 5. Check management commands (/flows:new, etc.) with known event mappings if (text.startsWith("/") && !text.includes("\n")) { const cmdText = text.slice(1); const spaceIdx = cmdText.indexOf(" "); const cmdName = spaceIdx === -1 ? cmdText : cmdText.slice(0, spaceIdx); const cmdArgs = spaceIdx === -1 ? "" : cmdText.slice(spaceIdx + 1); const mgmt = MANAGEMENT_COMMAND_EVENTS[cmdName]; if (mgmt) { return { type: "mgmt", event: mgmt.event, data: mgmt.dataFn(cmdArgs) }; } } // 6. Check / prefix (generic slash command) if (text.startsWith("/") && !text.includes("\n")) { return { type: "slash", text }; } // 5. Passthrough return { type: "passthrough", text }; } const BASH_TIMEOUT = 30_000; export interface CommandHandler { handle(msg: ServerToExtensionMessage): ExtensionToServerMessage | undefined | Promise; } export function createCommandHandler( pi: ExtensionAPI, sessionIdOrGetter: string | (() => string), options?: { getModelRegistry?: () => any; /** * Process-wide inbound bounds (bash concurrency + prompt bucket). The * bridge passes its single instance so the allowance survives `/reload`; * absent → a handler-local one built from the environment. * See change: harden-bridge-inbound-and-discovery (D17). */ limits?: InboundLimits; /** Re-sync dashboard-registered providers from providers.json (bridge wires * `reloadProviders(pi)`). Awaited by `request_models` before the registry * refresh. See change: refresh-models-on-provider-change (D1). */ reloadProviders?: () => Promise; /** * Ephemeral fork-subagent driver for AI-drafted commit messages: run one * throwaway in-memory agent turn on `seed` and resolve with the assistant * text. Wired from bridge.ts (has model/registry/authStorage). Absent → * the draft ladder falls to the deterministic stub. Never appends to the * visible conversation. See change: add-session-uncommitted-indicator-and-commit. */ runDraftAgent?: (seed: string, cwd: string) => Promise; /** Compact text of the live session context for the draft seed. */ getSessionContextText?: () => string | undefined; setThinkingLevel?: (level: string) => void; getThinkingLevel?: () => string | undefined; shutdown?: () => void; /** * Full bridge wrapper-abort. Runs the queue clears, shadow reset, * `cachedCtx.abort()`, and `retryTracker.noteAbort`. Invoked exactly * once on the initial user-abort command. Subsequent persistent-abort * scheduler ticks invoke `rawAbort` instead to avoid re-running the * wrapper's side-effects on every tick. * See change: unify-status-banner-and-terminal-limit-stop. */ abort?: () => void; /** * Raw `cachedCtx.abort()` only. Used by the persistent-abort scheduler * after the initial wrapper-abort has run, so repeated ticks do not * re-clear pi queues or reset bridge shadows. Closes the spec/impl * drift where the scheduler previously re-ran the full wrapper. * See change: unify-status-banner-and-terminal-limit-stop. */ rawAbort?: () => void; /** * Probe agent idleness for the persistent-abort scheduler. * See change: fix-provider-retry-infinite-loop. */ isIdle?: () => boolean; getCwd?: () => string; /** Callback to send events (e.g., bash_output, command_feedback) back to server */ eventSink?: (msg: ExtensionToServerMessage) => void; /** * Report an inbound message this handler threw away. The mismatch guard * lives inside `handle()`, which holds no connection reference, so the * channel is injected. See change: fix-spawn-correlation-ttl-coupling (D6). */ reportInboundDrop?: (drop: { dropClass: InboundDropClass; messageType?: string; droppedSessionId?: string; }) => void; /** Trigger context compaction */ compact?: (options: { customInstructions?: string }) => void; /** * Trigger session reload (extensions, settings, skills, etc.). * * Returns whether a reload ACTUALLY ran, so the caller never emits an * unconditional `completed`. The bridge self-dispatches its * `/__dashboard_reload ` command in-process and * resolves `{ok:true, handedOff:true}` on success: the RELOADED bridge * instance reports `completed` after re-registering, because this * instance's connection is torn down by the reload. On `handedOff` the * handler emits nothing. * * ASYNC by contract: a rejection that lands after we have already * emitted `completed` would be a false success. The handler awaits it. * See change: fix-out-of-band-reload (design.md D5), * fix-terminal-session-dashboard-reload (D4). */ reload?: () => Promise; /** Spawn a new session in the same cwd */ spawnNew?: () => void; /** Switch model via pi.setModel() */ setModel?: (provider: string, modelId: string) => Promise; /** * Route slash commands through pi's command system. May be sync or async. * In bridge wiring this also runs the extension-command dispatch branch * (see slash-dispatch.ts). The handler awaits the result so command_feedback * events emitted by the dispatch path arrive before this turn returns. * See change: fix-extension-slash-commands-in-dashboard. */ sessionPrompt?: ( text: string, delivery?: "steer" | "followUp", promptId?: string, ) => void | Promise; /** * Bridge-shadow-queue hooks: called AFTER pi accepts the user message, * gated by `isStreaming()` captured BEFORE the send. The capture order * matters — `pi.sendUserMessage` on an idle session synchronously * triggers `agent_start`, which flips bridge state to streaming. Checking * AFTER the send would mis-record idle sends as chip entries. * Pi doesn't expose `queue_update` to extensions, so the bridge is the * source of truth. See change: add-followup-edit-and-steer-cancel. */ onSteerSent?: (text: string) => void; /** * `images` carries the attachments sent with a buffered follow-up. Passing * them is what makes the bridge buffer able to deliver them on drain; * dropping them here was the original bug. * See change: fix-bridge-followup-image-drop. */ onFollowupSent?: (text: string, images?: unknown) => void; /** * Returns true iff the agent was streaming at the moment of the call. * Used to capture pre-send streaming state before `pi.sendUserMessage` * runs (which may flip the flag synchronously via agent_start). * See change: add-followup-edit-and-steer-cancel. */ isStreaming?: () => boolean; /** * Mirror a server `attach_proposal_changed` push into the bridge's * `BridgeContext.attachedChange`. The `before_agent_start` injector reads * that field to build the per-turn system-prompt fragment. Foreign-session * messages are already dropped by the sessionId guard at the top of * `handle`. See change: inject-session-context-into-agent. */ onAttachProposalChanged?: (attachedChange: string | null) => void; /** * A dashboard SYSTEM rename (`rename_session{origin:"system"}`) is about to * be applied. Called BEFORE `pi.setSessionName` so the namer records the * `system` provenance and the echo is not misread as a user rename. Returns * a rollback invoked if `setSessionName` throws. See change: * investigate-auto-name-provenance-relabel (D3). */ onSystemRename?: (name: string) => (() => void) | void; /** * A non-system (user) `rename_session` is about to be applied: the namer * clears its system-echo witness so the echo classifies external (`user`). */ onUserRename?: () => void; /** * Clear the bridge's abort latch. Called at the start of `send_prompt` * (before pi.sendUserMessage) so a deliberate new turn is never aborted * by a latch left set from a prior user abort. See change: * unify-error-retry-lifecycle. */ noteUserPrompt?: () => void; /** * Disarm a still-armed provider-retry chain before a manual retry re-drive * (bridge wires this to `retryTracker.noteExplicitRun`). Without it the * manual turn's native `agent_start` is converted into a synthetic * `auto_retry_start`, rendering pi's attempt counter for a user-initiated * retry. See change: replace-dashboard-retry-command-with-protocol-message. */ disarmRetryChain?: () => void; }, ): CommandHandler { const getSessionId = typeof sessionIdOrGetter === "function" ? sessionIdOrGetter : () => sessionIdOrGetter; /** * Persistent-abort scheduler. Re-invokes `options.rawAbort()` (NOT the * full wrapper-abort) at 200ms intervals for up to 2 seconds, breaking * early when (a) `opts.isStreaming()` transitions from true at scheduler * start to false (i.e. agent_end for the aborted turn has flipped the * bridge state), OR (b) `opts.isIdle()` returns true, OR (c) 2s elapsed. * * Closes the retry race window in pi-coding-agent (`_retryAbortController` * is briefly `undefined` between sleep-end and the next `agent.continue()` * call) without clobbering user prompts sent within the 2s window. * * See change: fix-provider-retry-infinite-loop (original scheduler). * See change: unify-status-banner-and-terminal-limit-stop (rawAbort + * streaming-transition break). */ const PERSISTENT_ABORT_INTERVAL_MS = 200; const PERSISTENT_ABORT_MAX_MS = 2000; function schedulePersistentAbort(opts: NonNullable): void { if (!opts.rawAbort) return; const startedAt = Date.now(); const wasStreamingAtStart = opts.isStreaming?.() === true; const interval = setInterval(() => { if (Date.now() - startedAt >= PERSISTENT_ABORT_MAX_MS) { clearInterval(interval); return; } // Break on the agent settling: once streaming flips back to false // (agent_end for the aborted turn processed), persistent-abort has // nothing left to do, and continuing would risk killing any new // turn the user re-started within the window. if (wasStreamingAtStart && opts.isStreaming?.() === false) { clearInterval(interval); return; } try { if (opts.isIdle?.()) { clearInterval(interval); return; } } catch { /* probe failure — keep trying */ } try { opts.rawAbort?.(); } catch { /* idempotent */ } }, PERSISTENT_ABORT_INTERVAL_MS); } const limits = options?.limits ?? createInboundLimits(); return { async handle(msg: ServerToExtensionMessage): Promise { const sessionId = getSessionId(); // Ignore messages for other sessions (skip session-less messages like heartbeat_ack) if ((msg as any).sessionId !== undefined && (msg as any).sessionId !== sessionId) { console.error(`[dashboard] Ignoring message type=${msg.type} for session ${(msg as any).sessionId}, current session is ${sessionId}`); // This `console.error` is written to /dev/null whenever // `keeperLog.capturePiOutput` is false (the default), so the drop is // ALSO reported over the socket. The guard cannot tell "never mine" // from "was mine, since replaced" — one reportable class. // See change: fix-spawn-correlation-ttl-coupling (D6). options?.reportInboundDrop?.({ dropClass: "session_mismatch", messageType: msg.type, droppedSessionId: (msg as any).sessionId, }); return undefined; } switch (msg.type) { case "send_prompt": { // Team-confined sessions: the shared parseSkillCommand rule runs // FIRST — before parseSendPrompt routing and before any // streaming/follow-up buffering (design D12, add-team-skill-access). // A granted command expands from its granted root into the standard // envelope and rides the normal delivery routing below; a refused // command (ungranted name, unreadable SKILL.md) settles the // optimistic bubble with an inline error and is never queued. // Team sessions never reach expandPromptTemplateFromDisk, the // extension dispatch, exec templates or sessionPrompt. const teamSkill: TeamSkillResolution = isTeamConfinedSession() ? resolveTeamSkill(msg.text) : { kind: "not-skill" }; if (teamSkill.kind === "refused") { options?.eventSink?.({ type: "prompt_received", sessionId, fresh: false }); options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: { command: "skill", status: "error", message: "skill not available" }, }, }); return undefined; } // A granted team /skill: is forced through the passthrough delivery // tail with the envelope as the outgoing text — never the slash // route (sessionPrompt / extension dispatch / exec templates). const parsed: ParsedPrompt = teamSkill.kind === "envelope" ? { type: "passthrough", text: teamSkill.text } : parseSendPrompt(msg.text); if (isTeamConfinedSession() && !TEAM_ALLOWED_PARSED.has(parsed.type)) { options?.eventSink?.({ type: "prompt_received", sessionId, fresh: false }); return undefined; } // Non-turn commands (bash/compact/shutdown/reload/new/model/mgmt) // return early below and never produce a user `message_start`, so an // optimistic idle `pendingPrompt` bubble would hang until the 30s // safety timeout. Settle it immediately (fresh:false → drop). The // passthrough + slash paths emit their own `prompt_received` with the // real streaming verdict. See change: optimistic-prompt-progress. // The `promptId` echo means ONE narrow thing — the owning bridge // handed this prompt to pi — so it rides only the ack emitted AFTER // an actual `pi.sendUserMessage`. The acks below are UI-state signals // for non-turn commands and for the buffered follow-up path (pi never // sees those), and attaching the handle to them would report a // delivery that did not happen. // See change: fix-spawn-correlation-ttl-coupling (D7). if (parsed.type !== "passthrough" && parsed.type !== "slash") { options?.eventSink?.({ type: "prompt_received", sessionId, fresh: false }); } // Route based on parsed command type if (parsed.type === "bash") { await handleBashCommand(pi, sessionId, parsed.command, parsed.excludeFromContext, options?.eventSink, undefined, limits); return undefined; } if (parsed.type === "compact") { await handleCompactCommand(sessionId, parsed.customInstructions, options?.compact, options?.eventSink); return undefined; } if (parsed.type === "shutdown") { if (options?.shutdown) { options.shutdown(); } return undefined; } if (parsed.type === "reload") { // Emit the REAL outcome. The previous unconditional `completed` // reported success for every reload that silently no-op'd on a // session with no captured reload function — which is every // dashboard-spawned session that was never touched in a TUI. // See change: fix-out-of-band-reload. let outcome: ReloadOutcome = { ok: false, reason: NO_RELOAD_PATH_REASON }; if (options?.reload) { // Defence in depth: the bridge already converts a throw into an // outcome, but a stale captured `ctx.reload` throws // SYNCHRONOUSLY out of `assertActive()`, and any caller wiring a // different `reload` must not be able to take the turn down. try { outcome = await options.reload(); } catch (err: any) { const reason = err instanceof Error ? err.message : String(err); outcome = { ok: false, reason: `Reload failed: ${reason}` }; } } // The reloaded bridge owns the terminal feedback. // See change: fix-terminal-session-dashboard-reload (D4). if (outcome.ok && outcome.handedOff) return undefined; options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: outcome.ok ? { command: "/reload", status: "completed" } : { command: "/reload", status: "error", message: outcome.reason }, }, }); return undefined; } if (parsed.type === "new") { if (options?.spawnNew) { options.spawnNew(); } options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: { command: "/new", status: "completed" }, }, }); return undefined; } if (parsed.type === "retry") { // Deprecated `/__dashboard_retry` sentinel alias: an un-upgraded // client still smuggles retry through send_prompt. Route it to the // SAME dispatch as the typed retry_session, never replaying the // sentinel as a user message. Remove one release after clients are // known upgraded. See change: // replace-dashboard-retry-command-with-protocol-message. dispatchDashboardRetry(pi, sessionId, options); return undefined; } if (parsed.type === "model") { if (options?.setModel) { await options.setModel(parsed.provider, parsed.modelId); } options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: { command: `/model ${parsed.provider}/${parsed.modelId}`, status: "completed" }, }, }); return undefined; } if (parsed.type === "mgmt") { // Dispatch management command via pi.events (e.g. flows:new-request) if ((pi as any).events) { (pi as any).events.emit(parsed.event, parsed.data); } options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: { command: parsed.event, status: "completed" }, }, }); return undefined; } if (parsed.type === "slash") { if (options?.sessionPrompt) { // sessionPrompt (bridge) owns slash-dispatch + flow fast-path + // template expansion. It also owns command_feedback emission for // extension-command dispatch. Do NOT emit completed here — would // duplicate the dispatch path's terminal event. // See change: fix-extension-slash-commands-in-dashboard. // The handle rides along so the branch that actually reaches // `pi.sendUserMessage` can acknowledge it; the non-turn slash // routes (flow, extension dispatch, exec template) settle without // one, because pi never receives those as a prompt. // See change: fix-spawn-correlation-ttl-coupling (D7). await options.sessionPrompt(parsed.text, msg.delivery, msg.promptId); } else { // Test / non-bridge callers: apply the extension-command dispatch // branch inline before falling through to sendUserMessage. Keeps // both call sites in lockstep per spec routing-step 9. const handled = await tryDispatchExtensionCommand( pi, parsed.text, sessionId, options?.eventSink, msg.delivery, ); // Exec-mode slash template (executable: bash): run as bash, no LLM. // Runs AFTER extension dispatch, BEFORE the sendUserMessage // fallback (disjoint by construction — see spec routing // precedence). See change: add-dashboard-slash-commands. const ranExec = !handled && (await tryExecSlashTemplate(pi, parsed.text, process.cwd(), sessionId, options?.eventSink, limits)); if (!handled && !ranExec) { // sendUserMessage exempt from gating: only typed single-line // slashes that are NOT extension commands reach this — i.e. // skills, prompt templates, unrecognized slashes. // Forward delivery so steering on slash fallback honors the // dashboard's keyboard contract. See change: add-steering-message. const deliverAs = msg.delivery ?? ("followUp" as const); // Capture the streaming verdict BEFORE the pi call: an idle // send synchronously fires `agent_start`, so reading it // afterwards reports `fresh:false` for every fresh turn — the // same trap the passthrough path documents. const wasStreamingBeforeSend = options?.isStreaming?.() ?? false; (pi.sendUserMessage as any)(parsed.text, { deliverAs }); // This slash DID reach pi as a user prompt, so it is delivered. // See change: fix-spawn-correlation-ttl-coupling (D7). if (msg.promptId) { options?.eventSink?.({ type: "prompt_received", sessionId, fresh: !wasStreamingBeforeSend, promptId: msg.promptId, }); } } } return undefined; } // Passthrough: send as regular user message (with image handling). // Multi-line slash commands (e.g. "/skill:foo\nuser text") are classified as // passthrough by parseSendPrompt to preserve images (the slash route strips them), // so we expand prompt templates / skills here before sending. // // sendUserMessage exempt from extension-dispatch gating: this path handles // multi-line slashes and image-bearing messages. Per spec, only typed // single-line slash text gates through extension dispatch — multi-line and // image-bearing messages go raw to the LLM as before. // See change: fix-extension-slash-commands-in-dashboard. // A real user turn WILL be dispatched on this passthrough path — clear // any latched abort BEFORE pi.sendUserMessage (which can fire // agent_start synchronously) so the new turn is never aborted by the // latch. Placed here (not at the top of send_prompt) so non-turn // commands (bash, compact, model, mgmt, slash dispatch/exec) do NOT // disarm the latch — they never start a replacement turn. // See change: unify-error-retry-lifecycle. options?.noteUserPrompt?.(); let outgoing = teamSkill.kind === "envelope" ? teamSkill.text : msg.text; if (outgoing.startsWith("/") && !isTeamConfinedSession()) { // Team-confined sessions never resolve templates from disk or the // registry (design D12, add-team-skill-access): their multi-line // `/` text is sent verbatim — only `/skill:` expands (above), // `/compact` keeps its own route, other single-line slashes stay // dropped as before. outgoing = expandPromptTemplateFromDisk(outgoing, process.cwd(), pi); } // Route the prompt based on delivery + streaming state: // // delivery="followUp" + streaming → ONLY notify bridge buffer // (pi never sees it until // drainFollowupQueue ships it // on agent_settled as a fresh turn). // delivery="steer" + streaming → forward to pi + shadow-record. // any delivery + idle → forward to pi (fresh turn). // // Capture pre-send streaming state BEFORE any pi call — pi flips // idle→streaming synchronously on the first user message, so // checking after sendUserMessage gives false positives. // // Image attachments RIDE the bridge buffer and are delivered on // drain. See change: rework-mid-turn-prompt-queue (design.md D1), // fix-bridge-followup-image-drop. const wasStreaming = options?.isStreaming?.() ?? false; // Per-send ack carrying the capture-before-send streaming verdict. // Drives the optimistic `pendingPrompt` bubble: fresh:true → "sent", // fresh:false → drop (raced mid-turn). Emitted BEFORE any pi call so // the snapshot is authoritative. See change: optimistic-prompt-progress. const da = msg.delivery ?? "followUp"; const buffered = wasStreaming && da === "followUp"; // The streaming-verdict ack is unchanged and still emitted BEFORE any // pi call, so the snapshot stays authoritative. It carries the // `promptId` ONLY on the branch that actually hands the prompt to pi; // a buffered follow-up stays `transmitted` until (and unless) the // drain ships it, which is the same honest degradation an older // bridge gets. See change: optimistic-prompt-progress, // fix-spawn-correlation-ttl-coupling (D7). options?.eventSink?.({ type: "prompt_received", sessionId, fresh: !wasStreaming, ...(msg.promptId && !buffered ? { promptId: msg.promptId } : {}), }); if (buffered) { // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The // images ride into the buffer so the drain can deliver them. // See change: fix-bridge-followup-image-drop. options?.onFollowupSent?.(outgoing, msg.images); } else { // Idle or steer — forward to pi directly. sendUserMessageWithImages(pi, outgoing, msg.images, msg.delivery); if (wasStreaming && da === "steer") options?.onSteerSent?.(outgoing); } return undefined; } case "retry_session": // First-class settled-error retry. Same dispatch as the deprecated // /__dashboard_retry sentinel, minus the send_prompt channel abuse. // See change: replace-dashboard-retry-command-with-protocol-message. dispatchDashboardRetry(pi, sessionId, options); return undefined; case "abort": // Pi owns both queues now. abort() asks pi to halt the current turn; // pi's native drain logic handles any remaining queue entries naturally. // See change: add-followup-edit-and-steer-cancel. if (options?.abort) { options.abort(); } // Synthesize an immediate auto_retry_end so the dashboard clears // any in-flight retry banner without waiting for pi's natural // auto_retry_end (which is delayed by the abortable-sleep cancel // window AND, on extension API, never reaches us at all — see // https://github.com/badlogic/pi-mono/discussions/2073). The // reducer no-ops auto_retry_end when retryState is undefined, // so this is idempotent against later events. // // No `finalError` is supplied: the placeholder "Aborted by user" // previously overwrote SessionState.lastError, hiding the real // provider error (e.g. usage_limit_reached). The orderer's pending // flag now survives wrapper-abort, so pi's terminal agent_end can // still synthesize a proper finalError carrying the real message. // See change: unify-status-banner-and-terminal-limit-stop. if (options?.eventSink) { options.eventSink({ type: "event_forward", sessionId, event: { eventType: "auto_retry_end", timestamp: Date.now(), data: { success: false, attempt: -1 }, }, }); } // Persistent-abort scheduler: pi-coding-agent's _retryAbortController // is briefly `undefined` between sleep-end and the next // agent.continue() call. An abort that arrives in that window is // a no-op against the retry. Re-invoke abort every 200ms for up // to 2s, breaking early when the agent is idle. // See change: fix-provider-retry-infinite-loop. if (options) schedulePersistentAbort(options); return undefined; case "request_commands": { const commands = filterHiddenCommands(pi.getCommands()); // Also send flows list alongside commands if (options?.eventSink) { const probe: any = {}; try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ } options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] }); } return { type: "commands_list", sessionId, commands, }; } case "list_files": { // `regex` is optional (editor filename search); absent for `@`-mention. const files = searchFiles(process.cwd(), msg.query, { regex: msg.regex }); return { type: "files_list", sessionId, query: msg.query, files, }; } case "git_commit_draft": { // AI-draft a commit message from the session's own context + the // staged diff, via an ephemeral fork-subagent. Never touches the // visible conversation. Always resolves (worst case: stub). // See change: add-session-uncommitted-indicator-and-commit. const draftMsg = msg as { requestId: string; cwd: string; files: string[]; }; const cwd = draftMsg.cwd || options?.getCwd?.() || process.cwd(); // Guard against a malformed payload: `files` must be an array of // strings before we map over it. Coerce to a safe empty list so the // draft ladder falls to its deterministic stub rather than throwing. const draftFiles = Array.isArray(draftMsg.files) ? draftMsg.files.filter((f): f is string => typeof f === "string") : []; const result = await draftCommitMessage({ files: draftFiles, buildDiff: () => draftFiles.map((f) => diffOr({ cwd, path: f })).join("\n"), buildContext: () => options?.getSessionContextText?.(), runAgent: options?.runDraftAgent ? (seed) => options.runDraftAgent!(seed, cwd) : undefined, }); return { type: "git_commit_draft_result", sessionId, requestId: draftMsg.requestId, message: result.message, source: result.source, }; } // openspec_refresh removed — server handles directly via DirectoryService case "attach_proposal_changed": // The top-of-handle guard only drops MISMATCHED sessionIds; a payload // with no sessionId falls through. Require an exact match so an // unscoped message cannot mutate the active bridge's attached change. if (msg.sessionId !== sessionId) { console.error("[dashboard] Ignoring attach_proposal_changed: missing/mismatched sessionId"); return undefined; } // Validate the socket payload shape before mirroring into // BridgeContext.attachedChange. See change: inject-session-context-into-agent. if (msg.attachedChange !== null && typeof msg.attachedChange !== "string") { console.error("[dashboard] Ignoring attach_proposal_changed: attachedChange must be string|null"); return undefined; } options?.onAttachProposalChanged?.(msg.attachedChange); return undefined; case "rename_session": { let rollback: (() => void) | void = undefined; if (msg.origin === "system") rollback = options?.onSystemRename?.(msg.name); else options?.onUserRename?.(); try { pi.setSessionName(msg.name); } catch (err) { rollback?.(); throw err; } return { type: "session_name_update", sessionId, name: msg.name, }; } case "request_models": { const registry = options?.getModelRegistry?.(); if (registry) { try { // Heal a missed credentials_updated broadcast: re-diff // providers.json before refreshing. Failure is degraded, not // fatal. See change: refresh-models-on-provider-change (D1). try { await options?.reloadProviders?.(); } catch (err) { console.warn("[dashboard] request_models providers re-sync failed:", errText(err)); } registry.authStorage?.reload?.(); // pi 0.84.0: refresh() is async and returns { aborted, errors }. // Await it -- the pre-0.84 fire-and-forget read the catalogue // before the refresh resolved. Report the outcome instead of // discarding it: a partly-failed refresh still yields a usable // (stale) catalogue, so we log and continue rather than throw. // See change: update-pi-core-0-84-adopt-apis. // Local only: selector open must never fetch remote catalogues on the // serialized pump. See change: refresh-models-on-provider-change (D3). const refreshResult = await reportRefresh(registry.refresh({ allowNetwork: false })); const models = filterByEnabledModels(registry.getAvailable().map(toModelInfo)); // Per-provider failures travel to the browser so the dropdown can // say WHY a model is missing. Omitted (never `[]`) on success so // the happy-path message is byte-identical to before. // // An ABORTED refresh never populates the field, even when it also // carries provider errors: the spec makes abort a log-level concern // only, and an abort means a newer refresh superseded this one — so // its partial errors describe a run whose result is already stale. // See change: upgrade-model-selector-primitives (design D5). const refreshErrors = refreshResult?.aborted ? [] : [...(refreshResult?.errors ?? [])].map(([provider, err]) => ({ provider, message: errText(err), })); return refreshErrors.length > 0 ? { type: "models_list", sessionId, models, refreshErrors } : { type: "models_list", sessionId, models }; } catch (err) { console.warn("[dashboard] request_models failed:", errText(err)); } } return { type: "models_list", sessionId, models: [] }; } case "request_providers": { // See change: replace-hardcoded-provider-lists. return { type: "providers_list", sessionId, providers: buildProviderCatalogue() }; } case "set_thinking_level": if (options?.setThinkingLevel) { options.setThinkingLevel(msg.level); } return undefined; case "set_model": if (options?.setModel) { await options.setModel(msg.provider, msg.modelId); } return undefined; case "kill_process": { const pgid = (msg as { pgid: number }).pgid; if (pgid) { const killed = killProcessByPgid(pgid); console.error(`[dashboard] kill_process pgid=${pgid} result=${killed}`); } return undefined; } case "shutdown": if (options?.shutdown) { options.shutdown(); } return undefined; case "request_state_sync": // State sync is handled by the bridge on reconnect return undefined; case "request_flows_refresh": { // Re-query pi-flows and send updated list if (options?.eventSink) { const probe: any = {}; try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ } options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] }); } return undefined; } case "list_sessions": { try { // Dynamic import to avoid hard dependency at module load const { SessionManager } = await import("@earendil-works/pi-coding-agent") as any; const cwd = msg.cwd || options?.getCwd?.() || process.cwd(); const sessionInfos = await SessionManager.list(cwd); const sessions: PiSessionInfo[] = (sessionInfos || []).map((s: any) => ({ id: s.id, path: s.path, cwd: s.cwd, name: s.name, parentSessionPath: s.parentSessionPath, created: s.created instanceof Date ? s.created.toISOString() : String(s.created), modified: s.modified instanceof Date ? s.modified.toISOString() : String(s.modified), messageCount: s.messageCount ?? 0, firstMessage: s.firstMessage, })); return { type: "sessions_list", sessionId, cwd, sessions }; } catch { return { type: "sessions_list", sessionId, cwd: msg.cwd || process.cwd(), sessions: [] }; } } default: return undefined; } }, }; } /** The image MIME types pi accepts inline. NEVER widened by this codebase. */ const VALID_IMAGE_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]); /** Outcome of the image allow-list filter: what survives, and what did not. */ export interface ImageValidation { valid: ImageContent[]; /** One human-readable reason per DROPPED image, for `command_feedback`. */ dropped: string[]; } /** * Filter an image array down to the blocks pi will accept. * * Mime and bytes are read through the canonical accessors (design D3c), never * through a direct `.mimeType` / `.data` property read: the direct read is * correct only for the flat pi shape and silently destroys a valid nested * Anthropic block (`{type:"image", source:{media_type, data}}`) as "invalid * mimeType". Survivors are normalised to the flat shape pi consumes. * * Dropped images are RETURNED rather than only logged — a bare `console.error` * is invisible to a dashboard user, which is the same defect class as the image * drop this change fixes (design D7). * * See change: fix-bridge-followup-image-drop (design D6, D7, D3c). */ export function validateImages(images?: unknown): ImageValidation { const valid: ImageContent[] = []; const dropped: string[] = []; if (images === undefined || images === null) return { valid, dropped }; // A non-array container would throw on `for...of`, failing the whole prompt // instead of reporting an unusable attachment. The wire is untrusted. if (!Array.isArray(images)) { dropped.push("attachments were not a list"); return { valid, dropped }; } for (const img of images) { if (!img || typeof img !== "object") { dropped.push("attachment was not an image block"); continue; } const mimeType = imageBlockMime(img); if (!mimeType || !VALID_IMAGE_MIME_TYPES.has(mimeType)) { dropped.push(`unsupported image type "${mimeType ?? "unknown"}"`); continue; } const data = imageBlockData(img); if (!data) { dropped.push("attachment carried no image data"); continue; } valid.push({ type: "image", data, mimeType }); } return { valid, dropped }; } /** * Assemble the pi message content for `text` + `images`: a bare string when * there is no surviving attachment, otherwise a `[{text}, {image}…]` content * array — the shape pi already accepts on the idle and steer paths. * * Deliberately carries NO send options. `sendUserMessageWithImages` used to * fuse validation, assembly and `deliverAs`; the bridge drain must reuse the * first two while passing NO options, because `{deliverAs:"followUp"}` is a * known-broken path there (pi has already exited `getFollowUpMessages()`, so * the entry never drains). Splitting the concerns makes that confusion * structurally impossible (design D6). */ export function buildUserMessageContent( text: string, images?: unknown, ): string | Array<{ type: "text"; text: string } | ImageContent> { const { valid } = validateImages(images); if (valid.length === 0) return text; return [{ type: "text" as const, text }, ...valid]; } /** Send a user message with optional image validation. * Uses deliverAs: "followUp" by default so messages queue properly when the agent is streaming. * Pass deliverAs: "steer" for steering messages (delivered after current turn). * See change: add-steering-message. */ function sendUserMessageWithImages( pi: ExtensionAPI, text: string, images?: unknown, delivery?: "steer" | "followUp", ): void { const deliverAs = delivery ?? ("followUp" as const); // POST-rework-mid-turn-prompt-queue: this helper is called for STEER and // for IDLE sends only — followUp-while-streaming is intercepted upstream // (bridge buffer path; never calls this helper). The deliverAs parameter // is preserved for steer routing. // See change: rework-mid-turn-prompt-queue (design.md D1). // // Drops are logged here rather than surfaced: this path has no event sink. // The buffer path emits `command_feedback` instead (design D7). const { dropped } = validateImages(images); for (const reason of dropped) console.error(`[dashboard] Dropping image — ${reason}`); (pi.sendUserMessage as any)(buildUserMessageContent(text, images), { deliverAs }); } /** * Resolve the dashboard HTTP port, in precedence order: * 1. `PI_DASHBOARD_PORT` / `DASHBOARD_PORT` env — set by the session's * RUNTIME environment (e.g. the docker harness compose env). The * dashboard server does NOT inject these into spawned sessions; it * pins them via `PI_DASHBOARD_URL` / `PI_DASHBOARD_SOCKET` instead. * 2. `~/.pi/dashboard/config.json` `port` — normal local installs write it. * 3. The shared default. * Delegates to the shared `resolveDashboardPorts` so this path and the * bridge's auto-start port resolution cannot drift. * Note: `PI_DASHBOARD_URL` is the gateway (ws) endpoint, NOT the HTTP port, * so it is deliberately not consulted here. * See change: add-dashboard-slash-commands, fix-bridge-autostart-port-resolution. */ function resolveDashboardPort(): number { let fileConfig: { port?: number } = {}; try { const raw = readFileSync(join(homedir(), ".pi", "dashboard", "config.json"), "utf-8"); const parsed = JSON.parse(raw); if (typeof parsed?.port === "number") fileConfig = { port: parsed.port }; } catch { /* missing / unparseable config */ } return resolveDashboardPorts(process.env, fileConfig).port; } /** * A word safe to paste into a bash command line: left bare when it has nothing the shell would * interpret, else POSIX single-quoted (a path with a space, a `'`, a `$`). */ function posixWord(word: string): string { return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`; } /** * Absolute, shell-quoted command that runs the `pi-dashboard` CLI shipped with THIS bridge * (` /bin/pi-dashboard.mjs`), so a template can call a non-observe route with * `eval "$PI_DASHBOARD_CLI" api ` (which sends local proof) with no `pi-dashboard` on PATH. * `eval` is what makes the quoting take effect for an install path with a space; a bare * `$PI_DASHBOARD_CLI` expansion also works whenever the path needs no quoting. */ function dashboardCliCommand(): string { const wrapper = resolve(dirname(resolveServerCliPath()), "..", "bin", "pi-dashboard.mjs"); return `${posixWord(process.execPath)} ${posixWord(wrapper)}`; } /** * Build the env vars exec-mode slash templates rely on: `PI_DASHBOARD_PORT`, * `PI_DASHBOARD_BASE` and `PI_DASHBOARD_CLI`. See changes: add-dashboard-slash-commands, * close-container-loopback-impersonation (D5). */ export function buildDashboardExecEnv(): Record { const port = resolveDashboardPort(); return { PI_DASHBOARD_PORT: String(port), PI_DASHBOARD_BASE: `http://localhost:${port}`, PI_DASHBOARD_CLI: dashboardCliCommand(), }; } /** * Resolve a typed slash command to a prompt template and, when it carries * `executable: bash` frontmatter, run the body as bash (no LLM) via * `handleBashCommand` and return true. Returns false when the text is not an * exec-mode template so the caller falls through to its existing path * (extension dispatch already ran; LLM expansion + sendUserMessage is next). * * Mirrors `tryDispatchExtensionCommand`'s shape so both call sites * (bridge.ts::sessionPrompt and command-handler's non-bridge slash fallback) * stay in lockstep. See change: add-dashboard-slash-commands. */ export async function tryExecSlashTemplate( pi: ExtensionAPI, text: string, cwd: string, sessionId: string, eventSink?: (msg: ExtensionToServerMessage) => void, limits?: InboundLimits, ): Promise { const loaded = loadPromptTemplate(text, cwd, pi as any); if (!loaded || loaded.kind !== "exec") return false; // Positional args bind as $1, $2, … inside the body (split on whitespace, // empty tokens dropped). Quoted args are not honoured in v1 — every exec // template takes simple identifiers (see design.md "Quoting hazard"). const args = loaded.argsString.trim().split(/\s+/).filter(Boolean); await handleBashCommand(pi, sessionId, loaded.body, loaded.excludeFromContext, eventSink, { args, env: buildDashboardExecEnv(), source: "slash-exec", }, limits); return true; } /** Options for executable-mode bash invocation (slash-exec templates). */ interface BashExecOptions { /** Positional args passed after `--` so `$1`, `$2`, … bind in the body. */ args?: string[]; /** Env vars injected by prepending `export` statements to the body. */ env?: Record; /** Marks the emitted bash_output event so the client renders the footer. */ source?: "slash-exec"; } /** * Re-drive a settled-error turn via the pi custom-message primitive. Shared by * the typed `retry_session` message and the deprecated `/__dashboard_retry` * sentinel alias, so both converge on ONE dispatch. See change: * replace-dashboard-retry-command-with-protocol-message. */ function dispatchDashboardRetry( pi: ExtensionAPI, sessionId: string, options?: { eventSink?: (msg: ExtensionToServerMessage) => void; /** Disarm a still-armed RetryTracker chain (bridge → retryTracker.noteExplicitRun). */ disarmRetryChain?: () => void; }, ): void { // Disarm any still-armed provider-retry chain BEFORE the re-drive. Otherwise // the manual turn's native agent_start is converted into a synthetic // auto_retry_start, rendering pi's attempt counter for a user-initiated retry. options?.disarmRetryChain?.(); const emitFailure = (error: unknown) => { const finalError = errText(error); console.error("[dashboard] Internal Retry dispatch failed:", finalError); options?.eventSink?.({ type: "event_forward", sessionId, event: { eventType: "auto_retry_end", timestamp: Date.now(), data: { success: false, attempt: 0, finalError }, }, }); }; try { // sendMessage is async at runtime (the .d.ts types it void). A SYNC throw is // trapped here; an ASYNC rejection by the .catch() below. Both surface as a // single auto_retry_end{success:false} so a failed dispatch never strands // the retry surface. See change (spike caveat 1). const result = pi.sendMessage( { customType: "pi-dashboard:retry", content: "Continue the interrupted response without repeating the user's request.", display: false, }, { triggerTurn: true }, ) as unknown as Promise | void; void Promise.resolve(result).catch(emitFailure); } catch (error) { emitFailure(error); } } /** Execute a bash command and forward results */ async function handleBashCommand( pi: ExtensionAPI, sessionId: string, command: string, excludeFromContext: boolean, eventSink?: (msg: ExtensionToServerMessage) => void, execOpts?: BashExecOptions, limits?: InboundLimits, ): Promise { // Concurrency bound: `!`, `!!` and exec slash templates share ONE counter // per session. A refusal is visible (command_feedback), never silent; the // slot is released on every exit path (success, non-zero, spawn error, // timeout, abort). See change: harden-bridge-inbound-and-discovery (D17). let release: (() => void) | undefined; if (limits) { release = limits.tryAcquireBash(sessionId); if (!release) { eventSink?.({ type: "event_forward", sessionId, event: { eventType: "command_feedback", timestamp: Date.now(), data: { command: "bash", status: "error", message: `bash concurrency limit reached (${limits.maxBash} in flight per session) — wait for a running command to finish`, }, }, }); return; } } try { await runBashCommand(pi, sessionId, command, excludeFromContext, eventSink, execOpts); } finally { release?.(); } } async function runBashCommand( pi: ExtensionAPI, sessionId: string, command: string, excludeFromContext: boolean, eventSink?: (msg: ExtensionToServerMessage) => void, execOpts?: BashExecOptions, ): Promise { // Resolve the shell binary through the tool registry instead of // spawning the literal "sh". On a clean Windows host (no Git-for-Windows // / WSL bash on PATH) resolution fails; we emit a structured // MissingToolError the client renders as an actionable inline error // with a deep-link to Settings → Tools — never a bare ENOENT. // See change: register-bash-and-tool-install-help. const resolved = getDefaultRegistry().resolve("bash"); if (!resolved.ok || !resolved.path) { const missingTool: MissingToolError = { kind: "missing-tool", toolName: "bash" }; eventSink?.({ type: "event_forward", sessionId, event: { eventType: "bash_output", timestamp: Date.now(), data: { command, output: "bash not found — install it from Settings → Tools.", exitCode: 127, excludeFromContext, missingTool, }, }, }); // Do NOT spawn and do NOT send to the LLM — the command never ran. return; } // Inject dashboard env by prepending `export` statements to the body // (pi.exec's ExecOptions has no `env` field). Values are a port number and // a localhost URL — shell-safe — but single-quote-escape defensively. let script = command; if (execOpts?.env) { const exports = Object.entries(execOpts.env) .map(([k, v]) => `export ${k}='${String(v).replace(/'/g, "'\\''")}'`) .join("; "); if (exports) script = `${exports}\n${command}`; } // Positional args bind as $1, $2, … via `bash -c