import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; import { delimiter, dirname, join, resolve } from "node:path"; import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent"; import { Type } from "@sinclair/typebox"; import { getAgentDir, getAgentPath, readJsonFile } from "../../src/shared/agent-paths"; import { notify } from "../../src/shared/ui"; import { loadCompactionConfig } from "../compaction/config"; import { resolveCompactionModelSelection } from "../compaction/model-selection"; import { describeEffectiveModel, describeSessionOverride, restoreSessionOverride } from "../compaction/state"; import type { CompactionState } from "../compaction/types"; import { formatModelRef } from "../../src/shared/model"; import { collectSubagentSystemStatus, type SubagentSystemStatus } from "../../../vera-subagents/src/public"; import { collectSchemeSandboxStatus, type SchemeSandboxStatus } from "../../../vera-scheme-sandbox/src/status"; import { defaultStatusBadge, kylinFrameForCall, kylinFrameForResult, type PanelItem, type PanelItemState, type PanelSection, type PanelStatus, renderCommandPanel, } from "../../../vera-theme/src/public"; interface PackageStatus { name: string; source: string; configured: boolean; present: boolean; } interface FileStatus { label: string; path: string; present: boolean; } interface WebToolReadiness { configuredKeys: string[]; missingKeys: string[]; webSearchReady: boolean; webReadReady: boolean; docsSearchReady: boolean; academicSearchReady: boolean; documentParseReady: boolean; } interface CompactionStatus { enabled: boolean; configSource: string; currentModel: string; override: string; effectiveModel: string; source: string; availableRefs: string[]; fallbackRefs: string[]; warnings: string[]; ready: boolean; } interface MemoryStatus { enabled: boolean; configSource: string; dbPath: string; dbPresent: boolean; shortTtlDays: number; rulesPresent: boolean; } interface CccStatus { available: boolean; binaryPath: string | null; cwd: string; initialized: boolean; indexed: boolean; reason?: string; statusSummary: string; } type VeraOverallStatus = "ok" | "partial" | "degraded"; interface VeraStatusSummary { overallStatus: VeraOverallStatus; coreIssues: string[]; optionalIssues: string[]; } function bool(value: boolean): string { return value ? "yes" : "no"; } function previewList(values: string[], max = 4): string { if (values.length === 0) return "(none)"; if (values.length <= max) return values.join(", "); return `${values.slice(0, max).join(", ")} … +${values.length - max} more`; } function normalizePackageSource(entry: unknown): string | null { if (typeof entry === "string") return entry; if (entry && typeof entry === "object" && typeof (entry as any).source === "string") { return (entry as any).source; } return null; } function getPackageStatuses(settings: any): PackageStatus[] { const configuredSources = new Set((settings?.packages ?? []).map(normalizePackageSource).filter(Boolean) as string[]); const expected = [ { name: "vera-session-tools", source: "./packages/vera-session-tools" }, { name: "vera-search-tools", source: "./packages/vera-search-tools" }, { name: "vera-web-tools", source: "./packages/vera-web-tools" }, { name: "vera-ccc-tools", source: "./packages/vera-ccc-tools" }, { name: "vera-theme", source: "./packages/vera-theme" }, { name: "vera-memory", source: "./packages/vera-memory" }, { name: "vera-subagents", source: "./packages/vera-subagents" }, { name: "vera-scheme-sandbox", source: "./packages/vera-scheme-sandbox" }, ]; return expected.map((pkg) => ({ ...pkg, configured: configuredSources.has(pkg.source), present: existsSync(getAgentPath(pkg.source.replace(/^\.\//, ""))), })); } function getConfigStatuses(agentDir: string): FileStatus[] { return [ { label: "output-guard config", path: join(agentDir, "config", "output-guard.json"), present: existsSync(join(agentDir, "config", "output-guard.json")) }, { label: "compaction config", path: join(agentDir, "config", "compaction.json"), present: existsSync(join(agentDir, "config", "compaction.json")) }, { label: "vera-theme config", path: join(agentDir, "config", "vera-theme.json"), present: existsSync(join(agentDir, "config", "vera-theme.json")) }, { label: "proxy-compat config", path: join(agentDir, "config", "proxy-compat.json"), present: existsSync(join(agentDir, "config", "proxy-compat.json")) }, { label: "memory config", path: join(agentDir, "config", "memory.json"), present: existsSync(join(agentDir, "config", "memory.json")) }, { label: "SOUL rules", path: join(agentDir, "rules", "SOUL.md"), present: existsSync(join(agentDir, "rules", "SOUL.md")) }, { label: "memory rules", path: join(agentDir, "rules", "core", "memory-rules.md"), present: existsSync(join(agentDir, "rules", "core", "memory-rules.md")) }, ]; } function getLocalExtensionStatuses(agentDir: string): FileStatus[] { return [ { label: "proxy-compat extension", path: join(agentDir, "extensions", "proxy-compat.ts"), present: existsSync(join(agentDir, "extensions", "proxy-compat.ts")) }, { label: "rtk-rewrite extension", path: join(agentDir, "extensions", "rtk-rewrite.ts"), present: existsSync(join(agentDir, "extensions", "rtk-rewrite.ts")) }, ]; } function hasServiceKey(auth: any, service: string, envVar?: string): boolean { if (envVar && process.env[envVar]) return true; return Boolean(auth?.[service]?.key); } function getWebToolReadiness(agentDir: string): WebToolReadiness { const auth = readJsonFile(join(agentDir, "auth.json"), {}); const serviceChecks = [ { service: "exa", envVar: "EXA_API_KEY" }, { service: "brave", envVar: "BRAVE_API_KEY" }, { service: "metaso", envVar: "METASO_API_KEY" }, { service: "jina", envVar: "JINA_API_KEY" }, { service: "tavily", envVar: "TAVILY_API_KEY" }, { service: "context7", envVar: "CONTEXT7_API_KEY" }, { service: "openalex", envVar: "OPENALEX_API_KEY" }, { service: "mineru", envVar: "MINERU_API_KEY" }, ]; const configuredKeys = serviceChecks .filter(({ service, envVar }) => hasServiceKey(auth, service, envVar)) .map(({ service }) => service); const missingKeys = serviceChecks .filter(({ service, envVar }) => !hasServiceKey(auth, service, envVar)) .map(({ service }) => service); const searchProviders = ["exa", "brave", "metaso", "jina"]; const searchReadyCount = searchProviders.filter((service) => configuredKeys.includes(service)).length; return { configuredKeys, missingKeys, webSearchReady: searchReadyCount > 0, webReadReady: configuredKeys.includes("tavily"), docsSearchReady: configuredKeys.includes("context7"), academicSearchReady: configuredKeys.includes("openalex"), documentParseReady: configuredKeys.includes("mineru"), }; } function getCompactionStatus(ctx: ExtensionContext): CompactionStatus { const loaded = loadCompactionConfig(ctx.cwd); const state: CompactionState = { config: loaded.config, configSource: loaded.source, sessionOverride: restoreSessionOverride(ctx.sessionManager), lastRun: null, }; const selection = resolveCompactionModelSelection(ctx, state); return { enabled: loaded.config.enabled, configSource: loaded.source, currentModel: formatModelRef(ctx.model) || "(none)", override: describeSessionOverride(state.sessionOverride), effectiveModel: describeEffectiveModel(selection.selected), source: selection.source, availableRefs: selection.availableRefs, fallbackRefs: selection.models.slice(1).map((model) => formatModelRef(model)).filter(Boolean), warnings: selection.warnings, ready: loaded.config.enabled && selection.selected !== null, }; } function getMemoryStatus(agentDir: string, cwd: string): MemoryStatus { const defaultConfigPath = join(agentDir, "config", "memory.json"); const projectConfigPath = join(cwd, ".pi", "config", "memory.json"); const defaults = { enabled: true, database: { path: getAgentPath("state", "vera-memory", "memory.sqlite") }, defaults: { shortTtlDays: 14 }, }; let config = { enabled: defaults.enabled, database: { ...defaults.database }, defaults: { ...defaults.defaults }, }; let configSource = "built-in defaults"; if (existsSync(defaultConfigPath)) { const parsed = readJsonFile(defaultConfigPath, {}); config = { ...config, ...parsed, database: { ...config.database, ...(parsed.database ?? {}) }, defaults: { ...config.defaults, ...(parsed.defaults ?? {}) }, }; configSource = defaultConfigPath; } if (existsSync(projectConfigPath)) { const parsed = readJsonFile(projectConfigPath, {}); config = { ...config, ...parsed, database: { ...config.database, ...(parsed.database ?? {}) }, defaults: { ...config.defaults, ...(parsed.defaults ?? {}) }, }; configSource = projectConfigPath; } const activeConfigPath = configSource === projectConfigPath ? projectConfigPath : configSource === defaultConfigPath ? defaultConfigPath : null; const dbPath = resolveConfigPath(config.database?.path || defaults.database.path, activeConfigPath); const rulesPath = join(agentDir, "rules", "core", "memory-rules.md"); return { enabled: Boolean(config.enabled), configSource, dbPath, dbPresent: existsSync(dbPath), shortTtlDays: Number(config.defaults?.shortTtlDays ?? defaults.defaults.shortTtlDays), rulesPresent: existsSync(rulesPath), }; } function resolveConfigPath(targetPath: string, configPath: string | null): string { if (targetPath.startsWith("/")) return targetPath; if (configPath) return resolve(dirname(configPath), targetPath); return resolve(agentDirFallback(), targetPath); } function agentDirFallback(): string { return getAgentDir(); } function findExecutableInPath(command: string): string | null { const pathValue = process.env.PATH ?? ""; const pathEntries = pathValue.split(delimiter).filter(Boolean); const isWindows = process.platform === "win32"; const pathext = isWindows ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM") .split(";") .filter(Boolean) : [""]; for (const dir of pathEntries) { if (isWindows) { const hasExtension = /\.[^./\\]+$/.test(command); const candidates = hasExtension ? [command] : pathext.map((ext) => `${command}${ext.toLowerCase()}`); for (const candidate of candidates) { const fullPath = join(dir, candidate); if (existsSync(fullPath)) return fullPath; } continue; } const fullPath = join(dir, command); if (existsSync(fullPath)) return fullPath; } return null; } function firstMeaningfulLine(text: string): string { return text .split(/\r?\n/) .map((line) => line.trim()) .find(Boolean) ?? "(no output)"; } async function probeRtk(): Promise<{ available: boolean; version: string | null; reason?: string }> { return await new Promise((resolve) => { execFile("rtk", ["--version"], { timeout: 3000 }, (err, stdout) => { if (err) { resolve({ available: false, version: null, reason: "rtk not found or not in PATH" }); return; } const match = stdout.match(/(\d+)\.(\d+)\.(\d+)/); if (!match) { resolve({ available: false, version: null, reason: "could not parse version" }); return; } resolve({ available: true, version: match[0] }); }); }); } async function probeCcc(ctx: ExtensionContext): Promise { const binaryPath = findExecutableInPath("ccc"); if (!binaryPath) { return { available: false, binaryPath: null, cwd: ctx.cwd, initialized: false, indexed: false, reason: "ccc not found or not in PATH", statusSummary: "binary unavailable", }; } return await new Promise((resolve) => { execFile( binaryPath, ["status"], { cwd: ctx.cwd, timeout: 10_000, maxBuffer: 512 * 1024, env: { ...process.env, NO_COLOR: "1", TERM: "dumb", }, }, (err, stdout, stderr) => { const combined = [String(stdout ?? "").trim(), String(stderr ?? "").trim()].filter(Boolean).join("\n\n").trim(); if (!err) { const initialized = /Settings:|Project:/i.test(combined); const indexed = /Index DB:|Index stats:/i.test(combined) && !/Index not created yet\./i.test(combined); resolve({ available: true, binaryPath, cwd: ctx.cwd, initialized, indexed, statusSummary: initialized ? indexed ? "initialized · index ready" : "initialized · index not built" : firstMeaningfulLine(combined), }); return; } if (/Not in an initialized project directory\./i.test(combined)) { resolve({ available: true, binaryPath, cwd: ctx.cwd, initialized: false, indexed: false, reason: "project not initialized", statusSummary: "project not initialized", }); return; } resolve({ available: true, binaryPath, cwd: ctx.cwd, initialized: false, indexed: false, reason: firstMeaningfulLine(combined || String((err as any)?.message ?? "ccc status failed")), statusSummary: firstMeaningfulLine(combined || String((err as any)?.message ?? "ccc status failed")), }); }, ); }); } function summarizeStatus(input: { packageStatuses: PackageStatus[]; configStatuses: FileStatus[]; localExtensions: FileStatus[]; web: WebToolReadiness; compaction: CompactionStatus; memory: MemoryStatus; ccc: CccStatus; subagents: SubagentSystemStatus; rtk: { available: boolean; version: string | null; reason?: string }; schemeSandbox: SchemeSandboxStatus; }): VeraStatusSummary { const coreIssues: string[] = []; const optionalIssues: string[] = []; for (const pkg of input.packageStatuses) { if (!pkg.configured) coreIssues.push(`${pkg.name} is not enabled in settings.json`); if (!pkg.present) coreIssues.push(`${pkg.name} directory is missing`); } const soulRules = input.configStatuses.find((file) => file.label === "SOUL rules"); if (!soulRules?.present) { coreIssues.push("global SOUL rules file is missing"); } if (!input.memory.rulesPresent) { coreIssues.push("memory rules file is missing"); } for (const ext of input.localExtensions) { if (!ext.present) optionalIssues.push(`${ext.label} is missing`); } if (!input.rtk.available) { optionalIssues.push(`rtk binary unavailable (${input.rtk.reason})`); } if (!input.ccc.available) { optionalIssues.push(`ccc binary unavailable (${input.ccc.reason})`); } else if (!input.ccc.initialized) { optionalIssues.push("ccc project is not initialized in the current cwd"); } else if (!input.ccc.indexed) { optionalIssues.push("ccc project index has not been built yet"); } if (input.compaction.enabled && !input.compaction.ready) { optionalIssues.push("compaction has no available summarization model"); } if (!input.memory.enabled) { optionalIssues.push("memory is disabled by configuration"); } if (input.memory.enabled && !input.memory.dbPresent) { optionalIssues.push("memory database file does not exist yet"); } for (const warning of input.compaction.warnings) { optionalIssues.push(`compaction: ${warning}`); } if (input.subagents.registry.errors.length > 0) { optionalIssues.push(`subagents: ${input.subagents.registry.errors.length} YAML discovery/parsing issue(s)`); } if (input.subagents.background.error > 0) { optionalIssues.push(`subagents: ${input.subagents.background.error} background job(s) failed`); } if (input.subagents.background.aborted > 0) { optionalIssues.push(`subagents: ${input.subagents.background.aborted} background job(s) aborted`); } if (!input.web.webSearchReady) optionalIssues.push("web_search has no configured provider key"); if (!input.web.webReadReady) optionalIssues.push("web_read is not ready (missing tavily key)"); if (!input.web.docsSearchReady) optionalIssues.push("docs_search is not ready (missing context7 key)"); if (!input.web.academicSearchReady) optionalIssues.push("academic_search is not ready (missing openalex key)"); if (!input.web.documentParseReady) optionalIssues.push("document_parse is not ready (missing mineru key)"); if (!input.schemeSandbox.available) { optionalIssues.push(`scheme sandbox: WASM integrity check failed (${input.schemeSandbox.wasmIntegrity.failures.join(", ")})`); } const overallStatus: VeraOverallStatus = coreIssues.length > 0 ? "degraded" : optionalIssues.length > 0 ? "partial" : "ok"; return { overallStatus, coreIssues, optionalIssues }; } interface BuildReportInput { defaultModel: string; defaultProvider: string; packageStatuses: PackageStatus[]; configStatuses: FileStatus[]; localExtensions: FileStatus[]; web: WebToolReadiness; compaction: CompactionStatus; memory: MemoryStatus; ccc: CccStatus; rtk: { available: boolean; version: string | null; reason?: string }; subagents: SubagentSystemStatus; schemeSandbox: SchemeSandboxStatus; summary: VeraStatusSummary; colorize?: boolean; /** * Panel title for the `┌ name ┐` top border. Defaults to `"vera_status"` * so the check_vera tool's output stays unchanged for the model surface; * the `/vera` slash command overrides this to `"vera"`. */ panelName?: string; } function issueItem(label: string, issues: string[], state: PanelItemState): PanelItem { return { label, value: issues.length > 0 ? `${issues.length} issue(s)` : "clear", state, details: issues.length > 0 ? issues : undefined, }; } function buildSections(input: BuildReportInput): PanelSection[] { const sections: PanelSection[] = []; sections.push({ items: [ issueItem("core", input.summary.coreIssues, input.summary.coreIssues.length > 0 ? "bad" : "ok"), issueItem("optional", input.summary.optionalIssues, input.summary.optionalIssues.length > 0 ? "warn" : "ok"), ], }); sections.push({ heading: "COMPACTION", items: [ { label: "status", value: `${input.compaction.enabled ? "enabled" : "disabled"} · ${input.compaction.configSource}`, state: input.compaction.enabled ? "ok" : "warn", }, { label: "current model", value: input.compaction.currentModel, state: input.compaction.currentModel === "(none)" ? "warn" : "ok", }, { label: "override", value: input.compaction.override, state: "ok" }, { label: "effective model", value: input.compaction.effectiveModel, state: input.compaction.enabled ? (input.compaction.ready ? "ok" : "warn") : undefined, }, { label: "selection source", value: input.compaction.source, state: input.compaction.enabled ? (input.compaction.ready ? "ok" : "warn") : undefined, }, { label: "fallbacks", value: previewList(input.compaction.fallbackRefs), state: input.compaction.fallbackRefs.length > 0 ? "ok" : undefined, }, { label: "available models", value: `${input.compaction.availableRefs.length} · ${previewList(input.compaction.availableRefs)}`, state: input.compaction.availableRefs.length > 0 ? "ok" : "warn", }, issueItem("warnings", input.compaction.warnings, input.compaction.warnings.length > 0 ? "warn" : "ok"), ], }); sections.push({ heading: "PACKAGES", items: input.packageStatuses.map((pkg): PanelItem => ({ label: pkg.name, value: `configured=${bool(pkg.configured)} present=${bool(pkg.present)} · ${pkg.source}`, state: pkg.configured && pkg.present ? "ok" : "bad", })), }); sections.push({ heading: "MEMORY", items: [ { label: "status", value: `${input.memory.enabled ? "enabled" : "disabled"} · ${input.memory.configSource}`, state: input.memory.enabled ? "ok" : "warn", }, { label: "database", value: `${bool(input.memory.dbPresent)} · ${input.memory.dbPath}`, state: input.memory.dbPresent ? "ok" : "warn", }, { label: "short ttl days", value: String(input.memory.shortTtlDays), state: "ok" }, { label: "rules", value: input.memory.rulesPresent ? "present" : "missing", state: input.memory.rulesPresent ? "ok" : "bad", }, ], }); sections.push({ heading: "CCC", items: [ { label: "binary", value: input.ccc.available ? `available · ${input.ccc.binaryPath}` : `missing · ${input.ccc.reason}`, state: input.ccc.available ? "ok" : "warn", }, { label: "cwd", value: input.ccc.cwd, state: "ok" }, { label: "project", value: input.ccc.initialized ? "initialized" : "not initialized", state: input.ccc.available ? (input.ccc.initialized ? "ok" : "warn") : undefined, }, { label: "index", value: input.ccc.initialized ? (input.ccc.indexed ? "ready" : "not built") : "unavailable until project is initialized", state: input.ccc.available ? (input.ccc.indexed ? "ok" : "warn") : undefined, }, { label: "status", value: input.ccc.statusSummary, state: input.ccc.available ? (input.ccc.initialized && input.ccc.indexed ? "ok" : "warn") : "warn", }, ], }); const subagentItems: PanelItem[] = [ { label: "status", value: `${input.subagents.summary.overallStatus} · defs=${input.subagents.registry.total} · queued=${input.subagents.background.queued} running=${input.subagents.background.running} finished=${input.subagents.background.finished}`, state: input.subagents.summary.overallStatus === "ok" ? "ok" : "warn", }, { label: "user dir", value: input.subagents.userDir, state: "ok" }, { label: "project dir", value: input.subagents.projectDir ?? "(none)", state: input.subagents.projectDir ? "ok" : undefined, }, { label: "definition names", value: previewList(input.subagents.registry.names), state: input.subagents.registry.names.length > 0 ? "ok" : "warn", }, { label: "runtime", value: `session=${bool(input.subagents.runtime.sessionActive)} ui=${bool(input.subagents.runtime.hasUI)} indicator=${input.subagents.runtime.statusIndicator ?? "(idle)"}`, state: input.subagents.runtime.sessionActive ? "ok" : "warn", }, { label: "tools", value: input.subagents.runtime.registeredTools.join(", "), state: "ok" }, { label: "commands", value: input.subagents.runtime.registeredCommands.join(", "), state: "ok" }, ]; if (input.subagents.background.recentJobs.length > 0) { for (const job of input.subagents.background.recentJobs) { subagentItems.push({ label: job.jobId, value: `${job.status} · ${job.agent} · ${job.summary}`, state: job.status === "done" ? "ok" : job.status === "error" ? "bad" : "warn", }); } } else { subagentItems.push({ label: "recent jobs", value: "(none)" }); } subagentItems.push( issueItem("discovery errors", input.subagents.registry.errors, input.subagents.registry.errors.length > 0 ? "warn" : "ok"), ); sections.push({ heading: "SUBAGENTS", items: subagentItems }); sections.push({ heading: "SCHEME SANDBOX", items: [ { label: "status", value: input.schemeSandbox.available ? `available · Chez Scheme ${input.schemeSandbox.version} (WASM/pb)` : "unavailable", state: input.schemeSandbox.available ? "ok" : "warn", }, { label: "wasm integrity", value: input.schemeSandbox.wasmIntegrity.ok ? `verified · ${input.schemeSandbox.artifacts.length} artifacts` : input.schemeSandbox.wasmIntegrity.failures.join(", "), state: input.schemeSandbox.wasmIntegrity.ok ? "ok" : "bad", }, { label: "tool", value: "scheme_eval", state: "ok" }, { label: "access modes", value: "readonly · write · fullaccess", state: "ok" }, ], }); const localItems: PanelItem[] = input.localExtensions.map((ext): PanelItem => ({ label: ext.label, value: `present=${bool(ext.present)} · ${ext.path}`, state: ext.present ? "ok" : "warn", })); localItems.push({ label: "rtk binary", value: input.rtk.available ? `available · ${input.rtk.version}` : `missing · ${input.rtk.reason}`, state: input.rtk.available ? "ok" : "warn", }); sections.push({ heading: "LOCAL COMPAT", items: localItems }); sections.push({ heading: "WEB READINESS", items: [ { label: "configured keys", value: input.web.configuredKeys.length > 0 ? input.web.configuredKeys.join(", ") : "(none)", state: input.web.configuredKeys.length > 0 ? "ok" : "warn", }, { label: "missing keys", value: input.web.missingKeys.length > 0 ? input.web.missingKeys.join(", ") : "(none)", state: input.web.missingKeys.length > 0 ? "warn" : "ok", }, { label: "web_search", value: input.web.webSearchReady ? "ready" : "missing provider key (exa|brave|metaso|jina)", state: input.web.webSearchReady ? "ok" : "warn", }, { label: "web_read", value: input.web.webReadReady ? "ready" : "missing tavily", state: input.web.webReadReady ? "ok" : "warn" }, { label: "docs_search", value: input.web.docsSearchReady ? "ready" : "missing context7", state: input.web.docsSearchReady ? "ok" : "warn" }, { label: "academic_search", value: input.web.academicSearchReady ? "ready" : "missing openalex", state: input.web.academicSearchReady ? "ok" : "warn" }, { label: "document_parse", value: input.web.documentParseReady ? "ready" : "missing mineru", state: input.web.documentParseReady ? "ok" : "warn" }, ], }); sections.push({ heading: "CONFIG", items: input.configStatuses.map((file): PanelItem => ({ label: file.label, value: `present=${bool(file.present)} · ${file.path}`, state: file.present ? "ok" : "warn", })), }); return sections; } function buildReport(input: BuildReportInput): string { const colorize = input.colorize === true; const status: PanelStatus = input.summary.overallStatus; const modelRef = `${input.defaultProvider || "(unset)"}/${input.defaultModel || "(unset)"}`; const panel = renderCommandPanel({ name: input.panelName ?? "vera_status", status, badge: defaultStatusBadge(status), meta: modelRef, sections: buildSections(input), }); return colorize ? panel.colorText : panel.text; } async function collectVeraStatus( ctx: ExtensionContext, options: { panelName?: string } = {}, ) { const agentDir = getAgentDir(); const settings = readJsonFile(join(agentDir, "settings.json"), {}); const packageStatuses = getPackageStatuses(settings); const configStatuses = getConfigStatuses(agentDir); const localExtensions = getLocalExtensionStatuses(agentDir); const web = getWebToolReadiness(agentDir); const compaction = getCompactionStatus(ctx); const memory = getMemoryStatus(agentDir, ctx.cwd); const ccc = await probeCcc(ctx); const subagents = collectSubagentSystemStatus(ctx.cwd); const schemeSandbox = collectSchemeSandboxStatus(); const rtk = await probeRtk(); const summary = summarizeStatus({ packageStatuses, configStatuses, localExtensions, web, compaction, memory, ccc, subagents, schemeSandbox, rtk, }); const panelName = options.panelName; const text = buildReport({ defaultModel: String(settings.defaultModel ?? ""), defaultProvider: String(settings.defaultProvider ?? ""), packageStatuses, configStatuses, localExtensions, web, compaction, memory, ccc, subagents, schemeSandbox, rtk, summary, panelName, }); const colorText = buildReport({ defaultModel: String(settings.defaultModel ?? ""), defaultProvider: String(settings.defaultProvider ?? ""), packageStatuses, configStatuses, localExtensions, web, compaction, memory, ccc, subagents, schemeSandbox, rtk, summary, colorize: true, panelName, }); return { text, colorText, details: { agentDir, packageStatuses, configStatuses, localExtensions, web, compaction, memory, ccc, subagents, schemeSandbox, rtk, summary, overallStatus: summary.overallStatus, defaultModel: settings.defaultModel ?? "", defaultProvider: settings.defaultProvider ?? "", }, }; } function renderCheckVeraCall(_args: any, theme: any, ctx: any): any { const state = ctx.state as { startedAt?: number }; if (state.startedAt === undefined) state.startedAt = Date.now(); return kylinFrameForCall(ctx, { name: "check_vera", theme, status: "pending", paramSummary: theme.fg("dim", "top-level"), startedAt: state.startedAt, }); } function renderCheckVeraResult(result: any, opts: any, theme: any, ctx: any): any { const details = result.details as any; const state = ctx.state as { startedAt?: number }; const startedAt = state.startedAt; const paramSummary = theme.fg("dim", "top-level"); if (!details) { return kylinFrameForResult(ctx, { name: "check_vera", theme, status: "error", paramSummary, errorMessage: "no status report", startedAt, }); } const packages = Array.isArray(details.packageStatuses) ? details.packageStatuses.length : 0; const coreIssues = details.summary?.coreIssues?.length ?? 0; const optionalIssues = details.summary?.optionalIssues?.length ?? 0; const issues = coreIssues + optionalIssues; const overall = String(details.overallStatus ?? details.summary?.overallStatus ?? "unknown"); const statusColor = overall === "ok" ? "success" : overall === "degraded" ? "error" : "warning"; const expandedBody = opts.expanded ? String(result.content?.find?.((item: any) => item?.type === "text")?.text ?? "").split("\n") : undefined; return kylinFrameForResult(ctx, { name: "check_vera", theme, status: overall === "degraded" ? "error" : "success", paramSummary, resultSummary: theme.fg(statusColor, overall) + theme.fg("borderMuted", " · ") + theme.fg("text", `${packages} packages`) + theme.fg("borderMuted", " · ") + theme.fg(issues > 0 ? "warning" : "success", `${issues} issues`), expanded: opts.expanded, expandedBody, expandedTotalLines: expandedBody?.length, startedAt, }); } export default function checkVera(pi: ExtensionAPI) { pi.registerTool({ name: "check_vera", label: "Check Vera", description: "Summarize Vera package presence, compaction routing, memory status, subagent system status, CCC availability/project readiness, Scheme sandbox status, local compatibility extensions, config files, and web-tool readiness.", parameters: Type.Object({}), renderShell: "self", renderCall: renderCheckVeraCall, renderResult: renderCheckVeraResult, async execute(_toolCallId, _params, _signal, _onUpdate, ctx) { const result = await collectVeraStatus(ctx); return { content: [{ type: "text" as const, text: result.text }], details: result.details, }; }, }); pi.registerCommand("vera", { description: "Show top-level Vera runtime status, including compaction routing, subagent system status, CCC readiness, Scheme sandbox status, memory status, and overall health.", handler: async (_args, ctx) => { const result = await collectVeraStatus(ctx, { panelName: "vera" }); notify(ctx, result.colorText, result.details.overallStatus === "degraded" ? "warning" : "info"); }, }); }