@narumitw/pi-starship 0.56.0 → 0.56.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/{chunk-SD7TUSSU.js → chunk-G2QRDLEN.js} +2 -8
- package/dist/chunks/chunk-G2QRDLEN.js.map +7 -0
- package/dist/chunks/{commands-MJCAK6JL.js → commands-JKG2TCPI.js} +2 -2
- package/dist/index.ts +3 -3
- package/dist/index.ts.map +2 -2
- package/package.json +4 -4
- package/src/config.ts +1 -10
- package/src/usage.ts +1 -1
- package/dist/chunks/chunk-SD7TUSSU.js.map +0 -7
- /package/dist/chunks/{commands-MJCAK6JL.js.map → commands-JKG2TCPI.js.map} +0 -0
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/pi-starship.ts", "../src/modules/git/runtime.ts", "../src/runtime/command.ts", "../src/runtime/github-pr.ts", "../src/runtime/refresh-controller.ts", "../src/runtime/workspace.ts", "../src/usage.ts"],
|
|
4
|
-
"sourcesContent": ["import { homedir, hostname, userInfo } from \"node:os\";\nimport {\n type ExtensionAPI,\n type ExtensionContext,\n getAgentDir,\n type ReadonlyFooterDataProvider,\n} from \"@earendil-works/pi-coding-agent\";\nimport { getCapabilities, wrapTextWithAnsi } from \"@earendil-works/pi-tui\";\nimport { completeStarshipArguments } from \"./command-contract.js\";\nimport type { StarshipCommandOptions } from \"./commands.js\";\nimport { type LoadedStarshipConfig, loadStarshipConfig, type StarshipConfig, settingsFilePath } from \"./config.js\";\nimport { gitSnapshotEqual, readGitSnapshot } from \"./modules/git/runtime.js\";\nimport {\n type GithubPrSnapshot,\n type GitSnapshot,\n inspectStatuslineModules,\n reachableModuleRequirements,\n renderStatusline,\n type StarshipRuntimeSnapshot,\n type StatuslineInspection,\n type WorkspaceSnapshot,\n} from \"./modules/index.js\";\nimport { execWorkspaceCommand } from \"./runtime/command.js\";\nimport { githubPrSnapshotEqual, queryGithubPr } from \"./runtime/github-pr.js\";\nimport { AsyncRefreshController } from \"./runtime/refresh-controller.js\";\nimport {\n collectWorkspaceSnapshot,\n type WorkspaceExec,\n type WorkspaceRefreshInput,\n workspaceSnapshotEqual,\n} from \"./runtime/workspace.js\";\nimport { summarizeFooterUsage } from \"./usage.js\";\n\nconst REFRESH_INTERVAL_MS = 30_000;\nconst GITHUB_PR_REFRESH_INTERVAL_MS = 60_000;\nconst EVENT_DEBOUNCE_MS = 250;\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\ntype StarshipCommands = typeof import(\"./commands.js\");\nlet starshipCommandsPromise: Promise<StarshipCommands> | undefined;\n\nfunction loadStarshipCommands(): Promise<StarshipCommands> {\n if (!starshipCommandsPromise) {\n starshipCommandsPromise = import(\"./commands.js\").catch((error) => {\n starshipCommandsPromise = undefined;\n throw error;\n });\n }\n return starshipCommandsPromise;\n}\n\ninterface RuntimeState {\n activeTools: Map<string, number>;\n isStreaming: boolean;\n uiPrompt?: NonNullable<StarshipRuntimeSnapshot[\"uiPrompt\"]>;\n thinkingLevel: string;\n lastCompletedTool?: string;\n git?: GitSnapshot;\n githubPr?: GithubPrSnapshot;\n workspace?: WorkspaceSnapshot;\n requestRender?: () => void;\n renderPreview?: (loaded: LoadedStarshipConfig, width: number) => string[];\n inspect?: (loaded: LoadedStarshipConfig) => StatuslineInspection;\n footerWidth?: number;\n}\n\ninterface RefreshTarget {\n cwd: string;\n generation: number;\n sessionManager: ExtensionContext[\"sessionManager\"];\n}\n\ninterface GitRefreshInput {\n cwd: string;\n config: StarshipConfig;\n}\n\ninterface PiStarshipOptions {\n githubPrExec?: WorkspaceExec;\n}\n\nexport default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions = {}) {\n let loaded: LoadedStarshipConfig | undefined;\n let loadedRevision = 0;\n let previewLoaded: LoadedStarshipConfig | undefined;\n const runtime: RuntimeState = {\n activeTools: new Map(),\n isStreaming: false,\n thinkingLevel: \"off\",\n };\n let sessionGeneration = 0;\n let menuController = new AbortController();\n let sessionOwner: ExtensionContext[\"sessionManager\"] | undefined;\n let activeTarget: RefreshTarget | undefined;\n let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;\n let githubPrRefreshTimer: ReturnType<typeof setInterval> | undefined;\n let githubPrExpiryTimer: ReturnType<typeof setTimeout> | undefined;\n let githubPrGeneration = 0;\n\n const refresh = () => runtime.requestRender?.();\n const ownsRuntime = (ctx: ExtensionContext) => sessionOwner === ctx.sessionManager;\n const githubPrExec = options.githubPrExec ?? execWorkspaceCommand;\n const gitController = new AsyncRefreshController<GitRefreshInput, GitSnapshot | undefined>({\n async read(input, signal) {\n const requirements = reachableModuleRequirements(input.config);\n const gitReachable =\n [...requirements.keys()].some((name) => name.startsWith(\"git_\")) ||\n (requirements.has(\"directory\") && input.config.modules.directory.options.truncate_to_repo === true);\n if (!gitReachable) return undefined;\n try {\n return await readGitSnapshot(pi, input.cwd, {\n includeMetrics: requirements.has(\"git_metrics\"),\n includeTag: requirements.get(\"git_commit\")?.has(\"tag\") ?? false,\n signal,\n });\n } catch {\n return undefined;\n }\n },\n equal: gitSnapshotEqual,\n publish(snapshot) {\n runtime.git = snapshot;\n refresh();\n },\n });\n const githubPrController = new AsyncRefreshController<Pick<RefreshTarget, \"cwd\">, GithubPrSnapshot | undefined>({\n read: (input, signal) => queryGithubPr(githubPrExec, input.cwd, signal),\n equal: githubPrSnapshotEqual,\n publish(snapshot) {\n runtime.githubPr = snapshot;\n scheduleGithubPrExpiry(snapshot);\n refresh();\n },\n });\n const workspaceController = new AsyncRefreshController<WorkspaceRefreshInput, WorkspaceSnapshot>({\n async read(input, signal) {\n try {\n return await collectWorkspaceSnapshot({ ...input, signal });\n } catch {\n return { modules: {} };\n }\n },\n equal: workspaceSnapshotEqual,\n publish(snapshot) {\n runtime.workspace = snapshot;\n refresh();\n },\n });\n\n const clearDebounce = () => {\n if (!eventDebounceTimer) return;\n clearTimeout(eventDebounceTimer);\n eventDebounceTimer = undefined;\n };\n const isActiveTarget = (target: RefreshTarget) =>\n activeTarget?.cwd === target.cwd &&\n activeTarget.generation === target.generation &&\n activeTarget.sessionManager === target.sessionManager &&\n target.generation === sessionGeneration;\n\n const requestRefresh = (target: RefreshTarget, reason: WorkspaceRefreshInput[\"reason\"] = \"event\") => {\n if (!loaded || !isActiveTarget(target)) return;\n gitController.request({ cwd: target.cwd, config: loaded.config });\n workspaceController.request(workspaceInput(target.cwd, loaded.config, reason, runtime.workspace));\n };\n const scheduleRefresh = (ctx: ExtensionContext) => {\n const target = activeTarget;\n if (!target || target.cwd !== ctx.cwd || target.sessionManager !== ctx.sessionManager) {\n return;\n }\n clearDebounce();\n eventDebounceTimer = setTimeout(() => {\n eventDebounceTimer = undefined;\n requestRefresh(target);\n }, EVENT_DEBOUNCE_MS);\n };\n\n function restartLocalControllers(target: RefreshTarget) {\n if (!isActiveTarget(target)) return;\n gitController.start(target.generation);\n workspaceController.start(target.generation);\n }\n\n function clearGithubPrTimers() {\n if (githubPrRefreshTimer) clearInterval(githubPrRefreshTimer);\n if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);\n githubPrRefreshTimer = undefined;\n githubPrExpiryTimer = undefined;\n }\n\n function stopGithubPr() {\n clearGithubPrTimers();\n githubPrController.stop();\n runtime.githubPr = undefined;\n }\n\n function githubPrReachable(): boolean {\n return Boolean(loaded && reachableModuleRequirements(loaded.config).has(\"github_pr\"));\n }\n\n function startGithubPr(target: RefreshTarget): boolean {\n if (!isActiveTarget(target)) return false;\n stopGithubPr();\n if (!githubPrReachable()) return false;\n githubPrController.start(++githubPrGeneration);\n githubPrRefreshTimer = setInterval(() => {\n requestGithubPr(target);\n }, GITHUB_PR_REFRESH_INTERVAL_MS);\n githubPrRefreshTimer.unref?.();\n return true;\n }\n\n function requestGithubPr(target: RefreshTarget) {\n if (!isActiveTarget(target) || !githubPrReachable()) return;\n githubPrController.request({ cwd: target.cwd });\n }\n\n function scheduleGithubPrExpiry(snapshot: GithubPrSnapshot | undefined) {\n if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);\n githubPrExpiryTimer = undefined;\n if (snapshot?.expiresAt === undefined) return;\n const target = activeTarget;\n if (!target) return;\n const delay = snapshot.expiresAt - Date.now();\n if (delay <= 0) {\n runtime.githubPr = undefined;\n githubPrController.clear();\n refresh();\n return;\n }\n githubPrExpiryTimer = setTimeout(\n () => {\n githubPrExpiryTimer = undefined;\n if (!isActiveTarget(target) || runtime.githubPr !== snapshot) return;\n scheduleGithubPrExpiry(snapshot);\n },\n Math.min(delay, MAX_TIMER_DELAY_MS),\n );\n githubPrExpiryTimer.unref?.();\n }\n\n const installFooter = (ctx: ExtensionContext) => {\n const generation = ++sessionGeneration;\n sessionOwner = ctx.sessionManager;\n previewLoaded = undefined;\n menuController.abort(new DOMException(\"Starship session context replaced\", \"AbortError\"));\n menuController = new AbortController();\n const target: RefreshTarget = { cwd: ctx.cwd, generation, sessionManager: ctx.sessionManager };\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n activeTarget = ctx.mode === \"tui\" ? target : undefined;\n ctx.ui.setStatus(\"starship\", undefined);\n if (!activeTarget || !loaded) return;\n gitController.start(generation);\n workspaceController.start(generation);\n startGithubPr(target);\n\n ctx.ui.setFooter((tui, _theme, footerData) => {\n runtime.requestRender = () => tui.requestRender();\n runtime.renderPreview = (preview, width) => {\n const snapshot = runtimeSnapshot(ctx, footerData, runtime);\n return wrapFormattedStatusline(\n renderStatusline(preview.config, snapshot, width, getCapabilities().trueColor).ansi,\n width,\n );\n };\n runtime.inspect = (current) =>\n inspectStatuslineModules(current.config, runtimeSnapshot(ctx, footerData, runtime), runtime.footerWidth ?? 80);\n const unsubscribe = footerData.onBranchChange(() => {\n if (!isActiveTarget(target)) return;\n runtime.git = undefined;\n restartLocalControllers(target);\n clearDebounce();\n startGithubPr(target);\n requestRefresh(target);\n requestGithubPr(target);\n tui.requestRender();\n });\n let lastRender:\n | {\n snapshot: StarshipRuntimeSnapshot;\n lines: string[];\n config: StarshipConfig;\n width: number;\n }\n | undefined;\n const timer = setInterval(() => {\n if (!isActiveTarget(target)) return;\n clearDebounce();\n requestRefresh(target, \"periodic\");\n // Collectors publish only changed snapshots. The clock is the sole value\n // that changes without publication; reuse the last render's session data.\n if (!lastRender || !reachableModuleRequirements(lastRender.config).get(\"time\")?.has(\"time\")) return;\n const now = new Date();\n const previous = lastRender.snapshot.now;\n if (now.getHours() === previous.getHours() && now.getMinutes() === previous.getMinutes()) return;\n const lines = wrapFormattedStatusline(\n renderStatusline(\n lastRender.config,\n { ...lastRender.snapshot, now },\n lastRender.width,\n getCapabilities().trueColor,\n ).ansi,\n lastRender.width,\n );\n const previousLines = lastRender.lines;\n if (lines.length !== previousLines.length || lines.some((line, index) => line !== previousLines[index]))\n tui.requestRender();\n }, REFRESH_INTERVAL_MS);\n let disposed = false;\n\n return {\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n clearInterval(timer);\n if (isActiveTarget(target)) {\n activeTarget = undefined;\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n }\n },\n invalidate() {},\n render(width: number): string[] {\n runtime.footerWidth = width;\n const current = previewLoaded ?? loaded;\n if (!current) return [];\n const snapshot = runtimeSnapshot(ctx, footerData, runtime);\n const lines = wrapFormattedStatusline(\n renderStatusline(current.config, snapshot, width, getCapabilities().trueColor).ansi,\n width,\n );\n lastRender = { snapshot, lines, config: current.config, width };\n return lines;\n },\n };\n });\n requestRefresh(target, \"initial\");\n requestGithubPr(target);\n };\n\n const configPath = settingsFilePath(getAgentDir());\n const commandOptions: StarshipCommandOptions = {\n settingsPath: configPath,\n getLoaded: () => loaded ?? loadStarshipConfig(configPath),\n getLoadedRevision: () => loadedRevision,\n getInspection: () => {\n const current = loaded ?? loadStarshipConfig(configPath);\n return runtime.inspect?.(current);\n },\n getMenuOwner: () => {\n const generation = sessionGeneration;\n return {\n signal: menuController.signal,\n isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,\n };\n },\n apply(next, ctx) {\n if (sessionOwner !== ctx.sessionManager) {\n throw new Error(\"Starship session context was replaced\");\n }\n previewLoaded = undefined;\n loaded = next;\n loadedRevision += 1;\n const target = activeTarget;\n if (target) {\n restartLocalControllers(target);\n startGithubPr(target);\n requestRefresh(target);\n requestGithubPr(target);\n }\n refresh();\n },\n preview(next, ctx) {\n if (sessionOwner !== ctx.sessionManager) return;\n previewLoaded = next;\n refresh();\n },\n renderPreview(preview, width) {\n return runtime.renderPreview?.(preview, width) ?? [\"Live preview is unavailable until the footer is ready.\"];\n },\n };\n pi.registerCommand(\"starship\", {\n description: \"Customize or inspect the native Starship-style footer\",\n getArgumentCompletions: completeStarshipArguments,\n handler: async (args, ctx) => {\n const commands = await loadStarshipCommands();\n if (sessionOwner !== ctx.sessionManager) return;\n await commands.handleStarshipCommand(args, ctx, commandOptions);\n },\n });\n\n pi.on(\"session_start\", (_event, ctx) => {\n runtime.activeTools.clear();\n runtime.isStreaming = false;\n runtime.uiPrompt = undefined;\n runtime.lastCompletedTool = undefined;\n loaded = loadStarshipConfig(configPath);\n loadedRevision += 1;\n if (loaded.diagnostics.length > 0 && (ctx.mode === \"tui\" || ctx.hasUI)) {\n ctx.ui.notify(formatDiagnostics(loaded), \"warning\");\n }\n runtime.thinkingLevel = pi.getThinkingLevel();\n installFooter(ctx);\n });\n\n pi.on(\"session_tree\", (_event, ctx) => {\n installFooter(ctx);\n refresh();\n });\n\n pi.on(\"session_shutdown\", (_event, ctx) => {\n if (sessionOwner !== ctx.sessionManager) return;\n sessionOwner = undefined;\n previewLoaded = undefined;\n sessionGeneration += 1;\n menuController.abort(new DOMException(\"Starship session shut down\", \"AbortError\"));\n activeTarget = undefined;\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.activeTools.clear();\n runtime.isStreaming = false;\n runtime.uiPrompt = undefined;\n runtime.lastCompletedTool = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n ctx.ui.setFooter(undefined);\n ctx.ui.setStatus(\"starship\", undefined);\n });\n\n pi.on(\"model_select\", () => refresh());\n pi.on(\"thinking_level_select\", (event) => {\n runtime.thinkingLevel = event.level;\n refresh();\n });\n pi.on(\"agent_start\", () => {\n runtime.isStreaming = true;\n refresh();\n });\n pi.on(\"agent_end\", (_event, ctx) => {\n runtime.isStreaming = false;\n scheduleRefresh(ctx);\n const target = activeTarget;\n if (target?.sessionManager === ctx.sessionManager) requestGithubPr(target);\n refresh();\n });\n pi.on(\"ui_prompt_start\", (event, ctx) => {\n if (!ownsRuntime(ctx)) return;\n runtime.uiPrompt = { kind: event.kind, title: event.title };\n refresh();\n });\n pi.on(\"ui_prompt_end\", (_event, ctx) => {\n if (!ownsRuntime(ctx)) return;\n runtime.uiPrompt = undefined;\n refresh();\n });\n pi.on(\"turn_start\", () => {\n runtime.isStreaming = true;\n refresh();\n });\n pi.on(\"turn_end\", (_event, ctx) => {\n scheduleRefresh(ctx);\n refresh();\n });\n pi.on(\"tool_execution_start\", (event) => {\n runtime.activeTools.set(event.toolName, (runtime.activeTools.get(event.toolName) ?? 0) + 1);\n refresh();\n });\n pi.on(\"tool_execution_end\", (event, ctx) => {\n const count = runtime.activeTools.get(event.toolName) ?? 0;\n if (count <= 1) runtime.activeTools.delete(event.toolName);\n else runtime.activeTools.set(event.toolName, count - 1);\n runtime.lastCompletedTool = event.toolName;\n scheduleRefresh(ctx);\n refresh();\n });\n}\n\nfunction workspaceInput(\n cwd: string,\n config: StarshipConfig,\n reason: WorkspaceRefreshInput[\"reason\"],\n previous: WorkspaceSnapshot | undefined,\n): WorkspaceRefreshInput {\n return {\n cwd,\n config,\n environment: allowlistedEnvironment(config),\n homeDir: homedir(),\n platform: process.platform,\n hostname: hostname(),\n username: safeUsername(),\n exec: execWorkspaceCommand,\n reason,\n previous,\n };\n}\n\nconst ENVIRONMENT_ALLOWLIST = [\n \"AWS_CONFIG_FILE\",\n \"AWS_DEFAULT_PROFILE\",\n \"AWS_DEFAULT_REGION\",\n \"AWS_PROFILE\",\n \"AWS_REGION\",\n \"AZURE_CONFIG_DIR\",\n \"CLOUDSDK_ACTIVE_CONFIG_NAME\",\n \"CLOUDSDK_CONFIG\",\n \"CODESPACES\",\n \"CONDA_DEFAULT_ENV\",\n \"DOCKER_CONFIG\",\n \"DOCKER_CONTEXT\",\n \"GUIX_ENVIRONMENT\",\n \"IN_NIX_SHELL\",\n \"KUBECONFIG\",\n \"LOGNAME\",\n \"NIX_SHELL_LEVEL\",\n \"NIX_SHELL_NAME\",\n \"OS_CLIENT_CONFIG_FILE\",\n \"OS_CLOUD\",\n \"OS_PROJECT_NAME\",\n \"PATH\",\n \"PIXI_ENVIRONMENT_NAME\",\n \"PIXI_PROJECT_NAME\",\n \"PYENV_VERSION\",\n \"REMOTE_CONTAINERS\",\n \"RUSTC\",\n \"RUSTUP_TOOLCHAIN\",\n \"SSH_CONNECTION\",\n \"SSH_TTY\",\n \"TF_DATA_DIR\",\n \"TF_WORKSPACE\",\n \"USER\",\n \"USERNAME\",\n \"VIRTUAL_ENV\",\n \"WSL_DISTRO_NAME\",\n] as const;\n\nfunction allowlistedEnvironment(config: StarshipConfig): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n const configured = config.modules.username.options.detect_env_vars;\n const names = new Set([\n ...ENVIRONMENT_ALLOWLIST,\n ...(Array.isArray(configured) ? configured.filter((name): name is string => typeof name === \"string\") : []),\n ]);\n for (const name of names) result[name] = process.env[name];\n return result;\n}\n\nfunction safeUsername(): string {\n try {\n return userInfo().username;\n } catch {\n return process.env.USER ?? process.env.USERNAME ?? \"\";\n }\n}\n\nfunction runtimeSnapshot(\n ctx: ExtensionContext,\n footerData: ReadonlyFooterDataProvider,\n runtime: RuntimeState,\n): StarshipRuntimeSnapshot {\n return {\n cwd: ctx.cwd,\n homeDir: homedir(),\n gitRoot: runtime.git?.root,\n model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined,\n thinkingLevel: runtime.thinkingLevel,\n turnCount: userTurnCount(ctx),\n activeTools: runtime.activeTools,\n isStreaming: runtime.isStreaming,\n uiPrompt: runtime.uiPrompt,\n lastCompletedTool: runtime.lastCompletedTool,\n contextUsage: ctx.getContextUsage() ?? undefined,\n tokenTotals: summarizeFooterUsage(ctx.sessionManager.getEntries()),\n usingSubscription: isSubscriptionBacked(ctx),\n gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),\n gitBranchDetails: runtime.git?.branch,\n gitCommit: runtime.git?.commit,\n gitState: runtime.git?.state,\n gitMetrics: runtime.git?.metrics,\n gitStatus: runtime.git?.status,\n gitWorktree: runtime.git?.worktree,\n githubPr: runtime.githubPr,\n workspace: runtime.workspace,\n extensionStatuses: footerData.getExtensionStatuses(),\n now: new Date(),\n };\n}\n\nfunction userTurnCount(ctx: ExtensionContext): number {\n return ctx.sessionManager.getBranch().filter((entry) => entry.type === \"message\" && entry.message.role === \"user\")\n .length;\n}\n\nfunction isSubscriptionBacked(ctx: ExtensionContext): boolean {\n const model = ctx.model;\n return model !== undefined && (model.provider === \"kimi-coding\" || ctx.modelRegistry.isUsingOAuth(model));\n}\n\nfunction formatDiagnostics(loaded: LoadedStarshipConfig): string {\n const details = loaded.diagnostics.slice(0, 5).map((item) => item.message);\n const remaining = loaded.diagnostics.length - details.length;\n return [`pi-starship settings: ${details.join(\"; \")}`, ...(remaining > 0 ? [`+${remaining} more`] : [])].join(\" \");\n}\n\nexport function wrapFormattedStatusline(format: string, width: number): string[] {\n if (width <= 0) return [];\n return wrapTextWithAnsi(format, width);\n}\n\nexport {\n parseGitDiffShortstat,\n parseGitState,\n parseGitStatusPorcelain,\n parseGitStatusPorcelainV2,\n parseGitWorktree,\n} from \"./modules/git/runtime.js\";\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { basename, isAbsolute, join, resolve } from \"node:path\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport type {\n GitBranchSnapshot,\n GitCommitSnapshot,\n GitMetricsSnapshot,\n GitSnapshot,\n GitStateSnapshot,\n GitStatusSnapshot,\n GitWorktreeSnapshot,\n} from \"../types.js\";\n\nconst GIT_TIMEOUT_MS = 3_000;\n\nexport interface ReadGitSnapshotOptions {\n includeMetrics: boolean;\n includeTag: boolean;\n signal?: AbortSignal;\n}\n\nexport async function readGitSnapshot(\n pi: ExtensionAPI,\n cwd: string,\n options: ReadGitSnapshotOptions,\n): Promise<GitSnapshot | undefined> {\n const statusPromise = pi.exec(\n \"git\",\n [\"--no-optional-locks\", \"status\", \"--porcelain=v2\", \"--branch\", \"--show-stash\", \"--untracked-files=normal\"],\n { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },\n );\n const metadataPromise = pi.exec(\n \"git\",\n [\"rev-parse\", \"--path-format=absolute\", \"--show-toplevel\", \"--git-common-dir\", \"--git-dir\"],\n { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },\n );\n const metricsPromise = options.includeMetrics\n ? pi.exec(\"git\", [\"--no-optional-locks\", \"diff\", \"--shortstat\", \"HEAD\", \"--\"], {\n cwd,\n signal: options.signal,\n timeout: GIT_TIMEOUT_MS,\n })\n : Promise.resolve(undefined);\n const tagPromise = options.includeTag\n ? pi.exec(\"git\", [\"describe\", \"--tags\", \"--exact-match\", \"HEAD\"], {\n cwd,\n signal: options.signal,\n timeout: GIT_TIMEOUT_MS,\n })\n : Promise.resolve(undefined);\n\n const [statusResult, metadataResult, metricsResult, tagResult] = await Promise.all([\n statusPromise,\n metadataPromise,\n metricsPromise,\n tagPromise,\n ]);\n if (statusResult.code !== 0 || statusResult.killed) return undefined;\n\n const parsed = parseGitStatusPorcelainV2(statusResult.stdout);\n const metadata =\n metadataResult.code === 0 && !metadataResult.killed ? parseGitRepositoryMetadata(metadataResult.stdout) : undefined;\n const commit = withTag(parsed.commit, tagResult);\n const metrics =\n metricsResult && metricsResult.code === 0 && !metricsResult.killed\n ? parseGitDiffShortstat(metricsResult.stdout)\n : undefined;\n\n return {\n ...parsed,\n root: metadata?.root,\n commit,\n state: metadata ? parseGitState(metadata.gitDirectory) : undefined,\n metrics,\n worktree: metadata?.worktree,\n };\n}\n\nexport async function readGitStatus(pi: ExtensionAPI, cwd: string): Promise<GitStatusSnapshot | undefined> {\n const result = await pi.exec(\n \"git\",\n [\"--no-optional-locks\", \"status\", \"--porcelain=v2\", \"--branch\", \"--show-stash\", \"--untracked-files=normal\"],\n { cwd, timeout: GIT_TIMEOUT_MS },\n );\n if (result.code !== 0 || result.killed) return undefined;\n return parseGitStatusPorcelainV2(result.stdout).status;\n}\n\nexport async function readGitWorktree(pi: ExtensionAPI, cwd: string): Promise<GitWorktreeSnapshot | undefined> {\n const result = await pi.exec(\n \"git\",\n [\"rev-parse\", \"--path-format=absolute\", \"--show-toplevel\", \"--git-common-dir\", \"--git-dir\"],\n { cwd, timeout: GIT_TIMEOUT_MS },\n );\n if (result.code !== 0 || result.killed) return undefined;\n return parseGitRepositoryMetadata(result.stdout)?.worktree;\n}\n\ninterface ParsedGitStatus {\n branch?: GitBranchSnapshot;\n commit?: GitCommitSnapshot;\n status: GitStatusSnapshot;\n}\n\nexport function parseGitStatusPorcelainV2(output: string): ParsedGitStatus {\n const status = emptyGitStatus();\n let branchName: string | undefined;\n let commitHash: string | undefined;\n let upstream: string | undefined;\n\n for (const line of output.split(/\\r?\\n/u)) {\n if (!line) continue;\n if (line.startsWith(\"# branch.oid \")) {\n const value = line.slice(\"# branch.oid \".length).trim();\n if (value && value !== \"(initial)\") commitHash = value;\n continue;\n }\n if (line.startsWith(\"# branch.head \")) {\n branchName = line.slice(\"# branch.head \".length).trim();\n continue;\n }\n if (line.startsWith(\"# branch.upstream \")) {\n upstream = line.slice(\"# branch.upstream \".length).trim();\n continue;\n }\n if (line.startsWith(\"# branch.ab \")) {\n const match = /^# branch\\.ab \\+(\\d+) -(\\d+)$/u.exec(line);\n status.ahead = match?.[1] ? Number(match[1]) : 0;\n status.behind = match?.[2] ? Number(match[2]) : 0;\n continue;\n }\n if (line.startsWith(\"# stash \")) {\n const count = Number(line.slice(\"# stash \".length));\n status.stashed = Number.isSafeInteger(count) && count > 0 ? count : 0;\n continue;\n }\n addPorcelainV2Status(status, line);\n }\n finalizeStatus(status);\n\n const detached = branchName === \"(detached)\";\n const remote = splitUpstream(upstream);\n const branch = branchName\n ? {\n name: detached ? \"HEAD\" : branchName,\n ...remote,\n detached,\n }\n : undefined;\n const commit = commitHash ? { hash: commitHash, detached } : undefined;\n return { branch, commit, status };\n}\n\nexport function parseGitStatusPorcelain(output: string): GitStatusSnapshot {\n const status = emptyGitStatus();\n for (const line of output.split(/\\r?\\n/u)) {\n if (!line) continue;\n if (line.startsWith(\"## \")) {\n const ahead = /\\bahead (\\d+)/u.exec(line);\n const behind = /\\bbehind (\\d+)/u.exec(line);\n status.ahead = ahead?.[1] ? Number(ahead[1]) : 0;\n status.behind = behind?.[1] ? Number(behind[1]) : 0;\n continue;\n }\n const indexStatus = line[0] ?? \" \";\n const worktreeStatus = line[1] ?? \" \";\n if (indexStatus === \"?\" && worktreeStatus === \"?\") {\n status.untracked += 1;\n continue;\n }\n if (isConflict(indexStatus, worktreeStatus)) {\n status.conflicted += 1;\n continue;\n }\n addNormalStatus(status, indexStatus, worktreeStatus);\n if (indexStatus === \"R\" || indexStatus === \"C\") status.renamed += 1;\n }\n finalizeStatus(status);\n return status;\n}\n\nexport function parseGitDiffShortstat(output: string): GitMetricsSnapshot {\n return {\n added: parseShortstatMetric(output, \"insertion(+)\", \"insertions(+)\") ?? 0,\n deleted: parseShortstatMetric(output, \"deletion(-)\", \"deletions(-)\") ?? 0,\n };\n}\n\nfunction parseShortstatMetric(output: string, singularLabel: string, pluralLabel: string): number | undefined {\n for (const field of output.split(\",\")) {\n const trimmed = field.trim();\n const separator = trimmed.indexOf(\" \");\n if (separator <= 0) continue;\n const label = trimmed.slice(separator + 1).trimStart();\n if (label !== singularLabel && label !== pluralLabel) continue;\n const countText = trimmed.slice(0, separator);\n for (const character of countText) {\n if (character < \"0\" || character > \"9\") return undefined;\n }\n const count = Number(countText);\n return Number.isSafeInteger(count) ? count : undefined;\n }\n return undefined;\n}\n\nexport function parseGitState(gitDirectory: string): GitStateSnapshot | undefined {\n const rebaseMerge = join(gitDirectory, \"rebase-merge\");\n if (existsSync(rebaseMerge)) return operationWithProgress(\"REBASING\", rebaseMerge, \"msgnum\", \"end\");\n\n const rebaseApply = join(gitDirectory, \"rebase-apply\");\n if (existsSync(rebaseApply)) {\n const state = existsSync(join(rebaseApply, \"applying\"))\n ? \"AM\"\n : existsSync(join(rebaseApply, \"rebasing\"))\n ? \"REBASING\"\n : \"AM/REBASE\";\n return operationWithProgress(state, rebaseApply, \"next\", \"last\");\n }\n if (existsSync(join(gitDirectory, \"MERGE_HEAD\"))) return { state: \"MERGING\" };\n if (existsSync(join(gitDirectory, \"REVERT_HEAD\"))) return { state: \"REVERTING\" };\n if (existsSync(join(gitDirectory, \"CHERRY_PICK_HEAD\"))) return { state: \"CHERRY-PICKING\" };\n if (existsSync(join(gitDirectory, \"BISECT_LOG\"))) return { state: \"BISECTING\" };\n return undefined;\n}\n\ninterface GitRepositoryMetadata {\n root: string;\n gitDirectory: string;\n worktree?: GitWorktreeSnapshot;\n}\n\nfunction parseGitRepositoryMetadata(output: string): GitRepositoryMetadata | undefined {\n const lines = output.trimEnd().split(/\\r?\\n/u);\n if (lines.length !== 3) return undefined;\n const [path, commonDir, gitDirectory] = lines;\n if (!path || !commonDir || !gitDirectory) return undefined;\n if (![path, commonDir, gitDirectory].every(isAbsolute)) return undefined;\n return {\n root: path,\n gitDirectory,\n worktree: samePath(commonDir, gitDirectory) ? undefined : { name: basename(path) || path, path },\n };\n}\n\nexport function parseGitWorktree(output: string): GitWorktreeSnapshot | undefined {\n return parseGitRepositoryMetadata(output)?.worktree;\n}\n\nfunction addPorcelainV2Status(status: GitStatusSnapshot, line: string) {\n const kind = line[0];\n if (kind === \"?\") {\n status.untracked += 1;\n return;\n }\n if (kind === \"u\") {\n status.conflicted += 1;\n return;\n }\n if (kind !== \"1\" && kind !== \"2\") return;\n const indexStatus = line[2] ?? \".\";\n const worktreeStatus = line[3] ?? \".\";\n addNormalStatus(status, indexStatus, worktreeStatus);\n if (kind === \"2\") status.renamed += 1;\n}\n\nfunction addNormalStatus(status: GitStatusSnapshot, indexStatus: string, worktreeStatus: string) {\n if (indexStatus === \"A\") status.indexAdded += 1;\n if (indexStatus === \"D\") status.indexDeleted += 1;\n if (indexStatus === \"M\") status.indexModified += 1;\n if (indexStatus === \"T\") status.indexTypechanged += 1;\n if (worktreeStatus === \"A\") status.worktreeAdded += 1;\n if (worktreeStatus === \"D\") status.worktreeDeleted += 1;\n if (worktreeStatus === \"M\") status.worktreeModified += 1;\n if (worktreeStatus === \"T\") status.worktreeTypechanged += 1;\n}\n\nfunction finalizeStatus(status: GitStatusSnapshot) {\n status.deleted = status.worktreeDeleted + status.indexDeleted;\n status.modified = status.worktreeModified + status.worktreeAdded;\n status.staged = status.indexModified + status.indexAdded + status.indexTypechanged;\n status.typechanged = status.worktreeTypechanged;\n}\n\nfunction emptyGitStatus(): GitStatusSnapshot {\n return {\n ahead: 0,\n behind: 0,\n stashed: 0,\n conflicted: 0,\n deleted: 0,\n renamed: 0,\n modified: 0,\n staged: 0,\n typechanged: 0,\n untracked: 0,\n worktreeAdded: 0,\n worktreeDeleted: 0,\n worktreeModified: 0,\n worktreeTypechanged: 0,\n indexAdded: 0,\n indexDeleted: 0,\n indexModified: 0,\n indexTypechanged: 0,\n };\n}\n\nfunction splitUpstream(upstream: string | undefined): {\n remoteName?: string;\n remoteBranch?: string;\n} {\n if (!upstream) return {};\n const separator = upstream.indexOf(\"/\");\n if (separator <= 0 || separator === upstream.length - 1) return { remoteBranch: upstream };\n return {\n remoteName: upstream.slice(0, separator),\n remoteBranch: upstream.slice(separator + 1),\n };\n}\n\nfunction withTag(\n commit: GitCommitSnapshot | undefined,\n result:\n | {\n stdout: string;\n code: number;\n killed: boolean;\n }\n | undefined,\n): GitCommitSnapshot | undefined {\n if (!commit || !result || result.code !== 0 || result.killed) return commit;\n const tag = result.stdout.trim();\n return tag ? { ...commit, tag: tag.split(/\\r?\\n/u)[0] } : commit;\n}\n\nfunction operationWithProgress(\n state: string,\n directory: string,\n currentName: string,\n totalName: string,\n): GitStateSnapshot {\n const progressCurrent = readPositiveInteger(join(directory, currentName));\n const progressTotal = readPositiveInteger(join(directory, totalName));\n return progressCurrent !== undefined && progressTotal !== undefined\n ? { state, progressCurrent, progressTotal }\n : { state };\n}\n\nfunction readPositiveInteger(path: string): number | undefined {\n try {\n const value = Number(readFileSync(path, \"utf8\").trim());\n return Number.isSafeInteger(value) && value > 0 ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction samePath(left: string, right: string): boolean {\n const normalizedLeft = resolve(left);\n const normalizedRight = resolve(right);\n return process.platform === \"win32\"\n ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()\n : normalizedLeft === normalizedRight;\n}\n\nfunction isConflict(indexStatus: string, worktreeStatus: string): boolean {\n return (\n (indexStatus === \"D\" && worktreeStatus === \"D\") ||\n (indexStatus === \"A\" && worktreeStatus === \"A\") ||\n indexStatus === \"U\" ||\n worktreeStatus === \"U\"\n );\n}\n\nexport function gitStatusEqual(left: GitStatusSnapshot | undefined, right: GitStatusSnapshot | undefined): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport function gitSnapshotEqual(left: GitSnapshot | undefined, right: GitSnapshot | undefined): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n", "import { spawn } from \"node:child_process\";\nimport type { WorkspaceExec } from \"./types.js\";\n\nconst FORCE_KILL_DELAY_MS = 250;\n\nexport const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>\n new Promise((resolve) => {\n if (options.signal?.aborted) {\n resolve({ stdout: \"\", stderr: \"\", code: 1, killed: true });\n return;\n }\n\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, {\n cwd: options.cwd,\n detached: process.platform !== \"win32\",\n env: explicitEnvironment(options.environment),\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n } catch {\n resolve({ stdout: \"\", stderr: \"\", code: 1, killed: false });\n return;\n }\n\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let outputBytes = 0;\n let killed = false;\n let settled = false;\n let forceKillTimer: NodeJS.Timeout | undefined;\n let timeoutTimer: NodeJS.Timeout | undefined;\n\n const finish = (code: number) => {\n if (settled) return;\n settled = true;\n if (timeoutTimer) clearTimeout(timeoutTimer);\n if (forceKillTimer) clearTimeout(forceKillTimer);\n options.signal?.removeEventListener(\"abort\", terminate);\n resolve({\n stdout: Buffer.concat(stdout).toString(\"utf8\"),\n stderr: Buffer.concat(stderr).toString(\"utf8\"),\n code,\n killed,\n });\n };\n\n const signalProcessTree = (signal: NodeJS.Signals) => {\n const pid = child.pid;\n if (pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-pid, signal);\n return;\n } catch {\n child.kill(signal);\n return;\n }\n }\n try {\n const killer = spawn(\"taskkill.exe\", [\"/pid\", String(pid), \"/t\", \"/f\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n killer.once(\"error\", () => child.kill(signal));\n killer.unref();\n } catch {\n child.kill(signal);\n }\n };\n\n function terminate() {\n if (killed || settled) return;\n killed = true;\n signalProcessTree(\"SIGTERM\");\n forceKillTimer = setTimeout(() => {\n signalProcessTree(\"SIGKILL\");\n child.stdout?.destroy();\n child.stderr?.destroy();\n finish(1);\n }, FORCE_KILL_DELAY_MS);\n }\n\n const collect = (target: Buffer[]) => (data: Buffer | string) => {\n const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);\n const remaining = Math.max(0, options.maxOutputBytes - outputBytes);\n if (remaining > 0) target.push(chunk.subarray(0, remaining));\n outputBytes += chunk.byteLength;\n if (outputBytes > options.maxOutputBytes) terminate();\n };\n\n child.stdout?.on(\"data\", collect(stdout));\n child.stderr?.on(\"data\", collect(stderr));\n child.once(\"error\", () => {\n if (!killed) finish(1);\n });\n child.once(\"close\", (code) => {\n if (!killed) finish(code ?? 1);\n });\n options.signal?.addEventListener(\"abort\", terminate, { once: true });\n if (options.signal?.aborted) terminate();\n timeoutTimer = setTimeout(terminate, options.timeout);\n });\n\nfunction explicitEnvironment(source: Readonly<Record<string, string | undefined>>): NodeJS.ProcessEnv {\n const result: NodeJS.ProcessEnv = Object.create(null);\n for (const [name, value] of Object.entries(source)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || value === undefined || value.includes(\"\\0\")) {\n continue;\n }\n Object.defineProperty(result, name, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return result;\n}\n", "import { getCapabilities } from \"@earendil-works/pi-tui\";\nimport type { GithubPrSnapshot, GithubPrState } from \"../modules/types.js\";\nimport type { WorkspaceExec } from \"./types.js\";\n\nconst GH_TIMEOUT_MS = 10_000;\nconst MAX_GH_OUTPUT_BYTES = 128 * 1024;\nconst MAX_URL_LENGTH = 4_096;\nconst MAX_CHECKS = 1_000;\nconst MAX_FIELD_LENGTH = 128;\nconst RFC3339_TIMESTAMP = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(?:Z|[+-](\\d{2}):(\\d{2}))$/u;\nexport const TERMINAL_PR_LIFETIME_MS = 24 * 60 * 60 * 1_000;\n\nconst GH_PR_FIELDS = [\n \"number\",\n \"isDraft\",\n \"url\",\n \"state\",\n \"closedAt\",\n \"mergedAt\",\n \"reviewDecision\",\n \"statusCheckRollup\",\n] as const;\n\ninterface GithubPrQueryOptions {\n platform?: NodeJS.Platform;\n environment?: Readonly<Record<string, string | undefined>>;\n}\n\ninterface CheckSummary {\n failed: number;\n pending: number;\n total: number;\n}\n\ntype PullRequestState = \"OPEN\" | \"CLOSED\" | \"MERGED\";\ntype ReviewDecision = \"APPROVED\" | \"CHANGES_REQUESTED\" | \"REVIEW_REQUIRED\" | \"\";\n\nexport function ghPrViewInvocation(platform: NodeJS.Platform = process.platform): {\n command: string;\n args: string[];\n} {\n return {\n command: platform === \"win32\" ? \"gh.exe\" : \"gh\",\n args: [\"pr\", \"view\", \"--json\", GH_PR_FIELDS.join(\",\")],\n };\n}\n\nexport function githubPrEnvironment(\n source: Readonly<Record<string, string | undefined>> = process.env,\n): Record<string, string | undefined> {\n const environment: Record<string, string | undefined> = Object.create(null);\n for (const [name, value] of Object.entries(source)) {\n const normalized = name.toUpperCase();\n if (normalized === \"GH_HOST\" || normalized === \"GH_REPO\") continue;\n Object.defineProperty(environment, name, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return environment;\n}\n\nexport async function queryGithubPr(\n exec: WorkspaceExec,\n cwd: string,\n signal?: AbortSignal,\n now = Date.now(),\n options: GithubPrQueryOptions = {},\n): Promise<GithubPrSnapshot | undefined> {\n const invocation = ghPrViewInvocation(options.platform);\n try {\n const result = await exec(invocation.command, invocation.args, {\n cwd,\n signal,\n timeout: GH_TIMEOUT_MS,\n maxOutputBytes: MAX_GH_OUTPUT_BYTES,\n environment: githubPrEnvironment(options.environment),\n });\n if (result.killed || result.code !== 0) return undefined;\n if (Buffer.byteLength(result.stdout) > MAX_GH_OUTPUT_BYTES) return undefined;\n return buildGithubPrSnapshot(JSON.parse(result.stdout), now);\n } catch {\n return undefined;\n }\n}\n\nexport function buildGithubPrSnapshot(value: unknown, now = Date.now()): GithubPrSnapshot | undefined {\n try {\n const pr = record(value);\n const number = positiveInteger(pr.number);\n const isDraft = requiredBoolean(pr.isDraft);\n const url = requiredBoundedString(pr.url, MAX_URL_LENGTH, true);\n const state = pullRequestState(pr.state);\n const closedAt = optionalTimestamp(pr.closedAt);\n const mergedAt = optionalTimestamp(pr.mergedAt);\n const reviewDecision = reviewDecisionValue(pr.reviewDecision);\n const checks = summarizeChecks(pr.statusCheckRollup);\n const expiresAt = terminalExpiry(state, closedAt, mergedAt);\n if (state !== \"OPEN\" && (expiresAt === undefined || now >= expiresAt)) return undefined;\n\n const presentationState: GithubPrState =\n state === \"MERGED\" ? \"merged\" : state === \"CLOSED\" ? \"closed\" : isDraft ? \"draft\" : \"open\";\n const checksText = formatChecks(checks);\n const review = formatReview(reviewDecision);\n const status = compactStatus(presentationState, checks, checksText, review);\n const snapshot: GithubPrSnapshot = {\n number: String(number),\n link: osc8Link(url, `#${number}`),\n state: presentationState,\n checks: checksText,\n review,\n status,\n ...(expiresAt === undefined ? {} : { expiresAt }),\n };\n return Object.freeze(snapshot);\n } catch {\n return undefined;\n }\n}\n\nexport function githubPrSnapshotEqual(\n left: GithubPrSnapshot | undefined,\n right: GithubPrSnapshot | undefined,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction terminalExpiry(\n state: PullRequestState,\n closedAt: number | undefined,\n mergedAt: number | undefined,\n): number | undefined {\n if (state === \"OPEN\") return undefined;\n const terminalAt = state === \"MERGED\" ? mergedAt : closedAt;\n return terminalAt === undefined ? undefined : terminalAt + TERMINAL_PR_LIFETIME_MS;\n}\n\nfunction summarizeChecks(value: unknown): CheckSummary {\n if (!Array.isArray(value) || value.length > MAX_CHECKS) throw new Error(\"Invalid PR checks\");\n const summary: CheckSummary = { failed: 0, pending: 0, total: value.length };\n for (const item of value) {\n const check = record(item);\n const state = optionalUppercase(check.state);\n const status = optionalUppercase(check.status);\n const conclusion = optionalUppercase(check.conclusion);\n if (state === \"SUCCESS\") continue;\n if (state === \"FAILURE\" || state === \"ERROR\") {\n summary.failed += 1;\n continue;\n }\n if (state === \"PENDING\" || state === \"EXPECTED\") {\n summary.pending += 1;\n continue;\n }\n if (status && status !== \"COMPLETED\") {\n summary.pending += 1;\n continue;\n }\n if (conclusion === \"SUCCESS\" || conclusion === \"SKIPPED\" || conclusion === \"NEUTRAL\") {\n continue;\n }\n if (\n conclusion === \"FAILURE\" ||\n conclusion === \"CANCELLED\" ||\n conclusion === \"TIMED_OUT\" ||\n conclusion === \"ACTION_REQUIRED\" ||\n conclusion === \"STARTUP_FAILURE\"\n ) {\n summary.failed += 1;\n continue;\n }\n summary.pending += 1;\n }\n return summary;\n}\n\nfunction formatChecks(checks: CheckSummary): string {\n if (checks.total === 0) return \"-\";\n const passed = checks.total - checks.failed - checks.pending;\n return [compactCount(\"\u2713\", passed), compactCount(\"\u00D7\", checks.failed), compactCount(\"\u2026\", checks.pending)]\n .filter(Boolean)\n .join(\" \");\n}\n\nfunction compactCount(symbol: string, count: number): string {\n return count > 0 ? `${symbol}${count}` : \"\";\n}\n\nfunction formatReview(review: ReviewDecision): string {\n if (review === \"APPROVED\") return \"R\u2713\";\n if (review === \"CHANGES_REQUESTED\") return \"R\u00D7\";\n if (review === \"REVIEW_REQUIRED\") return \"R?\";\n return \"\";\n}\n\nfunction compactStatus(state: GithubPrState, checks: CheckSummary, checksText: string, review: string): string {\n if (state === \"merged\") return \"M\";\n if (state === \"closed\") return \"C\";\n if (state === \"draft\") return \"D\";\n if (checks.failed > 0) return compactCount(\"\u00D7\", checks.failed);\n if (review === \"R\u00D7\") return review;\n if (checks.pending > 0) return compactCount(\"\u2026\", checks.pending);\n if (review === \"R\u2713\" || review === \"R?\") return review;\n return checksText;\n}\n\nfunction osc8Link(value: string, label: string): string {\n if (!getCapabilities().hyperlinks || hasTerminalControls(value)) return label;\n try {\n const url = new URL(value);\n if ((url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.username || url.password) {\n return label;\n }\n const normalized = url.toString();\n if (normalized.length > MAX_URL_LENGTH || hasTerminalControls(normalized)) return label;\n return `\\u001b]8;;${normalized}\\u0007${label}\\u001b]8;;\\u0007`;\n } catch {\n return label;\n }\n}\n\nfunction hasTerminalControls(value: string): boolean {\n return Array.from(value).some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return (\n codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) || (codePoint >= 0xd800 && codePoint <= 0xdfff)\n );\n });\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\"Expected PR object\");\n }\n return value as Record<string, unknown>;\n}\n\nfunction positiveInteger(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error(\"Invalid PR number\");\n }\n return value;\n}\n\nfunction requiredBoolean(value: unknown): boolean {\n if (typeof value !== \"boolean\") throw new Error(\"Invalid PR boolean\");\n return value;\n}\n\nfunction requiredBoundedString(value: unknown, maxLength: number, allowEmpty = false): string {\n if (typeof value !== \"string\" || value.length > maxLength || (!allowEmpty && value.length === 0)) {\n throw new Error(\"Invalid PR string\");\n }\n return value;\n}\n\nfunction optionalUppercase(value: unknown): string | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n return requiredBoundedString(value, MAX_FIELD_LENGTH).toUpperCase();\n}\n\nfunction optionalTimestamp(value: unknown): number | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n const text = requiredBoundedString(value, MAX_FIELD_LENGTH);\n const match = RFC3339_TIMESTAMP.exec(text);\n if (!match) throw new Error(\"Invalid PR timestamp\");\n const [, yearText, monthText, dayText, hourText, minuteText, secondText, offsetHourText, offsetMinuteText] = match;\n const year = Number(yearText);\n const month = Number(monthText);\n const day = Number(dayText);\n const hour = Number(hourText);\n const minute = Number(minuteText);\n const second = Number(secondText);\n const offsetHour = Number(offsetHourText ?? 0);\n const offsetMinute = Number(offsetMinuteText ?? 0);\n if (\n month < 1 ||\n month > 12 ||\n day < 1 ||\n day > daysInMonth(year, month) ||\n hour > 23 ||\n minute > 59 ||\n second > 59 ||\n offsetHour > 23 ||\n offsetMinute > 59\n ) {\n throw new Error(\"Invalid PR timestamp\");\n }\n const timestamp = Date.parse(text);\n if (!Number.isFinite(timestamp)) throw new Error(\"Invalid PR timestamp\");\n return timestamp;\n}\n\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) {\n const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n return leapYear ? 29 : 28;\n }\n return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;\n}\n\nfunction pullRequestState(value: unknown): PullRequestState {\n if (value === \"OPEN\" || value === \"CLOSED\" || value === \"MERGED\") return value;\n throw new Error(\"Invalid PR state\");\n}\n\nfunction reviewDecisionValue(value: unknown): ReviewDecision {\n if (value === null || value === undefined || value === \"\" || value === \"UNKNOWN\") return \"\";\n if (value === \"APPROVED\" || value === \"CHANGES_REQUESTED\" || value === \"REVIEW_REQUIRED\") {\n return value;\n }\n throw new Error(\"Invalid PR review decision\");\n}\n", "export interface AsyncRefreshControllerOptions<Input, Snapshot> {\n read(input: Input, signal: AbortSignal): Promise<Snapshot>;\n equal(left: Snapshot | undefined, right: Snapshot): boolean;\n publish(snapshot: Snapshot): void;\n onError?(error: unknown): void;\n}\n\ninterface RefreshRequest<Input> {\n generation: number;\n requestId: number;\n input: Input;\n}\n\ninterface ActiveRefresh<Input> {\n request: RefreshRequest<Input>;\n controller: AbortController;\n}\n\n/** Coalesces refreshes to one active read plus the latest pending request. */\nexport class AsyncRefreshController<Input, Snapshot> {\n private generation: number | undefined;\n private requestId = 0;\n private active: ActiveRefresh<Input> | undefined;\n private pending: RefreshRequest<Input> | undefined;\n private current: Snapshot | undefined;\n\n constructor(private readonly options: AsyncRefreshControllerOptions<Input, Snapshot>) {}\n\n start(generation: number): void {\n this.cancelActive(\"Refresh generation replaced\");\n this.generation = generation;\n this.requestId += 1;\n this.pending = undefined;\n this.current = undefined;\n }\n\n clear(): void {\n this.current = undefined;\n }\n\n request(input: Input): void {\n if (this.generation === undefined) return;\n const request = {\n generation: this.generation,\n requestId: ++this.requestId,\n input,\n };\n if (this.active) {\n this.pending = request;\n return;\n }\n this.run(request);\n }\n\n stop(): void {\n this.generation = undefined;\n this.requestId += 1;\n this.pending = undefined;\n this.current = undefined;\n this.cancelActive(\"Refresh controller stopped\");\n }\n\n private run(request: RefreshRequest<Input>): void {\n if (!this.isCurrentTarget(request)) return;\n const active: ActiveRefresh<Input> = {\n request,\n controller: new AbortController(),\n };\n this.active = active;\n void this.options\n .read(request.input, active.controller.signal)\n .then((snapshot) => {\n if (this.active !== active || !this.isCurrentRequest(request)) return;\n if (this.options.equal(this.current, snapshot)) return;\n this.current = snapshot;\n this.options.publish(snapshot);\n })\n .catch((error: unknown) => {\n if (this.active === active && this.isCurrentRequest(request) && !active.controller.signal.aborted) {\n this.options.onError?.(error);\n }\n })\n .finally(() => {\n if (this.active !== active) return;\n this.active = undefined;\n const pending = this.pending;\n this.pending = undefined;\n if (pending) this.run(pending);\n });\n }\n\n private cancelActive(reason: string): void {\n this.active?.controller.abort(new DOMException(reason, \"AbortError\"));\n }\n\n private isCurrentTarget(request: RefreshRequest<Input>): boolean {\n return this.generation !== undefined && request.generation === this.generation;\n }\n\n private isCurrentRequest(request: RefreshRequest<Input>): boolean {\n return this.isCurrentTarget(request) && request.requestId === this.requestId;\n }\n}\n", "import type { ModuleName } from \"../modules/catalog.js\";\nimport { reachableModuleRequirements } from \"../modules/render.js\";\nimport type { WorkspaceSnapshot } from \"../modules/types.js\";\nimport { createFileSystem } from \"./helpers.js\";\nimport {\n type CollectorContext,\n type MutableModuleSnapshot,\n PRIVATE_STYLE_SELECTOR,\n type WorkspaceEntry,\n type WorkspaceRefreshInput,\n} from \"./types.js\";\n\nexport type { WorkspaceExec, WorkspaceExecResult, WorkspaceRefreshInput } from \"./types.js\";\n\nexport async function collectWorkspaceSnapshot(input: WorkspaceRefreshInput): Promise<WorkspaceSnapshot> {\n const requirements = reachableModuleRequirements(input.config);\n if (input.signal?.aborted || !hasWorkspaceRequirement(requirements)) return freezeSnapshot({});\n const fs = createFileSystem(input);\n let listing: Promise<readonly WorkspaceEntry[]> | undefined;\n const context: CollectorContext = {\n input,\n fs,\n requirements,\n entries() {\n listing ??= fs.readDirectory(input.cwd);\n return listing;\n },\n options(name) {\n return input.config.modules[name].options;\n },\n needs(name, variable) {\n const variables = requirements.get(name);\n return Boolean(variables && (variable === undefined || variables.has(variable)));\n },\n };\n const modules: MutableModuleSnapshot = {};\n if (requirements.has(\"package\")) {\n const { collectPackage } = await import(\"./package.js\");\n if (input.signal?.aborted) return freezeSnapshot({});\n const packageValues = await collectPackage(context);\n if (input.signal?.aborted) return freezeSnapshot({});\n if (packageValues) modules.package = packageValues;\n }\n for (const descriptor of COLLECTOR_GROUPS) {\n if (!descriptor.modules.some((name) => requirements.has(name))) continue;\n if (input.signal?.aborted) return freezeSnapshot({});\n const collector = await descriptor.load();\n if (input.signal?.aborted) return freezeSnapshot({});\n mergeModules(modules, await collector(context));\n }\n return input.signal?.aborted ? freezeSnapshot({}) : freezeSnapshot(modules);\n}\n\nexport function workspaceSnapshotEqual(\n left: WorkspaceSnapshot | undefined,\n right: WorkspaceSnapshot | undefined,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction hasWorkspaceRequirement(requirements: ReadonlyMap<ModuleName, ReadonlySet<string>>): boolean {\n return [...requirements.keys()].some((name) => !BUILT_IN_ONLY_MODULES.has(name));\n}\n\ntype WorkspaceCollector = (context: CollectorContext) => Promise<MutableModuleSnapshot>;\n\nconst COLLECTOR_GROUPS: readonly {\n modules: readonly ModuleName[];\n load(): Promise<WorkspaceCollector>;\n}[] = [\n {\n modules: [\"nodejs\", \"python\", \"rust\", \"golang\", \"bun\", \"deno\"],\n load: async () => (await import(\"./languages.js\")).collectLanguages,\n },\n {\n modules: [\"mise\", \"direnv\", \"pixi\", \"conda\", \"nix_shell\", \"guix_shell\"],\n load: async () => (await import(\"./development.js\")).collectDevelopment,\n },\n {\n modules: [\"docker_context\", \"kubernetes\", \"terraform\"],\n load: async () => (await import(\"./deployment.js\")).collectDeployment,\n },\n {\n modules: [\"aws\", \"gcloud\", \"azure\", \"openstack\"],\n load: async () => (await import(\"./cloud.js\")).collectCloud,\n },\n {\n modules: [\"container\", \"hostname\", \"os\", \"username\"],\n load: async () => (await import(\"./execution.js\")).collectExecution,\n },\n];\n\nconst BUILT_IN_ONLY_MODULES = new Set<ModuleName>([\n \"brand\",\n \"provider\",\n \"model\",\n \"thinking\",\n \"directory\",\n \"git_worktree\",\n \"git_branch\",\n \"github_pr\",\n \"git_commit\",\n \"git_state\",\n \"git_metrics\",\n \"git_status\",\n \"activity\",\n \"context\",\n \"tokens\",\n \"cost\",\n \"time\",\n \"turn\",\n \"fill\",\n \"extension_status\",\n]);\n\nfunction mergeModules(target: MutableModuleSnapshot, source: MutableModuleSnapshot): void {\n for (const [name, values] of Object.entries(source)) {\n Object.defineProperty(target, name, {\n value: values,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n}\n\nfunction freezeSnapshot(modules: MutableModuleSnapshot): WorkspaceSnapshot {\n const styleSelectors: Record<string, string> = {};\n for (const [name, values] of Object.entries(modules)) {\n const selector = Object.hasOwn(values, PRIVATE_STYLE_SELECTOR) ? values[PRIVATE_STYLE_SELECTOR] : undefined;\n delete values[PRIVATE_STYLE_SELECTOR];\n if (selector !== undefined) styleSelectors[name] = selector;\n Object.freeze(values);\n }\n return Object.freeze({\n modules: Object.freeze(modules),\n ...(Object.keys(styleSelectors).length > 0 ? { styleSelectors: Object.freeze(styleSelectors) } : {}),\n });\n}\n", "import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\n\ninterface UsageLike {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n}\n\nexport interface FooterUsageSummary {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n latestCacheHitRate?: number;\n}\n\nexport function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUsageSummary {\n const totals: FooterUsageSummary = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: 0,\n };\n\n for (const entry of entries) {\n let usage: UsageLike | undefined;\n if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n usage = entry.message.usage;\n const input = usage.input ?? 0;\n const cacheRead = usage.cacheRead ?? 0;\n const cacheWrite = usage.cacheWrite ?? 0;\n const promptTokens = input + cacheRead + cacheWrite;\n totals.latestCacheHitRate = promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;\n } else if (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n usage = entry.message.usage;\n } else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n usage = entry.usage;\n }\n if (!usage) continue;\n\n totals.input += usage.input ?? 0;\n totals.output += usage.output ?? 0;\n totals.cacheRead += usage.cacheRead ?? 0;\n totals.cacheWrite += usage.cacheWrite ?? 0;\n totals.cost += usage.cost?.total ?? 0;\n }\n\n return totals;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,UAAU,gBAAgB;AAC5C;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,mBAAAA,kBAAiB,wBAAwB;;;ACPlD,SAAS,YAAY,oBAAoB;AACzC,SAAS,UAAU,YAAY,MAAM,eAAe;AAYpD,IAAM,iBAAiB;AAQvB,eAAsB,gBACpB,IACA,KACA,SACkC;AAClC,QAAM,gBAAgB,GAAG;AAAA,IACvB;AAAA,IACA,CAAC,uBAAuB,UAAU,kBAAkB,YAAY,gBAAgB,0BAA0B;AAAA,IAC1G,EAAE,KAAK,QAAQ,QAAQ,QAAQ,SAAS,eAAe;AAAA,EACzD;AACA,QAAM,kBAAkB,GAAG;AAAA,IACzB;AAAA,IACA,CAAC,aAAa,0BAA0B,mBAAmB,oBAAoB,WAAW;AAAA,IAC1F,EAAE,KAAK,QAAQ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,QAAQ;AAAA,IAClB,WAAW,QAAQ;AAAA,IACnB,mBAAmB,WAAW,qBAAqB;AAAA,IACnD,KAAK,oBAAI,KAAK;AAAA,EAChB;AACF;AAEA,SAAS,cAAc,KAA+B;AACpD,SAAO,IAAI,eAAe,UAAU,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,aAAa,MAAM,QAAQ,SAAS,MAAM,EAC9G;AACL;AAEA,SAAS,qBAAqB,KAAgC;AAC5D,QAAM,QAAQ,IAAI;AAClB,SAAO,UAAU,WAAc,MAAM,aAAa,iBAAiB,IAAI,cAAc,aAAa,KAAK;AACzG;AAEA,SAAS,kBAAkB,QAAsC;AAC/D,QAAM,UAAU,OAAO,YAAY,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,SAAS,KAAK,OAAO;AACzE,QAAM,YAAY,OAAO,YAAY,SAAS,QAAQ;AACtD,SAAO,CAAC,yBAAyB,QAAQ,KAAK,IAAI,CAAC,IAAI,GAAI,YAAY,IAAI,CAAC,IAAI,SAAS,OAAO,IAAI,CAAC,CAAE,EAAE,KAAK,GAAG;AACnH;AAEO,SAAS,wBAAwB,QAAgB,OAAyB;AAC/E,MAAI,SAAS,EAAG,QAAO,CAAC;AACxB,SAAO,iBAAiB,QAAQ,KAAK;AACvC;",
|
|
4
|
+
"sourcesContent": ["import { homedir, hostname, userInfo } from \"node:os\";\nimport {\n type ExtensionAPI,\n type ExtensionContext,\n getAgentDir,\n type ReadonlyFooterDataProvider,\n} from \"@earendil-works/pi-coding-agent\";\nimport { getCapabilities, wrapTextWithAnsi } from \"@earendil-works/pi-tui\";\nimport { completeStarshipArguments } from \"./command-contract.js\";\nimport type { StarshipCommandOptions } from \"./commands.js\";\nimport { type LoadedStarshipConfig, loadStarshipConfig, type StarshipConfig, settingsFilePath } from \"./config.js\";\nimport { gitSnapshotEqual, readGitSnapshot } from \"./modules/git/runtime.js\";\nimport {\n type GithubPrSnapshot,\n type GitSnapshot,\n inspectStatuslineModules,\n reachableModuleRequirements,\n renderStatusline,\n type StarshipRuntimeSnapshot,\n type StatuslineInspection,\n type WorkspaceSnapshot,\n} from \"./modules/index.js\";\nimport { execWorkspaceCommand } from \"./runtime/command.js\";\nimport { githubPrSnapshotEqual, queryGithubPr } from \"./runtime/github-pr.js\";\nimport { AsyncRefreshController } from \"./runtime/refresh-controller.js\";\nimport {\n collectWorkspaceSnapshot,\n type WorkspaceExec,\n type WorkspaceRefreshInput,\n workspaceSnapshotEqual,\n} from \"./runtime/workspace.js\";\nimport { summarizeFooterUsage } from \"./usage.js\";\n\nconst REFRESH_INTERVAL_MS = 30_000;\nconst GITHUB_PR_REFRESH_INTERVAL_MS = 60_000;\nconst EVENT_DEBOUNCE_MS = 250;\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\ntype StarshipCommands = typeof import(\"./commands.js\");\nlet starshipCommandsPromise: Promise<StarshipCommands> | undefined;\n\nfunction loadStarshipCommands(): Promise<StarshipCommands> {\n if (!starshipCommandsPromise) {\n starshipCommandsPromise = import(\"./commands.js\").catch((error) => {\n starshipCommandsPromise = undefined;\n throw error;\n });\n }\n return starshipCommandsPromise;\n}\n\ninterface RuntimeState {\n activeTools: Map<string, number>;\n isStreaming: boolean;\n uiPrompt?: NonNullable<StarshipRuntimeSnapshot[\"uiPrompt\"]>;\n thinkingLevel: string;\n lastCompletedTool?: string;\n git?: GitSnapshot;\n githubPr?: GithubPrSnapshot;\n workspace?: WorkspaceSnapshot;\n requestRender?: () => void;\n renderPreview?: (loaded: LoadedStarshipConfig, width: number) => string[];\n inspect?: (loaded: LoadedStarshipConfig) => StatuslineInspection;\n footerWidth?: number;\n}\n\ninterface RefreshTarget {\n cwd: string;\n generation: number;\n sessionManager: ExtensionContext[\"sessionManager\"];\n}\n\ninterface GitRefreshInput {\n cwd: string;\n config: StarshipConfig;\n}\n\ninterface PiStarshipOptions {\n githubPrExec?: WorkspaceExec;\n}\n\nexport default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions = {}) {\n let loaded: LoadedStarshipConfig | undefined;\n let loadedRevision = 0;\n let previewLoaded: LoadedStarshipConfig | undefined;\n const runtime: RuntimeState = {\n activeTools: new Map(),\n isStreaming: false,\n thinkingLevel: \"off\",\n };\n let sessionGeneration = 0;\n let menuController = new AbortController();\n let sessionOwner: ExtensionContext[\"sessionManager\"] | undefined;\n let activeTarget: RefreshTarget | undefined;\n let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;\n let githubPrRefreshTimer: ReturnType<typeof setInterval> | undefined;\n let githubPrExpiryTimer: ReturnType<typeof setTimeout> | undefined;\n let githubPrGeneration = 0;\n\n const refresh = () => runtime.requestRender?.();\n const ownsRuntime = (ctx: ExtensionContext) => sessionOwner === ctx.sessionManager;\n const githubPrExec = options.githubPrExec ?? execWorkspaceCommand;\n const gitController = new AsyncRefreshController<GitRefreshInput, GitSnapshot | undefined>({\n async read(input, signal) {\n const requirements = reachableModuleRequirements(input.config);\n const gitReachable =\n [...requirements.keys()].some((name) => name.startsWith(\"git_\")) ||\n (requirements.has(\"directory\") && input.config.modules.directory.options.truncate_to_repo === true);\n if (!gitReachable) return undefined;\n try {\n return await readGitSnapshot(pi, input.cwd, {\n includeMetrics: requirements.has(\"git_metrics\"),\n includeTag: requirements.get(\"git_commit\")?.has(\"tag\") ?? false,\n signal,\n });\n } catch {\n return undefined;\n }\n },\n equal: gitSnapshotEqual,\n publish(snapshot) {\n runtime.git = snapshot;\n refresh();\n },\n });\n const githubPrController = new AsyncRefreshController<Pick<RefreshTarget, \"cwd\">, GithubPrSnapshot | undefined>({\n read: (input, signal) => queryGithubPr(githubPrExec, input.cwd, signal),\n equal: githubPrSnapshotEqual,\n publish(snapshot) {\n runtime.githubPr = snapshot;\n scheduleGithubPrExpiry(snapshot);\n refresh();\n },\n });\n const workspaceController = new AsyncRefreshController<WorkspaceRefreshInput, WorkspaceSnapshot>({\n async read(input, signal) {\n try {\n return await collectWorkspaceSnapshot({ ...input, signal });\n } catch {\n return { modules: {} };\n }\n },\n equal: workspaceSnapshotEqual,\n publish(snapshot) {\n runtime.workspace = snapshot;\n refresh();\n },\n });\n\n const clearDebounce = () => {\n if (!eventDebounceTimer) return;\n clearTimeout(eventDebounceTimer);\n eventDebounceTimer = undefined;\n };\n const isActiveTarget = (target: RefreshTarget) =>\n activeTarget?.cwd === target.cwd &&\n activeTarget.generation === target.generation &&\n activeTarget.sessionManager === target.sessionManager &&\n target.generation === sessionGeneration;\n\n const requestRefresh = (target: RefreshTarget, reason: WorkspaceRefreshInput[\"reason\"] = \"event\") => {\n if (!loaded || !isActiveTarget(target)) return;\n gitController.request({ cwd: target.cwd, config: loaded.config });\n workspaceController.request(workspaceInput(target.cwd, loaded.config, reason, runtime.workspace));\n };\n const scheduleRefresh = (ctx: ExtensionContext) => {\n const target = activeTarget;\n if (!target || target.cwd !== ctx.cwd || target.sessionManager !== ctx.sessionManager) {\n return;\n }\n clearDebounce();\n eventDebounceTimer = setTimeout(() => {\n eventDebounceTimer = undefined;\n requestRefresh(target);\n }, EVENT_DEBOUNCE_MS);\n };\n\n function restartLocalControllers(target: RefreshTarget) {\n if (!isActiveTarget(target)) return;\n gitController.start(target.generation);\n workspaceController.start(target.generation);\n }\n\n function clearGithubPrTimers() {\n if (githubPrRefreshTimer) clearInterval(githubPrRefreshTimer);\n if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);\n githubPrRefreshTimer = undefined;\n githubPrExpiryTimer = undefined;\n }\n\n function stopGithubPr() {\n clearGithubPrTimers();\n githubPrController.stop();\n runtime.githubPr = undefined;\n }\n\n function githubPrReachable(): boolean {\n return Boolean(loaded && reachableModuleRequirements(loaded.config).has(\"github_pr\"));\n }\n\n function startGithubPr(target: RefreshTarget): boolean {\n if (!isActiveTarget(target)) return false;\n stopGithubPr();\n if (!githubPrReachable()) return false;\n githubPrController.start(++githubPrGeneration);\n githubPrRefreshTimer = setInterval(() => {\n requestGithubPr(target);\n }, GITHUB_PR_REFRESH_INTERVAL_MS);\n githubPrRefreshTimer.unref?.();\n return true;\n }\n\n function requestGithubPr(target: RefreshTarget) {\n if (!isActiveTarget(target) || !githubPrReachable()) return;\n githubPrController.request({ cwd: target.cwd });\n }\n\n function scheduleGithubPrExpiry(snapshot: GithubPrSnapshot | undefined) {\n if (githubPrExpiryTimer) clearTimeout(githubPrExpiryTimer);\n githubPrExpiryTimer = undefined;\n if (snapshot?.expiresAt === undefined) return;\n const target = activeTarget;\n if (!target) return;\n const delay = snapshot.expiresAt - Date.now();\n if (delay <= 0) {\n runtime.githubPr = undefined;\n githubPrController.clear();\n refresh();\n return;\n }\n githubPrExpiryTimer = setTimeout(\n () => {\n githubPrExpiryTimer = undefined;\n if (!isActiveTarget(target) || runtime.githubPr !== snapshot) return;\n scheduleGithubPrExpiry(snapshot);\n },\n Math.min(delay, MAX_TIMER_DELAY_MS),\n );\n githubPrExpiryTimer.unref?.();\n }\n\n const installFooter = (ctx: ExtensionContext) => {\n const generation = ++sessionGeneration;\n sessionOwner = ctx.sessionManager;\n previewLoaded = undefined;\n menuController.abort(new DOMException(\"Starship session context replaced\", \"AbortError\"));\n menuController = new AbortController();\n const target: RefreshTarget = { cwd: ctx.cwd, generation, sessionManager: ctx.sessionManager };\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n activeTarget = ctx.mode === \"tui\" ? target : undefined;\n ctx.ui.setStatus(\"starship\", undefined);\n if (!activeTarget || !loaded) return;\n gitController.start(generation);\n workspaceController.start(generation);\n startGithubPr(target);\n\n ctx.ui.setFooter((tui, _theme, footerData) => {\n runtime.requestRender = () => tui.requestRender();\n runtime.renderPreview = (preview, width) => {\n const snapshot = runtimeSnapshot(ctx, footerData, runtime);\n return wrapFormattedStatusline(\n renderStatusline(preview.config, snapshot, width, getCapabilities().trueColor).ansi,\n width,\n );\n };\n runtime.inspect = (current) =>\n inspectStatuslineModules(current.config, runtimeSnapshot(ctx, footerData, runtime), runtime.footerWidth ?? 80);\n const unsubscribe = footerData.onBranchChange(() => {\n if (!isActiveTarget(target)) return;\n runtime.git = undefined;\n restartLocalControllers(target);\n clearDebounce();\n startGithubPr(target);\n requestRefresh(target);\n requestGithubPr(target);\n tui.requestRender();\n });\n let lastRender:\n | {\n snapshot: StarshipRuntimeSnapshot;\n lines: string[];\n config: StarshipConfig;\n width: number;\n }\n | undefined;\n const timer = setInterval(() => {\n if (!isActiveTarget(target)) return;\n clearDebounce();\n requestRefresh(target, \"periodic\");\n // Collectors publish only changed snapshots. The clock is the sole value\n // that changes without publication; reuse the last render's session data.\n if (!lastRender || !reachableModuleRequirements(lastRender.config).get(\"time\")?.has(\"time\")) return;\n const now = new Date();\n const previous = lastRender.snapshot.now;\n if (now.getHours() === previous.getHours() && now.getMinutes() === previous.getMinutes()) return;\n const lines = wrapFormattedStatusline(\n renderStatusline(\n lastRender.config,\n { ...lastRender.snapshot, now },\n lastRender.width,\n getCapabilities().trueColor,\n ).ansi,\n lastRender.width,\n );\n const previousLines = lastRender.lines;\n if (lines.length !== previousLines.length || lines.some((line, index) => line !== previousLines[index]))\n tui.requestRender();\n }, REFRESH_INTERVAL_MS);\n let disposed = false;\n\n return {\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n clearInterval(timer);\n if (isActiveTarget(target)) {\n activeTarget = undefined;\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n }\n },\n invalidate() {},\n render(width: number): string[] {\n runtime.footerWidth = width;\n const current = previewLoaded ?? loaded;\n if (!current) return [];\n const snapshot = runtimeSnapshot(ctx, footerData, runtime);\n const lines = wrapFormattedStatusline(\n renderStatusline(current.config, snapshot, width, getCapabilities().trueColor).ansi,\n width,\n );\n lastRender = { snapshot, lines, config: current.config, width };\n return lines;\n },\n };\n });\n requestRefresh(target, \"initial\");\n requestGithubPr(target);\n };\n\n const configPath = settingsFilePath(getAgentDir());\n const commandOptions: StarshipCommandOptions = {\n settingsPath: configPath,\n getLoaded: () => loaded ?? loadStarshipConfig(configPath),\n getLoadedRevision: () => loadedRevision,\n getInspection: () => {\n const current = loaded ?? loadStarshipConfig(configPath);\n return runtime.inspect?.(current);\n },\n getMenuOwner: () => {\n const generation = sessionGeneration;\n return {\n signal: menuController.signal,\n isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,\n };\n },\n apply(next, ctx) {\n if (sessionOwner !== ctx.sessionManager) {\n throw new Error(\"Starship session context was replaced\");\n }\n previewLoaded = undefined;\n loaded = next;\n loadedRevision += 1;\n const target = activeTarget;\n if (target) {\n restartLocalControllers(target);\n startGithubPr(target);\n requestRefresh(target);\n requestGithubPr(target);\n }\n refresh();\n },\n preview(next, ctx) {\n if (sessionOwner !== ctx.sessionManager) return;\n previewLoaded = next;\n refresh();\n },\n renderPreview(preview, width) {\n return runtime.renderPreview?.(preview, width) ?? [\"Live preview is unavailable until the footer is ready.\"];\n },\n };\n pi.registerCommand(\"starship\", {\n description: \"Customize or inspect the native Starship-style footer\",\n getArgumentCompletions: completeStarshipArguments,\n handler: async (args, ctx) => {\n const commands = await loadStarshipCommands();\n if (sessionOwner !== ctx.sessionManager) return;\n await commands.handleStarshipCommand(args, ctx, commandOptions);\n },\n });\n\n pi.on(\"session_start\", (_event, ctx) => {\n runtime.activeTools.clear();\n runtime.isStreaming = false;\n runtime.uiPrompt = undefined;\n runtime.lastCompletedTool = undefined;\n loaded = loadStarshipConfig(configPath);\n loadedRevision += 1;\n if (loaded.diagnostics.length > 0 && (ctx.mode === \"tui\" || ctx.hasUI)) {\n ctx.ui.notify(formatDiagnostics(loaded), \"warning\");\n }\n runtime.thinkingLevel = pi.getThinkingLevel();\n installFooter(ctx);\n });\n\n pi.on(\"session_tree\", (_event, ctx) => {\n installFooter(ctx);\n refresh();\n });\n\n pi.on(\"session_shutdown\", (_event, ctx) => {\n if (sessionOwner !== ctx.sessionManager) return;\n sessionOwner = undefined;\n previewLoaded = undefined;\n sessionGeneration += 1;\n menuController.abort(new DOMException(\"Starship session shut down\", \"AbortError\"));\n activeTarget = undefined;\n clearDebounce();\n gitController.stop();\n workspaceController.stop();\n stopGithubPr();\n runtime.git = undefined;\n runtime.workspace = undefined;\n runtime.activeTools.clear();\n runtime.isStreaming = false;\n runtime.uiPrompt = undefined;\n runtime.lastCompletedTool = undefined;\n runtime.requestRender = undefined;\n runtime.renderPreview = undefined;\n runtime.inspect = undefined;\n runtime.footerWidth = undefined;\n ctx.ui.setFooter(undefined);\n ctx.ui.setStatus(\"starship\", undefined);\n });\n\n pi.on(\"model_select\", () => refresh());\n pi.on(\"thinking_level_select\", (event) => {\n runtime.thinkingLevel = event.level;\n refresh();\n });\n pi.on(\"agent_start\", () => {\n runtime.isStreaming = true;\n refresh();\n });\n pi.on(\"agent_end\", (_event, ctx) => {\n runtime.isStreaming = false;\n scheduleRefresh(ctx);\n const target = activeTarget;\n if (target?.sessionManager === ctx.sessionManager) requestGithubPr(target);\n refresh();\n });\n pi.on(\"ui_prompt_start\", (event, ctx) => {\n if (!ownsRuntime(ctx)) return;\n runtime.uiPrompt = { kind: event.kind, title: event.title };\n refresh();\n });\n pi.on(\"ui_prompt_end\", (_event, ctx) => {\n if (!ownsRuntime(ctx)) return;\n runtime.uiPrompt = undefined;\n refresh();\n });\n pi.on(\"turn_start\", () => {\n runtime.isStreaming = true;\n refresh();\n });\n pi.on(\"turn_end\", (_event, ctx) => {\n scheduleRefresh(ctx);\n refresh();\n });\n pi.on(\"tool_execution_start\", (event) => {\n runtime.activeTools.set(event.toolName, (runtime.activeTools.get(event.toolName) ?? 0) + 1);\n refresh();\n });\n pi.on(\"tool_execution_end\", (event, ctx) => {\n const count = runtime.activeTools.get(event.toolName) ?? 0;\n if (count <= 1) runtime.activeTools.delete(event.toolName);\n else runtime.activeTools.set(event.toolName, count - 1);\n runtime.lastCompletedTool = event.toolName;\n scheduleRefresh(ctx);\n refresh();\n });\n}\n\nfunction workspaceInput(\n cwd: string,\n config: StarshipConfig,\n reason: WorkspaceRefreshInput[\"reason\"],\n previous: WorkspaceSnapshot | undefined,\n): WorkspaceRefreshInput {\n return {\n cwd,\n config,\n environment: allowlistedEnvironment(config),\n homeDir: homedir(),\n platform: process.platform,\n hostname: hostname(),\n username: safeUsername(),\n exec: execWorkspaceCommand,\n reason,\n previous,\n };\n}\n\nconst ENVIRONMENT_ALLOWLIST = [\n \"AWS_CONFIG_FILE\",\n \"AWS_DEFAULT_PROFILE\",\n \"AWS_DEFAULT_REGION\",\n \"AWS_PROFILE\",\n \"AWS_REGION\",\n \"AZURE_CONFIG_DIR\",\n \"CLOUDSDK_ACTIVE_CONFIG_NAME\",\n \"CLOUDSDK_CONFIG\",\n \"CODESPACES\",\n \"CONDA_DEFAULT_ENV\",\n \"DOCKER_CONFIG\",\n \"DOCKER_CONTEXT\",\n \"GUIX_ENVIRONMENT\",\n \"IN_NIX_SHELL\",\n \"KUBECONFIG\",\n \"LOGNAME\",\n \"NIX_SHELL_LEVEL\",\n \"NIX_SHELL_NAME\",\n \"OS_CLIENT_CONFIG_FILE\",\n \"OS_CLOUD\",\n \"OS_PROJECT_NAME\",\n \"PATH\",\n \"PIXI_ENVIRONMENT_NAME\",\n \"PIXI_PROJECT_NAME\",\n \"PYENV_VERSION\",\n \"REMOTE_CONTAINERS\",\n \"RUSTC\",\n \"RUSTUP_TOOLCHAIN\",\n \"SSH_CONNECTION\",\n \"SSH_TTY\",\n \"TF_DATA_DIR\",\n \"TF_WORKSPACE\",\n \"USER\",\n \"USERNAME\",\n \"VIRTUAL_ENV\",\n \"WSL_DISTRO_NAME\",\n] as const;\n\nfunction allowlistedEnvironment(config: StarshipConfig): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n const configured = config.modules.username.options.detect_env_vars;\n const names = new Set([\n ...ENVIRONMENT_ALLOWLIST,\n ...(Array.isArray(configured) ? configured.filter((name): name is string => typeof name === \"string\") : []),\n ]);\n for (const name of names) result[name] = process.env[name];\n return result;\n}\n\nfunction safeUsername(): string {\n try {\n return userInfo().username;\n } catch {\n return process.env.USER ?? process.env.USERNAME ?? \"\";\n }\n}\n\nfunction runtimeSnapshot(\n ctx: ExtensionContext,\n footerData: ReadonlyFooterDataProvider,\n runtime: RuntimeState,\n): StarshipRuntimeSnapshot {\n return {\n cwd: ctx.cwd,\n homeDir: homedir(),\n gitRoot: runtime.git?.root,\n model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined,\n thinkingLevel: runtime.thinkingLevel,\n turnCount: userTurnCount(ctx),\n activeTools: runtime.activeTools,\n isStreaming: runtime.isStreaming,\n uiPrompt: runtime.uiPrompt,\n lastCompletedTool: runtime.lastCompletedTool,\n contextUsage: ctx.getContextUsage() ?? undefined,\n tokenTotals: summarizeFooterUsage(ctx.sessionManager.getEntries()),\n usingSubscription: isSubscriptionBacked(ctx),\n gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),\n gitBranchDetails: runtime.git?.branch,\n gitCommit: runtime.git?.commit,\n gitState: runtime.git?.state,\n gitMetrics: runtime.git?.metrics,\n gitStatus: runtime.git?.status,\n gitWorktree: runtime.git?.worktree,\n githubPr: runtime.githubPr,\n workspace: runtime.workspace,\n extensionStatuses: footerData.getExtensionStatuses(),\n now: new Date(),\n };\n}\n\nfunction userTurnCount(ctx: ExtensionContext): number {\n return ctx.sessionManager.getBranch().filter((entry) => entry.type === \"message\" && entry.message.role === \"user\")\n .length;\n}\n\nfunction isSubscriptionBacked(ctx: ExtensionContext): boolean {\n const model = ctx.model;\n return model !== undefined && (model.provider === \"kimi-coding\" || ctx.modelRegistry.isUsingOAuth(model));\n}\n\nfunction formatDiagnostics(loaded: LoadedStarshipConfig): string {\n const details = loaded.diagnostics.slice(0, 5).map((item) => item.message);\n const remaining = loaded.diagnostics.length - details.length;\n return [`pi-starship settings: ${details.join(\"; \")}`, ...(remaining > 0 ? [`+${remaining} more`] : [])].join(\" \");\n}\n\nexport function wrapFormattedStatusline(format: string, width: number): string[] {\n if (width <= 0) return [];\n return wrapTextWithAnsi(format, width);\n}\n\nexport {\n parseGitDiffShortstat,\n parseGitState,\n parseGitStatusPorcelain,\n parseGitStatusPorcelainV2,\n parseGitWorktree,\n} from \"./modules/git/runtime.js\";\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { basename, isAbsolute, join, resolve } from \"node:path\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport type {\n GitBranchSnapshot,\n GitCommitSnapshot,\n GitMetricsSnapshot,\n GitSnapshot,\n GitStateSnapshot,\n GitStatusSnapshot,\n GitWorktreeSnapshot,\n} from \"../types.js\";\n\nconst GIT_TIMEOUT_MS = 3_000;\n\nexport interface ReadGitSnapshotOptions {\n includeMetrics: boolean;\n includeTag: boolean;\n signal?: AbortSignal;\n}\n\nexport async function readGitSnapshot(\n pi: ExtensionAPI,\n cwd: string,\n options: ReadGitSnapshotOptions,\n): Promise<GitSnapshot | undefined> {\n const statusPromise = pi.exec(\n \"git\",\n [\"--no-optional-locks\", \"status\", \"--porcelain=v2\", \"--branch\", \"--show-stash\", \"--untracked-files=normal\"],\n { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },\n );\n const metadataPromise = pi.exec(\n \"git\",\n [\"rev-parse\", \"--path-format=absolute\", \"--show-toplevel\", \"--git-common-dir\", \"--git-dir\"],\n { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },\n );\n const metricsPromise = options.includeMetrics\n ? pi.exec(\"git\", [\"--no-optional-locks\", \"diff\", \"--shortstat\", \"HEAD\", \"--\"], {\n cwd,\n signal: options.signal,\n timeout: GIT_TIMEOUT_MS,\n })\n : Promise.resolve(undefined);\n const tagPromise = options.includeTag\n ? pi.exec(\"git\", [\"describe\", \"--tags\", \"--exact-match\", \"HEAD\"], {\n cwd,\n signal: options.signal,\n timeout: GIT_TIMEOUT_MS,\n })\n : Promise.resolve(undefined);\n\n const [statusResult, metadataResult, metricsResult, tagResult] = await Promise.all([\n statusPromise,\n metadataPromise,\n metricsPromise,\n tagPromise,\n ]);\n if (statusResult.code !== 0 || statusResult.killed) return undefined;\n\n const parsed = parseGitStatusPorcelainV2(statusResult.stdout);\n const metadata =\n metadataResult.code === 0 && !metadataResult.killed ? parseGitRepositoryMetadata(metadataResult.stdout) : undefined;\n const commit = withTag(parsed.commit, tagResult);\n const metrics =\n metricsResult && metricsResult.code === 0 && !metricsResult.killed\n ? parseGitDiffShortstat(metricsResult.stdout)\n : undefined;\n\n return {\n ...parsed,\n root: metadata?.root,\n commit,\n state: metadata ? parseGitState(metadata.gitDirectory) : undefined,\n metrics,\n worktree: metadata?.worktree,\n };\n}\n\nexport async function readGitStatus(pi: ExtensionAPI, cwd: string): Promise<GitStatusSnapshot | undefined> {\n const result = await pi.exec(\n \"git\",\n [\"--no-optional-locks\", \"status\", \"--porcelain=v2\", \"--branch\", \"--show-stash\", \"--untracked-files=normal\"],\n { cwd, timeout: GIT_TIMEOUT_MS },\n );\n if (result.code !== 0 || result.killed) return undefined;\n return parseGitStatusPorcelainV2(result.stdout).status;\n}\n\nexport async function readGitWorktree(pi: ExtensionAPI, cwd: string): Promise<GitWorktreeSnapshot | undefined> {\n const result = await pi.exec(\n \"git\",\n [\"rev-parse\", \"--path-format=absolute\", \"--show-toplevel\", \"--git-common-dir\", \"--git-dir\"],\n { cwd, timeout: GIT_TIMEOUT_MS },\n );\n if (result.code !== 0 || result.killed) return undefined;\n return parseGitRepositoryMetadata(result.stdout)?.worktree;\n}\n\ninterface ParsedGitStatus {\n branch?: GitBranchSnapshot;\n commit?: GitCommitSnapshot;\n status: GitStatusSnapshot;\n}\n\nexport function parseGitStatusPorcelainV2(output: string): ParsedGitStatus {\n const status = emptyGitStatus();\n let branchName: string | undefined;\n let commitHash: string | undefined;\n let upstream: string | undefined;\n\n for (const line of output.split(/\\r?\\n/u)) {\n if (!line) continue;\n if (line.startsWith(\"# branch.oid \")) {\n const value = line.slice(\"# branch.oid \".length).trim();\n if (value && value !== \"(initial)\") commitHash = value;\n continue;\n }\n if (line.startsWith(\"# branch.head \")) {\n branchName = line.slice(\"# branch.head \".length).trim();\n continue;\n }\n if (line.startsWith(\"# branch.upstream \")) {\n upstream = line.slice(\"# branch.upstream \".length).trim();\n continue;\n }\n if (line.startsWith(\"# branch.ab \")) {\n const match = /^# branch\\.ab \\+(\\d+) -(\\d+)$/u.exec(line);\n status.ahead = match?.[1] ? Number(match[1]) : 0;\n status.behind = match?.[2] ? Number(match[2]) : 0;\n continue;\n }\n if (line.startsWith(\"# stash \")) {\n const count = Number(line.slice(\"# stash \".length));\n status.stashed = Number.isSafeInteger(count) && count > 0 ? count : 0;\n continue;\n }\n addPorcelainV2Status(status, line);\n }\n finalizeStatus(status);\n\n const detached = branchName === \"(detached)\";\n const remote = splitUpstream(upstream);\n const branch = branchName\n ? {\n name: detached ? \"HEAD\" : branchName,\n ...remote,\n detached,\n }\n : undefined;\n const commit = commitHash ? { hash: commitHash, detached } : undefined;\n return { branch, commit, status };\n}\n\nexport function parseGitStatusPorcelain(output: string): GitStatusSnapshot {\n const status = emptyGitStatus();\n for (const line of output.split(/\\r?\\n/u)) {\n if (!line) continue;\n if (line.startsWith(\"## \")) {\n const ahead = /\\bahead (\\d+)/u.exec(line);\n const behind = /\\bbehind (\\d+)/u.exec(line);\n status.ahead = ahead?.[1] ? Number(ahead[1]) : 0;\n status.behind = behind?.[1] ? Number(behind[1]) : 0;\n continue;\n }\n const indexStatus = line[0] ?? \" \";\n const worktreeStatus = line[1] ?? \" \";\n if (indexStatus === \"?\" && worktreeStatus === \"?\") {\n status.untracked += 1;\n continue;\n }\n if (isConflict(indexStatus, worktreeStatus)) {\n status.conflicted += 1;\n continue;\n }\n addNormalStatus(status, indexStatus, worktreeStatus);\n if (indexStatus === \"R\" || indexStatus === \"C\") status.renamed += 1;\n }\n finalizeStatus(status);\n return status;\n}\n\nexport function parseGitDiffShortstat(output: string): GitMetricsSnapshot {\n return {\n added: parseShortstatMetric(output, \"insertion(+)\", \"insertions(+)\") ?? 0,\n deleted: parseShortstatMetric(output, \"deletion(-)\", \"deletions(-)\") ?? 0,\n };\n}\n\nfunction parseShortstatMetric(output: string, singularLabel: string, pluralLabel: string): number | undefined {\n for (const field of output.split(\",\")) {\n const trimmed = field.trim();\n const separator = trimmed.indexOf(\" \");\n if (separator <= 0) continue;\n const label = trimmed.slice(separator + 1).trimStart();\n if (label !== singularLabel && label !== pluralLabel) continue;\n const countText = trimmed.slice(0, separator);\n for (const character of countText) {\n if (character < \"0\" || character > \"9\") return undefined;\n }\n const count = Number(countText);\n return Number.isSafeInteger(count) ? count : undefined;\n }\n return undefined;\n}\n\nexport function parseGitState(gitDirectory: string): GitStateSnapshot | undefined {\n const rebaseMerge = join(gitDirectory, \"rebase-merge\");\n if (existsSync(rebaseMerge)) return operationWithProgress(\"REBASING\", rebaseMerge, \"msgnum\", \"end\");\n\n const rebaseApply = join(gitDirectory, \"rebase-apply\");\n if (existsSync(rebaseApply)) {\n const state = existsSync(join(rebaseApply, \"applying\"))\n ? \"AM\"\n : existsSync(join(rebaseApply, \"rebasing\"))\n ? \"REBASING\"\n : \"AM/REBASE\";\n return operationWithProgress(state, rebaseApply, \"next\", \"last\");\n }\n if (existsSync(join(gitDirectory, \"MERGE_HEAD\"))) return { state: \"MERGING\" };\n if (existsSync(join(gitDirectory, \"REVERT_HEAD\"))) return { state: \"REVERTING\" };\n if (existsSync(join(gitDirectory, \"CHERRY_PICK_HEAD\"))) return { state: \"CHERRY-PICKING\" };\n if (existsSync(join(gitDirectory, \"BISECT_LOG\"))) return { state: \"BISECTING\" };\n return undefined;\n}\n\ninterface GitRepositoryMetadata {\n root: string;\n gitDirectory: string;\n worktree?: GitWorktreeSnapshot;\n}\n\nfunction parseGitRepositoryMetadata(output: string): GitRepositoryMetadata | undefined {\n const lines = output.trimEnd().split(/\\r?\\n/u);\n if (lines.length !== 3) return undefined;\n const [path, commonDir, gitDirectory] = lines;\n if (!path || !commonDir || !gitDirectory) return undefined;\n if (![path, commonDir, gitDirectory].every(isAbsolute)) return undefined;\n return {\n root: path,\n gitDirectory,\n worktree: samePath(commonDir, gitDirectory) ? undefined : { name: basename(path) || path, path },\n };\n}\n\nexport function parseGitWorktree(output: string): GitWorktreeSnapshot | undefined {\n return parseGitRepositoryMetadata(output)?.worktree;\n}\n\nfunction addPorcelainV2Status(status: GitStatusSnapshot, line: string) {\n const kind = line[0];\n if (kind === \"?\") {\n status.untracked += 1;\n return;\n }\n if (kind === \"u\") {\n status.conflicted += 1;\n return;\n }\n if (kind !== \"1\" && kind !== \"2\") return;\n const indexStatus = line[2] ?? \".\";\n const worktreeStatus = line[3] ?? \".\";\n addNormalStatus(status, indexStatus, worktreeStatus);\n if (kind === \"2\") status.renamed += 1;\n}\n\nfunction addNormalStatus(status: GitStatusSnapshot, indexStatus: string, worktreeStatus: string) {\n if (indexStatus === \"A\") status.indexAdded += 1;\n if (indexStatus === \"D\") status.indexDeleted += 1;\n if (indexStatus === \"M\") status.indexModified += 1;\n if (indexStatus === \"T\") status.indexTypechanged += 1;\n if (worktreeStatus === \"A\") status.worktreeAdded += 1;\n if (worktreeStatus === \"D\") status.worktreeDeleted += 1;\n if (worktreeStatus === \"M\") status.worktreeModified += 1;\n if (worktreeStatus === \"T\") status.worktreeTypechanged += 1;\n}\n\nfunction finalizeStatus(status: GitStatusSnapshot) {\n status.deleted = status.worktreeDeleted + status.indexDeleted;\n status.modified = status.worktreeModified + status.worktreeAdded;\n status.staged = status.indexModified + status.indexAdded + status.indexTypechanged;\n status.typechanged = status.worktreeTypechanged;\n}\n\nfunction emptyGitStatus(): GitStatusSnapshot {\n return {\n ahead: 0,\n behind: 0,\n stashed: 0,\n conflicted: 0,\n deleted: 0,\n renamed: 0,\n modified: 0,\n staged: 0,\n typechanged: 0,\n untracked: 0,\n worktreeAdded: 0,\n worktreeDeleted: 0,\n worktreeModified: 0,\n worktreeTypechanged: 0,\n indexAdded: 0,\n indexDeleted: 0,\n indexModified: 0,\n indexTypechanged: 0,\n };\n}\n\nfunction splitUpstream(upstream: string | undefined): {\n remoteName?: string;\n remoteBranch?: string;\n} {\n if (!upstream) return {};\n const separator = upstream.indexOf(\"/\");\n if (separator <= 0 || separator === upstream.length - 1) return { remoteBranch: upstream };\n return {\n remoteName: upstream.slice(0, separator),\n remoteBranch: upstream.slice(separator + 1),\n };\n}\n\nfunction withTag(\n commit: GitCommitSnapshot | undefined,\n result:\n | {\n stdout: string;\n code: number;\n killed: boolean;\n }\n | undefined,\n): GitCommitSnapshot | undefined {\n if (!commit || !result || result.code !== 0 || result.killed) return commit;\n const tag = result.stdout.trim();\n return tag ? { ...commit, tag: tag.split(/\\r?\\n/u)[0] } : commit;\n}\n\nfunction operationWithProgress(\n state: string,\n directory: string,\n currentName: string,\n totalName: string,\n): GitStateSnapshot {\n const progressCurrent = readPositiveInteger(join(directory, currentName));\n const progressTotal = readPositiveInteger(join(directory, totalName));\n return progressCurrent !== undefined && progressTotal !== undefined\n ? { state, progressCurrent, progressTotal }\n : { state };\n}\n\nfunction readPositiveInteger(path: string): number | undefined {\n try {\n const value = Number(readFileSync(path, \"utf8\").trim());\n return Number.isSafeInteger(value) && value > 0 ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction samePath(left: string, right: string): boolean {\n const normalizedLeft = resolve(left);\n const normalizedRight = resolve(right);\n return process.platform === \"win32\"\n ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()\n : normalizedLeft === normalizedRight;\n}\n\nfunction isConflict(indexStatus: string, worktreeStatus: string): boolean {\n return (\n (indexStatus === \"D\" && worktreeStatus === \"D\") ||\n (indexStatus === \"A\" && worktreeStatus === \"A\") ||\n indexStatus === \"U\" ||\n worktreeStatus === \"U\"\n );\n}\n\nexport function gitStatusEqual(left: GitStatusSnapshot | undefined, right: GitStatusSnapshot | undefined): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport function gitSnapshotEqual(left: GitSnapshot | undefined, right: GitSnapshot | undefined): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n", "import { spawn } from \"node:child_process\";\nimport type { WorkspaceExec } from \"./types.js\";\n\nconst FORCE_KILL_DELAY_MS = 250;\n\nexport const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>\n new Promise((resolve) => {\n if (options.signal?.aborted) {\n resolve({ stdout: \"\", stderr: \"\", code: 1, killed: true });\n return;\n }\n\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, {\n cwd: options.cwd,\n detached: process.platform !== \"win32\",\n env: explicitEnvironment(options.environment),\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n } catch {\n resolve({ stdout: \"\", stderr: \"\", code: 1, killed: false });\n return;\n }\n\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let outputBytes = 0;\n let killed = false;\n let settled = false;\n let forceKillTimer: NodeJS.Timeout | undefined;\n let timeoutTimer: NodeJS.Timeout | undefined;\n\n const finish = (code: number) => {\n if (settled) return;\n settled = true;\n if (timeoutTimer) clearTimeout(timeoutTimer);\n if (forceKillTimer) clearTimeout(forceKillTimer);\n options.signal?.removeEventListener(\"abort\", terminate);\n resolve({\n stdout: Buffer.concat(stdout).toString(\"utf8\"),\n stderr: Buffer.concat(stderr).toString(\"utf8\"),\n code,\n killed,\n });\n };\n\n const signalProcessTree = (signal: NodeJS.Signals) => {\n const pid = child.pid;\n if (pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-pid, signal);\n return;\n } catch {\n child.kill(signal);\n return;\n }\n }\n try {\n const killer = spawn(\"taskkill.exe\", [\"/pid\", String(pid), \"/t\", \"/f\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n killer.once(\"error\", () => child.kill(signal));\n killer.unref();\n } catch {\n child.kill(signal);\n }\n };\n\n function terminate() {\n if (killed || settled) return;\n killed = true;\n signalProcessTree(\"SIGTERM\");\n forceKillTimer = setTimeout(() => {\n signalProcessTree(\"SIGKILL\");\n child.stdout?.destroy();\n child.stderr?.destroy();\n finish(1);\n }, FORCE_KILL_DELAY_MS);\n }\n\n const collect = (target: Buffer[]) => (data: Buffer | string) => {\n const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);\n const remaining = Math.max(0, options.maxOutputBytes - outputBytes);\n if (remaining > 0) target.push(chunk.subarray(0, remaining));\n outputBytes += chunk.byteLength;\n if (outputBytes > options.maxOutputBytes) terminate();\n };\n\n child.stdout?.on(\"data\", collect(stdout));\n child.stderr?.on(\"data\", collect(stderr));\n child.once(\"error\", () => {\n if (!killed) finish(1);\n });\n child.once(\"close\", (code) => {\n if (!killed) finish(code ?? 1);\n });\n options.signal?.addEventListener(\"abort\", terminate, { once: true });\n if (options.signal?.aborted) terminate();\n timeoutTimer = setTimeout(terminate, options.timeout);\n });\n\nfunction explicitEnvironment(source: Readonly<Record<string, string | undefined>>): NodeJS.ProcessEnv {\n const result: NodeJS.ProcessEnv = Object.create(null);\n for (const [name, value] of Object.entries(source)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || value === undefined || value.includes(\"\\0\")) {\n continue;\n }\n Object.defineProperty(result, name, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return result;\n}\n", "import { getCapabilities } from \"@earendil-works/pi-tui\";\nimport type { GithubPrSnapshot, GithubPrState } from \"../modules/types.js\";\nimport type { WorkspaceExec } from \"./types.js\";\n\nconst GH_TIMEOUT_MS = 10_000;\nconst MAX_GH_OUTPUT_BYTES = 128 * 1024;\nconst MAX_URL_LENGTH = 4_096;\nconst MAX_CHECKS = 1_000;\nconst MAX_FIELD_LENGTH = 128;\nconst RFC3339_TIMESTAMP = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(?:Z|[+-](\\d{2}):(\\d{2}))$/u;\nexport const TERMINAL_PR_LIFETIME_MS = 24 * 60 * 60 * 1_000;\n\nconst GH_PR_FIELDS = [\n \"number\",\n \"isDraft\",\n \"url\",\n \"state\",\n \"closedAt\",\n \"mergedAt\",\n \"reviewDecision\",\n \"statusCheckRollup\",\n] as const;\n\ninterface GithubPrQueryOptions {\n platform?: NodeJS.Platform;\n environment?: Readonly<Record<string, string | undefined>>;\n}\n\ninterface CheckSummary {\n failed: number;\n pending: number;\n total: number;\n}\n\ntype PullRequestState = \"OPEN\" | \"CLOSED\" | \"MERGED\";\ntype ReviewDecision = \"APPROVED\" | \"CHANGES_REQUESTED\" | \"REVIEW_REQUIRED\" | \"\";\n\nexport function ghPrViewInvocation(platform: NodeJS.Platform = process.platform): {\n command: string;\n args: string[];\n} {\n return {\n command: platform === \"win32\" ? \"gh.exe\" : \"gh\",\n args: [\"pr\", \"view\", \"--json\", GH_PR_FIELDS.join(\",\")],\n };\n}\n\nexport function githubPrEnvironment(\n source: Readonly<Record<string, string | undefined>> = process.env,\n): Record<string, string | undefined> {\n const environment: Record<string, string | undefined> = Object.create(null);\n for (const [name, value] of Object.entries(source)) {\n const normalized = name.toUpperCase();\n if (normalized === \"GH_HOST\" || normalized === \"GH_REPO\") continue;\n Object.defineProperty(environment, name, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return environment;\n}\n\nexport async function queryGithubPr(\n exec: WorkspaceExec,\n cwd: string,\n signal?: AbortSignal,\n now = Date.now(),\n options: GithubPrQueryOptions = {},\n): Promise<GithubPrSnapshot | undefined> {\n const invocation = ghPrViewInvocation(options.platform);\n try {\n const result = await exec(invocation.command, invocation.args, {\n cwd,\n signal,\n timeout: GH_TIMEOUT_MS,\n maxOutputBytes: MAX_GH_OUTPUT_BYTES,\n environment: githubPrEnvironment(options.environment),\n });\n if (result.killed || result.code !== 0) return undefined;\n if (Buffer.byteLength(result.stdout) > MAX_GH_OUTPUT_BYTES) return undefined;\n return buildGithubPrSnapshot(JSON.parse(result.stdout), now);\n } catch {\n return undefined;\n }\n}\n\nexport function buildGithubPrSnapshot(value: unknown, now = Date.now()): GithubPrSnapshot | undefined {\n try {\n const pr = record(value);\n const number = positiveInteger(pr.number);\n const isDraft = requiredBoolean(pr.isDraft);\n const url = requiredBoundedString(pr.url, MAX_URL_LENGTH, true);\n const state = pullRequestState(pr.state);\n const closedAt = optionalTimestamp(pr.closedAt);\n const mergedAt = optionalTimestamp(pr.mergedAt);\n const reviewDecision = reviewDecisionValue(pr.reviewDecision);\n const checks = summarizeChecks(pr.statusCheckRollup);\n const expiresAt = terminalExpiry(state, closedAt, mergedAt);\n if (state !== \"OPEN\" && (expiresAt === undefined || now >= expiresAt)) return undefined;\n\n const presentationState: GithubPrState =\n state === \"MERGED\" ? \"merged\" : state === \"CLOSED\" ? \"closed\" : isDraft ? \"draft\" : \"open\";\n const checksText = formatChecks(checks);\n const review = formatReview(reviewDecision);\n const status = compactStatus(presentationState, checks, checksText, review);\n const snapshot: GithubPrSnapshot = {\n number: String(number),\n link: osc8Link(url, `#${number}`),\n state: presentationState,\n checks: checksText,\n review,\n status,\n ...(expiresAt === undefined ? {} : { expiresAt }),\n };\n return Object.freeze(snapshot);\n } catch {\n return undefined;\n }\n}\n\nexport function githubPrSnapshotEqual(\n left: GithubPrSnapshot | undefined,\n right: GithubPrSnapshot | undefined,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction terminalExpiry(\n state: PullRequestState,\n closedAt: number | undefined,\n mergedAt: number | undefined,\n): number | undefined {\n if (state === \"OPEN\") return undefined;\n const terminalAt = state === \"MERGED\" ? mergedAt : closedAt;\n return terminalAt === undefined ? undefined : terminalAt + TERMINAL_PR_LIFETIME_MS;\n}\n\nfunction summarizeChecks(value: unknown): CheckSummary {\n if (!Array.isArray(value) || value.length > MAX_CHECKS) throw new Error(\"Invalid PR checks\");\n const summary: CheckSummary = { failed: 0, pending: 0, total: value.length };\n for (const item of value) {\n const check = record(item);\n const state = optionalUppercase(check.state);\n const status = optionalUppercase(check.status);\n const conclusion = optionalUppercase(check.conclusion);\n if (state === \"SUCCESS\") continue;\n if (state === \"FAILURE\" || state === \"ERROR\") {\n summary.failed += 1;\n continue;\n }\n if (state === \"PENDING\" || state === \"EXPECTED\") {\n summary.pending += 1;\n continue;\n }\n if (status && status !== \"COMPLETED\") {\n summary.pending += 1;\n continue;\n }\n if (conclusion === \"SUCCESS\" || conclusion === \"SKIPPED\" || conclusion === \"NEUTRAL\") {\n continue;\n }\n if (\n conclusion === \"FAILURE\" ||\n conclusion === \"CANCELLED\" ||\n conclusion === \"TIMED_OUT\" ||\n conclusion === \"ACTION_REQUIRED\" ||\n conclusion === \"STARTUP_FAILURE\"\n ) {\n summary.failed += 1;\n continue;\n }\n summary.pending += 1;\n }\n return summary;\n}\n\nfunction formatChecks(checks: CheckSummary): string {\n if (checks.total === 0) return \"-\";\n const passed = checks.total - checks.failed - checks.pending;\n return [compactCount(\"\u2713\", passed), compactCount(\"\u00D7\", checks.failed), compactCount(\"\u2026\", checks.pending)]\n .filter(Boolean)\n .join(\" \");\n}\n\nfunction compactCount(symbol: string, count: number): string {\n return count > 0 ? `${symbol}${count}` : \"\";\n}\n\nfunction formatReview(review: ReviewDecision): string {\n if (review === \"APPROVED\") return \"R\u2713\";\n if (review === \"CHANGES_REQUESTED\") return \"R\u00D7\";\n if (review === \"REVIEW_REQUIRED\") return \"R?\";\n return \"\";\n}\n\nfunction compactStatus(state: GithubPrState, checks: CheckSummary, checksText: string, review: string): string {\n if (state === \"merged\") return \"M\";\n if (state === \"closed\") return \"C\";\n if (state === \"draft\") return \"D\";\n if (checks.failed > 0) return compactCount(\"\u00D7\", checks.failed);\n if (review === \"R\u00D7\") return review;\n if (checks.pending > 0) return compactCount(\"\u2026\", checks.pending);\n if (review === \"R\u2713\" || review === \"R?\") return review;\n return checksText;\n}\n\nfunction osc8Link(value: string, label: string): string {\n if (!getCapabilities().hyperlinks || hasTerminalControls(value)) return label;\n try {\n const url = new URL(value);\n if ((url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.username || url.password) {\n return label;\n }\n const normalized = url.toString();\n if (normalized.length > MAX_URL_LENGTH || hasTerminalControls(normalized)) return label;\n return `\\u001b]8;;${normalized}\\u0007${label}\\u001b]8;;\\u0007`;\n } catch {\n return label;\n }\n}\n\nfunction hasTerminalControls(value: string): boolean {\n return Array.from(value).some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return (\n codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) || (codePoint >= 0xd800 && codePoint <= 0xdfff)\n );\n });\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\"Expected PR object\");\n }\n return value as Record<string, unknown>;\n}\n\nfunction positiveInteger(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error(\"Invalid PR number\");\n }\n return value;\n}\n\nfunction requiredBoolean(value: unknown): boolean {\n if (typeof value !== \"boolean\") throw new Error(\"Invalid PR boolean\");\n return value;\n}\n\nfunction requiredBoundedString(value: unknown, maxLength: number, allowEmpty = false): string {\n if (typeof value !== \"string\" || value.length > maxLength || (!allowEmpty && value.length === 0)) {\n throw new Error(\"Invalid PR string\");\n }\n return value;\n}\n\nfunction optionalUppercase(value: unknown): string | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n return requiredBoundedString(value, MAX_FIELD_LENGTH).toUpperCase();\n}\n\nfunction optionalTimestamp(value: unknown): number | undefined {\n if (value === null || value === undefined || value === \"\") return undefined;\n const text = requiredBoundedString(value, MAX_FIELD_LENGTH);\n const match = RFC3339_TIMESTAMP.exec(text);\n if (!match) throw new Error(\"Invalid PR timestamp\");\n const [, yearText, monthText, dayText, hourText, minuteText, secondText, offsetHourText, offsetMinuteText] = match;\n const year = Number(yearText);\n const month = Number(monthText);\n const day = Number(dayText);\n const hour = Number(hourText);\n const minute = Number(minuteText);\n const second = Number(secondText);\n const offsetHour = Number(offsetHourText ?? 0);\n const offsetMinute = Number(offsetMinuteText ?? 0);\n if (\n month < 1 ||\n month > 12 ||\n day < 1 ||\n day > daysInMonth(year, month) ||\n hour > 23 ||\n minute > 59 ||\n second > 59 ||\n offsetHour > 23 ||\n offsetMinute > 59\n ) {\n throw new Error(\"Invalid PR timestamp\");\n }\n const timestamp = Date.parse(text);\n if (!Number.isFinite(timestamp)) throw new Error(\"Invalid PR timestamp\");\n return timestamp;\n}\n\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) {\n const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n return leapYear ? 29 : 28;\n }\n return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;\n}\n\nfunction pullRequestState(value: unknown): PullRequestState {\n if (value === \"OPEN\" || value === \"CLOSED\" || value === \"MERGED\") return value;\n throw new Error(\"Invalid PR state\");\n}\n\nfunction reviewDecisionValue(value: unknown): ReviewDecision {\n if (value === null || value === undefined || value === \"\" || value === \"UNKNOWN\") return \"\";\n if (value === \"APPROVED\" || value === \"CHANGES_REQUESTED\" || value === \"REVIEW_REQUIRED\") {\n return value;\n }\n throw new Error(\"Invalid PR review decision\");\n}\n", "export interface AsyncRefreshControllerOptions<Input, Snapshot> {\n read(input: Input, signal: AbortSignal): Promise<Snapshot>;\n equal(left: Snapshot | undefined, right: Snapshot): boolean;\n publish(snapshot: Snapshot): void;\n onError?(error: unknown): void;\n}\n\ninterface RefreshRequest<Input> {\n generation: number;\n requestId: number;\n input: Input;\n}\n\ninterface ActiveRefresh<Input> {\n request: RefreshRequest<Input>;\n controller: AbortController;\n}\n\n/** Coalesces refreshes to one active read plus the latest pending request. */\nexport class AsyncRefreshController<Input, Snapshot> {\n private generation: number | undefined;\n private requestId = 0;\n private active: ActiveRefresh<Input> | undefined;\n private pending: RefreshRequest<Input> | undefined;\n private current: Snapshot | undefined;\n\n constructor(private readonly options: AsyncRefreshControllerOptions<Input, Snapshot>) {}\n\n start(generation: number): void {\n this.cancelActive(\"Refresh generation replaced\");\n this.generation = generation;\n this.requestId += 1;\n this.pending = undefined;\n this.current = undefined;\n }\n\n clear(): void {\n this.current = undefined;\n }\n\n request(input: Input): void {\n if (this.generation === undefined) return;\n const request = {\n generation: this.generation,\n requestId: ++this.requestId,\n input,\n };\n if (this.active) {\n this.pending = request;\n return;\n }\n this.run(request);\n }\n\n stop(): void {\n this.generation = undefined;\n this.requestId += 1;\n this.pending = undefined;\n this.current = undefined;\n this.cancelActive(\"Refresh controller stopped\");\n }\n\n private run(request: RefreshRequest<Input>): void {\n if (!this.isCurrentTarget(request)) return;\n const active: ActiveRefresh<Input> = {\n request,\n controller: new AbortController(),\n };\n this.active = active;\n void this.options\n .read(request.input, active.controller.signal)\n .then((snapshot) => {\n if (this.active !== active || !this.isCurrentRequest(request)) return;\n if (this.options.equal(this.current, snapshot)) return;\n this.current = snapshot;\n this.options.publish(snapshot);\n })\n .catch((error: unknown) => {\n if (this.active === active && this.isCurrentRequest(request) && !active.controller.signal.aborted) {\n this.options.onError?.(error);\n }\n })\n .finally(() => {\n if (this.active !== active) return;\n this.active = undefined;\n const pending = this.pending;\n this.pending = undefined;\n if (pending) this.run(pending);\n });\n }\n\n private cancelActive(reason: string): void {\n this.active?.controller.abort(new DOMException(reason, \"AbortError\"));\n }\n\n private isCurrentTarget(request: RefreshRequest<Input>): boolean {\n return this.generation !== undefined && request.generation === this.generation;\n }\n\n private isCurrentRequest(request: RefreshRequest<Input>): boolean {\n return this.isCurrentTarget(request) && request.requestId === this.requestId;\n }\n}\n", "import type { ModuleName } from \"../modules/catalog.js\";\nimport { reachableModuleRequirements } from \"../modules/render.js\";\nimport type { WorkspaceSnapshot } from \"../modules/types.js\";\nimport { createFileSystem } from \"./helpers.js\";\nimport {\n type CollectorContext,\n type MutableModuleSnapshot,\n PRIVATE_STYLE_SELECTOR,\n type WorkspaceEntry,\n type WorkspaceRefreshInput,\n} from \"./types.js\";\n\nexport type { WorkspaceExec, WorkspaceExecResult, WorkspaceRefreshInput } from \"./types.js\";\n\nexport async function collectWorkspaceSnapshot(input: WorkspaceRefreshInput): Promise<WorkspaceSnapshot> {\n const requirements = reachableModuleRequirements(input.config);\n if (input.signal?.aborted || !hasWorkspaceRequirement(requirements)) return freezeSnapshot({});\n const fs = createFileSystem(input);\n let listing: Promise<readonly WorkspaceEntry[]> | undefined;\n const context: CollectorContext = {\n input,\n fs,\n requirements,\n entries() {\n listing ??= fs.readDirectory(input.cwd);\n return listing;\n },\n options(name) {\n return input.config.modules[name].options;\n },\n needs(name, variable) {\n const variables = requirements.get(name);\n return Boolean(variables && (variable === undefined || variables.has(variable)));\n },\n };\n const modules: MutableModuleSnapshot = {};\n if (requirements.has(\"package\")) {\n const { collectPackage } = await import(\"./package.js\");\n if (input.signal?.aborted) return freezeSnapshot({});\n const packageValues = await collectPackage(context);\n if (input.signal?.aborted) return freezeSnapshot({});\n if (packageValues) modules.package = packageValues;\n }\n for (const descriptor of COLLECTOR_GROUPS) {\n if (!descriptor.modules.some((name) => requirements.has(name))) continue;\n if (input.signal?.aborted) return freezeSnapshot({});\n const collector = await descriptor.load();\n if (input.signal?.aborted) return freezeSnapshot({});\n mergeModules(modules, await collector(context));\n }\n return input.signal?.aborted ? freezeSnapshot({}) : freezeSnapshot(modules);\n}\n\nexport function workspaceSnapshotEqual(\n left: WorkspaceSnapshot | undefined,\n right: WorkspaceSnapshot | undefined,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction hasWorkspaceRequirement(requirements: ReadonlyMap<ModuleName, ReadonlySet<string>>): boolean {\n return [...requirements.keys()].some((name) => !BUILT_IN_ONLY_MODULES.has(name));\n}\n\ntype WorkspaceCollector = (context: CollectorContext) => Promise<MutableModuleSnapshot>;\n\nconst COLLECTOR_GROUPS: readonly {\n modules: readonly ModuleName[];\n load(): Promise<WorkspaceCollector>;\n}[] = [\n {\n modules: [\"nodejs\", \"python\", \"rust\", \"golang\", \"bun\", \"deno\"],\n load: async () => (await import(\"./languages.js\")).collectLanguages,\n },\n {\n modules: [\"mise\", \"direnv\", \"pixi\", \"conda\", \"nix_shell\", \"guix_shell\"],\n load: async () => (await import(\"./development.js\")).collectDevelopment,\n },\n {\n modules: [\"docker_context\", \"kubernetes\", \"terraform\"],\n load: async () => (await import(\"./deployment.js\")).collectDeployment,\n },\n {\n modules: [\"aws\", \"gcloud\", \"azure\", \"openstack\"],\n load: async () => (await import(\"./cloud.js\")).collectCloud,\n },\n {\n modules: [\"container\", \"hostname\", \"os\", \"username\"],\n load: async () => (await import(\"./execution.js\")).collectExecution,\n },\n];\n\nconst BUILT_IN_ONLY_MODULES = new Set<ModuleName>([\n \"brand\",\n \"provider\",\n \"model\",\n \"thinking\",\n \"directory\",\n \"git_worktree\",\n \"git_branch\",\n \"github_pr\",\n \"git_commit\",\n \"git_state\",\n \"git_metrics\",\n \"git_status\",\n \"activity\",\n \"context\",\n \"tokens\",\n \"cost\",\n \"time\",\n \"turn\",\n \"fill\",\n \"extension_status\",\n]);\n\nfunction mergeModules(target: MutableModuleSnapshot, source: MutableModuleSnapshot): void {\n for (const [name, values] of Object.entries(source)) {\n Object.defineProperty(target, name, {\n value: values,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n}\n\nfunction freezeSnapshot(modules: MutableModuleSnapshot): WorkspaceSnapshot {\n const styleSelectors: Record<string, string> = {};\n for (const [name, values] of Object.entries(modules)) {\n const selector = Object.hasOwn(values, PRIVATE_STYLE_SELECTOR) ? values[PRIVATE_STYLE_SELECTOR] : undefined;\n delete values[PRIVATE_STYLE_SELECTOR];\n if (selector !== undefined) styleSelectors[name] = selector;\n Object.freeze(values);\n }\n return Object.freeze({\n modules: Object.freeze(modules),\n ...(Object.keys(styleSelectors).length > 0 ? { styleSelectors: Object.freeze(styleSelectors) } : {}),\n });\n}\n", "import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\n\ninterface UsageLike {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n}\n\nexport interface FooterUsageSummary {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n latestCacheHitRate?: number;\n}\n\nexport function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUsageSummary {\n const totals: FooterUsageSummary = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: 0,\n };\n\n for (const entry of entries) {\n let usage: UsageLike | undefined;\n if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n usage = entry.message.usage;\n const input = usage.input ?? 0;\n const cacheRead = usage.cacheRead ?? 0;\n const cacheWrite = usage.cacheWrite ?? 0;\n const promptTokens = input + cacheRead + cacheWrite;\n totals.latestCacheHitRate = promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;\n } else if (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n usage = entry.message.usage;\n } else if (entry.type === \"compaction\" || entry.type === \"branch_summary\" || entry.type === \"usage\") {\n usage = entry.usage;\n }\n if (!usage) continue;\n\n totals.input += usage.input ?? 0;\n totals.output += usage.output ?? 0;\n totals.cacheRead += usage.cacheRead ?? 0;\n totals.cacheWrite += usage.cacheWrite ?? 0;\n totals.cost += usage.cost?.total ?? 0;\n }\n\n return totals;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,UAAU,gBAAgB;AAC5C;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,mBAAAA,kBAAiB,wBAAwB;;;ACPlD,SAAS,YAAY,oBAAoB;AACzC,SAAS,UAAU,YAAY,MAAM,eAAe;AAYpD,IAAM,iBAAiB;AAQvB,eAAsB,gBACpB,IACA,KACA,SACkC;AAClC,QAAM,gBAAgB,GAAG;AAAA,IACvB;AAAA,IACA,CAAC,uBAAuB,UAAU,kBAAkB,YAAY,gBAAgB,0BAA0B;AAAA,IAC1G,EAAE,KAAK,QAAQ,QAAQ,QAAQ,SAAS,eAAe;AAAA,EACzD;AACA,Q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B,UAAU,QAAQ,KAAK;AAAA,IACvB,YAAY,QAAQ,KAAK;AAAA,IACzB,WAAW,QAAQ,KAAK;AAAA,IACxB,aAAa,QAAQ,KAAK;AAAA,IAC1B,UAAU,QAAQ;AAAA,IAClB,WAAW,QAAQ;AAAA,IACnB,mBAAmB,WAAW,qBAAqB;AAAA,IACnD,KAAK,oBAAI,KAAK;AAAA,EAChB;AACF;AAEA,SAAS,cAAc,KAA+B;AACpD,SAAO,IAAI,eAAe,UAAU,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,aAAa,MAAM,QAAQ,SAAS,MAAM,EAC9G;AACL;AAEA,SAAS,qBAAqB,KAAgC;AAC5D,QAAM,QAAQ,IAAI;AAClB,SAAO,UAAU,WAAc,MAAM,aAAa,iBAAiB,IAAI,cAAc,aAAa,KAAK;AACzG;AAEA,SAAS,kBAAkB,QAAsC;AAC/D,QAAM,UAAU,OAAO,YAAY,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,SAAS,KAAK,OAAO;AACzE,QAAM,YAAY,OAAO,YAAY,SAAS,QAAQ;AACtD,SAAO,CAAC,yBAAyB,QAAQ,KAAK,IAAI,CAAC,IAAI,GAAI,YAAY,IAAI,CAAC,IAAI,SAAS,OAAO,IAAI,CAAC,CAAE,EAAE,KAAK,GAAG;AACnH;AAEO,SAAS,wBAAwB,QAAgB,OAAyB;AAC/E,MAAI,SAAS,EAAG,QAAO,CAAC;AACxB,SAAO,iBAAiB,QAAQ,KAAK;AACvC;",
|
|
6
6
|
"names": ["getCapabilities", "resolve", "getCapabilities"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-starship",
|
|
3
|
-
"version": "0.56.
|
|
3
|
+
"version": "0.56.2",
|
|
4
4
|
"description": "Native Starship-style TOML statusline and configuration skill for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,9 +48,9 @@
|
|
|
48
48
|
"@earendil-works/pi-tui": "*"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
52
|
-
"@earendil-works/pi-tui": "0.
|
|
53
|
-
"@types/node": "26.
|
|
51
|
+
"@earendil-works/pi-coding-agent": "0.86.0",
|
|
52
|
+
"@earendil-works/pi-tui": "0.86.0",
|
|
53
|
+
"@types/node": "26.6.2",
|
|
54
54
|
"esbuild": "0.28.2",
|
|
55
55
|
"typescript": "7.0.2"
|
|
56
56
|
},
|
package/src/config.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
3
|
import { dirname, join } from "node:path";
|
|
5
|
-
import type
|
|
4
|
+
import { parse as parseToml, type TomlTable } from "smol-toml";
|
|
6
5
|
import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
|
|
7
6
|
import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
|
|
8
7
|
import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
|
|
@@ -97,14 +96,6 @@ export const BUILT_IN_CONFIG: StarshipConfig = {
|
|
|
97
96
|
|
|
98
97
|
export const BUILT_IN_EXAMPLE = `# Native Pi modules with Starship-compatible format and style syntax.\n${BUILT_IN_FORMAT_DOCUMENT}\n`;
|
|
99
98
|
|
|
100
|
-
const require = createRequire(import.meta.url);
|
|
101
|
-
let parseTomlImplementation: typeof import("smol-toml")["parse"] | undefined;
|
|
102
|
-
|
|
103
|
-
function parseToml(document: string): TomlTable {
|
|
104
|
-
parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
|
|
105
|
-
return parseTomlImplementation(document);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
99
|
export function settingsFilePath(agentDir: string): string {
|
|
109
100
|
return join(agentDir, CONFIG_FILE_NAME);
|
|
110
101
|
}
|
package/src/usage.ts
CHANGED
|
@@ -37,7 +37,7 @@ export function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUs
|
|
|
37
37
|
totals.latestCacheHitRate = promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;
|
|
38
38
|
} else if (entry.type === "message" && entry.message.role === "toolResult") {
|
|
39
39
|
usage = entry.message.usage;
|
|
40
|
-
} else if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
40
|
+
} else if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "usage") {
|
|
41
41
|
usage = entry.usage;
|
|
42
42
|
}
|
|
43
43
|
if (!usage) continue;
|