/** * Shared mutable state for bridge modules. * Avoids passing 14+ closure variables to every extracted function. */ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { shouldSkipByPrefilter } from "./auto-session-namer.js"; import type { ConnectionManager } from "./connection.js"; import type { GitTracker } from "./git-tracker.js"; import type { PrStatusScheduler } from "./pr-status.js"; export interface BridgeContext { pi: ExtensionAPI; connection: ConnectionManager; /** Current session ID (mutated on session change: new/fork/resume) */ sessionId: string; /** * Dashboard-attached OpenSpec change name, or `null` when none. Mirrored * from server `attach_proposal_changed` pushes and replayed on * `session_register`. Read by the `before_agent_start` injector to build * the per-turn system-prompt fragment. See change: * inject-session-context-into-agent. */ attachedChange: string | null; cachedCtx: any; cachedModelRegistry: any; cachedHasUI: boolean | undefined; lastModel: string | undefined; lastThinkingLevel: string | undefined; lastSessionFile: string | undefined; lastSessionDir: string | undefined; lastFirstMessage: string | undefined; lastGitBranch: string | undefined; /** * Last serialized PR tuple (`PrTuple`) sent via `git_info_update`, or * `undefined` when nothing sent yet. Replaces `lastGitPrNumber`. * See change: redesign-composer-session-strip (D5). */ lastGitPrJson: string | undefined; /** * Per-bridge async PR-status scheduler (stable reference across * `syncBc()` snapshots). Absent in unit-test contexts that don't need it. * See change: redesign-composer-session-strip (D5). */ prStatus?: PrStatusScheduler; /** * Per-bridge git tracker (facts cache, HEAD branch, async status probe). * Stable reference across `syncBc()` snapshots. Absent in unit-test contexts. * See change: optimize-polling-hot-paths. */ gitTracker?: GitTracker; /** * Last serialized `GitWorktreeInfo` snapshot sent to the server, or * the literal string `"null"` when we explicitly cleared worktree * state. Compared on every probe tick so we only re-send when the * value actually changes. `undefined` means "nothing sent yet". * See change: add-worktree-spawn-dialog. */ lastGitWorktreeJson: string | undefined; /** * Last serialized `GitStatus` snapshot sent via `git_info_update`, or * `undefined` when nothing sent yet. Compared each VCS tick so the * dirty/drift counts re-broadcast only on change. * See change: add-session-uncommitted-indicator-and-commit. */ lastGitStatusJson: string | undefined; lastSessionName: string | undefined; /** * `true` once the bridge's VCS tick has observed `existsSync(cwd) === false` * and sent the `cwd_missing` notification. Debounce flag so subsequent * ticks don't re-emit. We deliberately never clear it back to `false` even * if the cwd reappears (recreated dir is almost certainly a different * project) — the bridge process typically dies shortly after cwd loss * anyway. See change: add-worktree-lifecycle-actions. */ lastCwdMissing: boolean | undefined; /** * `false` until the very first `sendStateSync` after the bridge * process boots; `true` for the rest of the process lifetime. * Drives `registerReason` on `session_register` so the server can * distinguish initial spawn vs. dashboard-restart reattach. * `handleSessionChange` (new/fork/resume) ignores this flag and * always tags `"spawn"` because it mints a fresh sessionId. * See change: reattach-move-to-front. */ hasRegisteredOnce: boolean; /** * Capture-once "was this pi dashboard-spawned?" boolean. Captured ONCE at * bridge startup from `!!process.env.PI_DASHBOARD_SPAWN_TOKEN`, BEFORE the * single-use token is scrubbed on first register. Reused on every register * so scrubbing the token (to stop descendant/respawn leakage) does not * regress `source: "dashboard"` labelling. Descendant children capture * `false` (their env has no token). See change: fix-spawn-token-env-leak. */ dashboardSpawned: boolean; /** * PIDs (== PGIDs on Unix at spawn time, since `spawnDetached` makes the * child a session/process-group leader) of subprocesses the bridge has * spawned itself — dashboard server auto-start, RPC keeper sidecar, etc. * * Passed to `scanChildProcesses` as `excludedPgids` so the bridge's own * infrastructure never surfaces in the session-card process list. * Pruned in-place by the scanner when entries die. * * See change: tighten-process-list-ux. */ selfSpawnedPgids: Set; } // Commands that the dashboard handles natively with superior UX, filtered from // the command list sent to dashboard clients AND from extension-slash detection. // Current set: { "roles" }. Bridge-registered `__dashboard_reload` is filtered // separately by the `__`-prefix rule. See change: fix-extension-slash-commands-in-dashboard. export const DASHBOARD_NATIVE_COMMANDS = new Set(["roles"]); /** * Filter out hidden commands (names starting with __) and dashboard-native * commands from the commands list, and fill in `CommandInfo.path` from pi's * `sourceInfo.path`. * * The path mapping lives here, not at a sender, because all five * `commands_list` senders pass through this one function (session register, * spawn, flow rediscovery, `session_start` reload, `request_commands`). The * server retains the *latest* list, so a sender that skipped the mapping would * replace a good list with a path-less one and flip every skill to * `not-loaded`. `sourceInfo` is a pi-internal shape, so its absence is * tolerated rather than assumed. See change: fix-skill-discovery-parity. */ export function filterHiddenCommands(commands: any[]): any[] { return commands .filter((cmd) => !cmd.name.startsWith("__") && !DASHBOARD_NATIVE_COMMANDS.has(cmd.name) ) .map((cmd) => { const sourcePath = cmd?.sourceInfo?.path; if (cmd?.path !== undefined || typeof sourcePath !== "string") return cmd; return { ...cmd, path: sourcePath }; }); } /** * Pure predicate: does `text` name an extension-registered slash command? * * Returns true iff: * - `text` starts with `/` and contains no embedded newline * - the token after `/` (up to first space or end) appears in `commandList` * with `source === "extension"` * - that token is NOT in `DASHBOARD_NATIVE_COMMANDS` (and not `__`-prefixed) * * Pure: no pi calls, no mutation. See change: fix-extension-slash-commands-in-dashboard. */ export function isExtensionSlashCommand( text: string, commandList: ReadonlyArray<{ name: string; source?: string }>, ): boolean { if (typeof text !== "string" || !text.startsWith("/")) return false; if (text.includes("\n")) return false; const rest = text.slice(1); const spaceIdx = rest.indexOf(" "); const cmdName = spaceIdx === -1 ? rest : rest.slice(0, spaceIdx); if (!cmdName) return false; if (cmdName.startsWith("__")) return false; if (DASHBOARD_NATIVE_COMMANDS.has(cmdName)) return false; return commandList.some((c) => c?.name === cmdName && c?.source === "extension"); } /** * Pure predicate: is this bridge running inside a dashboard-spawned * headless `pi --mode rpc` session? * * Both probes MUST be true: * 1. `process.env.PI_DASHBOARD_SPAWNED === "1"` (set by * `process-manager.ts::buildSpawnEnv` for every dashboard-spawned session). * 2. `process.argv` contains `--mode` adjacent to `rpc`. * * Either alone is insufficient: env-only matches dashboard-spawned tmux * sessions; argv-only matches non-dashboard RPC invocations. * * Optional `env` / `argv` parameters exist purely for unit testing * (defaulting to the live process state). See change: * add-rpc-stdin-dispatch-with-keeper-sidecar (task 7.1). */ export function isHeadlessRpcSession( env: NodeJS.ProcessEnv = process.env, argv: ReadonlyArray = process.argv, ): boolean { if (env.PI_DASHBOARD_SPAWNED !== "1") return false; for (let i = 0; i < argv.length - 1; i++) { if (argv[i] === "--mode" && argv[i + 1] === "rpc") return true; } return false; } /** Extract first user message text from session entries */ export function extractFirstMessage(ctx: any): string | undefined { try { const entries = ctx?.sessionManager?.getEntries?.(); if (!entries || !Array.isArray(entries)) return undefined; for (const entry of entries) { if (entry.role === "user" && typeof entry.content === "string") { return entry.content.slice(0, 200); } if (entry.role === "user" && Array.isArray(entry.content)) { for (const part of entry.content) { if (part.type === "text" && typeof part.text === "string") { return part.text.slice(0, 200); } } } } } catch { /* ignore */ } return undefined; } /** * Extract the first assistant reply text from session entries. Used to build * the bounded transcript window fed to the auto-naming summarizer. * See change: add-auto-session-naming. */ export function extractFirstAssistantReply(ctx: any): string | undefined { try { const entries = ctx?.sessionManager?.getEntries?.(); if (!entries || !Array.isArray(entries)) return undefined; for (const entry of entries) { if (entry.role !== "assistant") continue; if (typeof entry.content === "string") return entry.content.slice(0, 2000); if (Array.isArray(entry.content)) { let text = ""; for (const part of entry.content) { if (part?.type === "text" && typeof part.text === "string") text += part.text; } if (text) return text.slice(0, 2000); } } } catch { /* ignore */ } return undefined; } /** Concatenated text of one entry's content, or "" when it carries none. */ function entryText(entry: any): string { if (typeof entry?.content === "string") return entry.content; if (!Array.isArray(entry?.content)) return ""; let text = ""; for (const part of entry.content) { if (part?.type === "text" && typeof part.text === "string") text += part.text; } return text; } /** * The ADVANCING transcript window fed to the auto-naming summarizer: the most * recent user entry carrying non-empty text — skipping tool-result-only entries * and empty entries — paired with the assistant reply of that same turn. * * Naming used to send the FIRST user message and FIRST assistant reply forever, * so every retry re-sent a byte-identical request and a session that opened * with a greeting was skipped for life. Only WHICH turn is sent changes here: * the slice bounds are preserved exactly (user 200 chars, assistant 2000), so * at most two bounded slices still leave the process. * See change: fix-auto-naming-reasoning-model (design D6). */ export function extractLatestTurnWindow(ctx: any): { userMsg?: string; assistantReply?: string } { try { const entries = ctx?.sessionManager?.getEntries?.(); if (!entries || !Array.isArray(entries)) return {}; const windowAt = (i: number, text: string) => { let assistantReply: string | undefined; for (let j = i + 1; j < entries.length; j++) { if (entries[j]?.role !== "assistant") continue; const reply = entryText(entries[j]); if (reply) { assistantReply = reply.slice(0, 2000); break; } } return { userMsg: text.slice(0, 200), assistantReply }; }; let latestNonEmpty: { i: number; text: string } | undefined; for (let i = entries.length - 1; i >= 0; i--) { const entry = entries[i]; if (entry?.role !== "user") continue; const text = entryText(entry).trim(); // A tool-result-only entry carries the `user` role but no text — it is // not something a human said, so it can never be the naming window. if (!text) continue; if (latestNonEmpty === undefined) latestNonEmpty = { i, text }; // Select the latest turn the PRE-FILTER would accept. Selecting merely // the latest non-empty turn means a trailing "ok" / "thanks" masks an // otherwise-nameable session, because the pre-filter then rejects the // window and the session is skipped — the exact defect the advancing // window exists to remove. if (!shouldSkipByPrefilter(text)) return windowAt(i, text); } // Nothing substantive was ever said: fall back to the latest non-empty // turn so a genuinely trivial session still reports `skipped-prefilter` // rather than `not-ready`. if (latestNonEmpty) return windowAt(latestNonEmpty.i, latestNonEmpty.text); } catch { /* ignore */ } return {}; } /** * Defensive read of pi's `ctx.cwd` guarded getter. That getter throws once the * session is replaced (new/fork/resume/reload). During a `session_start` for a * replacement, `handleSessionChange(ctx)` runs BEFORE `connection.connect()`; * an un-guarded `ctx.cwd` read there throws, the bridge's `safe()` wrapper * swallows it, `connect()` is skipped, and the socket the preceding * `session_shutdown` closed stays terminally down — the #393 permanent * disconnect. Reading through `safeCwd` yields `process.cwd()` on a throw so the * re-registration path always reaches `connect()`. See change: * fix-bridge-resume-disconnect. */ export function safeCwd(ctx: unknown): string { try { const c = (ctx as { cwd?: unknown } | null | undefined)?.cwd; if (typeof c === "string") return c; } catch { /* guarded getter threw — session was replaced */ } return process.cwd(); } /** Get current model string (provider/id) from cached context */ export function getCurrentModelString(bc: BridgeContext): string | undefined { const model = bc.cachedCtx?.model; if (!model) return undefined; return `${model.provider}/${model.id}`; }